Coverage Report

Created: 2026-09-15 13:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/cloud/src/recycler/recycler.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/recycler.h"
19
20
#include <brpc/builtin_service.pb.h>
21
#include <brpc/server.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <bvar/status.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
28
#include <algorithm>
29
#include <atomic>
30
#include <chrono>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstdlib>
34
#include <deque>
35
#include <functional>
36
#include <initializer_list>
37
#include <memory>
38
#include <numeric>
39
#include <optional>
40
#include <random>
41
#include <string>
42
#include <string_view>
43
#include <thread>
44
#include <unordered_map>
45
#include <unordered_set>
46
#include <utility>
47
#include <variant>
48
49
#include "common/defer.h"
50
#include "common/stopwatch.h"
51
#include "meta-service/meta_service.h"
52
#include "meta-service/meta_service_helper.h"
53
#include "meta-service/meta_service_schema.h"
54
#include "meta-store/blob_message.h"
55
#include "meta-store/meta_reader.h"
56
#include "meta-store/txn_kv.h"
57
#include "meta-store/txn_kv_error.h"
58
#include "meta-store/versioned_value.h"
59
#include "recycler/checker.h"
60
#ifdef ENABLE_HDFS_STORAGE_VAULT
61
#include "recycler/hdfs_accessor.h"
62
#endif
63
#include "recycler/s3_accessor.h"
64
#include "recycler/storage_vault_accessor.h"
65
#ifdef UNIT_TEST
66
#include "../test/mock_accessor.h"
67
#endif
68
#include "common/bvars.h"
69
#include "common/config.h"
70
#include "common/encryption_util.h"
71
#include "common/logging.h"
72
#include "common/rowset_segment_id.h"
73
#include "common/simple_thread_pool.h"
74
#include "common/util.h"
75
#include "cpp/sync_point.h"
76
#include "meta-store/codec.h"
77
#include "meta-store/document_message.h"
78
#include "meta-store/keys.h"
79
#include "recycler/recycler_service.h"
80
#include "recycler/sync_executor.h"
81
#include "recycler/util.h"
82
#include "snapshot/snapshot_manager_factory.h"
83
84
namespace doris::cloud {
85
86
using namespace std::chrono;
87
88
namespace {
89
90
constexpr size_t kRowsetBatchGetSize = 256;
91
92
0
int64_t packed_file_retry_sleep_ms() {
93
0
    const int64_t min_ms = std::max<int64_t>(0, config::packed_file_txn_retry_sleep_min_ms);
94
0
    const int64_t max_ms = std::max<int64_t>(min_ms, config::packed_file_txn_retry_sleep_max_ms);
95
0
    thread_local std::mt19937_64 gen(std::random_device {}());
96
0
    std::uniform_int_distribution<int64_t> dist(min_ms, max_ms);
97
0
    return dist(gen);
98
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_126packed_file_retry_sleep_msEv
99
100
0
void sleep_for_packed_file_retry() {
101
0
    std::this_thread::sleep_for(std::chrono::milliseconds(packed_file_retry_sleep_ms()));
102
0
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
Unexecuted instantiation: recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_127sleep_for_packed_file_retryEv
103
104
869k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
869k
    const auto& locations = rowset.packed_slice_locations();
106
869k
    auto it = locations.find(path);
107
869k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
869k
           !it->second.packed_file_path().empty();
109
869k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
104
7
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
7
    const auto& locations = rowset.packed_slice_locations();
106
7
    auto it = locations.find(path);
107
7
    return it != locations.end() && it->second.has_packed_file_path() &&
108
7
           !it->second.packed_file_path().empty();
109
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_120is_packed_slice_pathERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
104
869k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
869k
    const auto& locations = rowset.packed_slice_locations();
106
869k
    auto it = locations.find(path);
107
869k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
869k
           !it->second.packed_file_path().empty();
109
869k
}
110
111
void add_file_to_delete_if_not_packed(const doris::RowsetMetaCloudPB& rowset,
112
                                      const std::string& path,
113
869k
                                      std::vector<std::string>* file_paths) {
114
870k
    if (!is_packed_slice_path(rowset, path)) {
115
870k
        file_paths->push_back(path);
116
870k
    }
117
869k
}
recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
113
7
                                      std::vector<std::string>* file_paths) {
114
7
    if (!is_packed_slice_path(rowset, path)) {
115
7
        file_paths->push_back(path);
116
7
    }
117
7
}
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_132add_file_to_delete_if_not_packedERKNS_17RowsetMetaCloudPBERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPSt6vectorISA_SaISA_EE
Line
Count
Source
113
869k
                                      std::vector<std::string>* file_paths) {
114
870k
    if (!is_packed_slice_path(rowset, path)) {
115
870k
        file_paths->push_back(path);
116
870k
    }
117
869k
}
118
119
37
bool filter_out_instance(const std::string& instance_id) {
120
37
    if (config::recycle_whitelist.empty()) {
121
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
122
35
               config::recycle_blacklist.end();
123
35
    }
124
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
125
2
           config::recycle_whitelist.end();
126
37
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
recycler_test.cpp:_ZN5doris5cloud12_GLOBAL__N_119filter_out_instanceERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
119
37
bool filter_out_instance(const std::string& instance_id) {
120
37
    if (config::recycle_whitelist.empty()) {
121
35
        return std::ranges::find(config::recycle_blacklist, instance_id) !=
122
35
               config::recycle_blacklist.end();
123
35
    }
124
2
    return std::ranges::find(config::recycle_whitelist, instance_id) ==
125
2
           config::recycle_whitelist.end();
126
37
}
127
128
} // namespace
129
130
// return 0 for success get a key, 1 for key not found, negative for error
131
18
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
18
    std::unique_ptr<Transaction> txn;
133
18
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
18
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
18
    switch (txn->get(key, &val, true)) {
138
8
    case TxnErrorCode::TXN_OK:
139
8
        return 0;
140
10
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
10
        return 1;
142
0
    default:
143
0
        return -1;
144
18
    };
145
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
131
10
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
10
    std::unique_ptr<Transaction> txn;
133
10
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
10
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
10
    switch (txn->get(key, &val, true)) {
138
3
    case TxnErrorCode::TXN_OK:
139
3
        return 0;
140
7
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
7
        return 1;
142
0
    default:
143
0
        return -1;
144
10
    };
145
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEERNSt7__cxx1112basic_stringIcS5_SaIcEEE
Line
Count
Source
131
8
[[maybe_unused]] static int txn_get(TxnKv* txn_kv, std::string_view key, std::string& val) {
132
8
    std::unique_ptr<Transaction> txn;
133
8
    TxnErrorCode err = txn_kv->create_txn(&txn);
134
8
    if (err != TxnErrorCode::TXN_OK) {
135
0
        return -1;
136
0
    }
137
8
    switch (txn->get(key, &val, true)) {
138
5
    case TxnErrorCode::TXN_OK:
139
5
        return 0;
140
3
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
141
3
        return 1;
142
0
    default:
143
0
        return -1;
144
8
    };
145
0
}
146
147
// 0 for success, negative for error
148
static int txn_get(TxnKv* txn_kv, std::string_view begin, std::string_view end,
149
380
                   std::unique_ptr<RangeGetIterator>& it) {
150
380
    std::unique_ptr<Transaction> txn;
151
380
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
380
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
380
    switch (txn->get(begin, end, &it, true)) {
156
380
    case TxnErrorCode::TXN_OK:
157
380
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
380
    };
163
0
}
recycler.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
149
39
                   std::unique_ptr<RangeGetIterator>& it) {
150
39
    std::unique_ptr<Transaction> txn;
151
39
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
39
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
39
    switch (txn->get(begin, end, &it, true)) {
156
39
    case TxnErrorCode::TXN_OK:
157
39
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
39
    };
163
0
}
recycler_test.cpp:_ZN5doris5cloudL7txn_getEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_RSt10unique_ptrINS0_16RangeGetIteratorESt14default_deleteIS8_EE
Line
Count
Source
149
341
                   std::unique_ptr<RangeGetIterator>& it) {
150
341
    std::unique_ptr<Transaction> txn;
151
341
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
341
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
341
    switch (txn->get(begin, end, &it, true)) {
156
341
    case TxnErrorCode::TXN_OK:
157
341
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
341
    };
163
0
}
164
165
// return 0 for success otherwise error
166
22
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
22
    std::unique_ptr<Transaction> txn;
168
22
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
22
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
20.0k
    for (auto k : keys) {
173
20.0k
        txn->remove(k);
174
20.0k
    }
175
22
    switch (txn->commit()) {
176
22
    case TxnErrorCode::TXN_OK:
177
22
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
22
    }
183
22
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
166
5
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
5
    std::unique_ptr<Transaction> txn;
168
5
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
5
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
5
    for (auto k : keys) {
173
5
        txn->remove(k);
174
5
    }
175
5
    switch (txn->commit()) {
176
5
    case TxnErrorCode::TXN_OK:
177
5
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
5
    }
183
5
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorISt17basic_string_viewIcSt11char_traitsIcEESaIS7_EE
Line
Count
Source
166
17
static int txn_remove(TxnKv* txn_kv, std::vector<std::string_view> keys) {
167
17
    std::unique_ptr<Transaction> txn;
168
17
    TxnErrorCode err = txn_kv->create_txn(&txn);
169
17
    if (err != TxnErrorCode::TXN_OK) {
170
0
        return -1;
171
0
    }
172
20.0k
    for (auto k : keys) {
173
20.0k
        txn->remove(k);
174
20.0k
    }
175
17
    switch (txn->commit()) {
176
17
    case TxnErrorCode::TXN_OK:
177
17
        return 0;
178
0
    case TxnErrorCode::TXN_CONFLICT:
179
0
        return -1;
180
0
    default:
181
0
        return -1;
182
17
    }
183
17
}
184
185
// return 0 for success otherwise error
186
385
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
385
    std::unique_ptr<Transaction> txn;
188
385
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
385
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
106k
    for (auto& k : keys) {
193
106k
        txn->remove(k);
194
106k
    }
195
385
    switch (txn->commit()) {
196
385
    case TxnErrorCode::TXN_OK:
197
385
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
385
    }
203
385
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
186
40
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
40
    std::unique_ptr<Transaction> txn;
188
40
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
40
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
40
    for (auto& k : keys) {
193
17
        txn->remove(k);
194
17
    }
195
40
    switch (txn->commit()) {
196
40
    case TxnErrorCode::TXN_OK:
197
40
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
40
    }
203
40
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EE
Line
Count
Source
186
345
static int txn_remove(TxnKv* txn_kv, std::vector<std::string> keys) {
187
345
    std::unique_ptr<Transaction> txn;
188
345
    TxnErrorCode err = txn_kv->create_txn(&txn);
189
345
    if (err != TxnErrorCode::TXN_OK) {
190
0
        return -1;
191
0
    }
192
106k
    for (auto& k : keys) {
193
106k
        txn->remove(k);
194
106k
    }
195
345
    switch (txn->commit()) {
196
345
    case TxnErrorCode::TXN_OK:
197
345
        return 0;
198
0
    case TxnErrorCode::TXN_CONFLICT:
199
0
        return -1;
200
0
    default:
201
0
        return -1;
202
345
    }
203
345
}
204
205
// return 0 for success otherwise error
206
[[maybe_unused]] static int txn_remove(TxnKv* txn_kv, std::string_view begin,
207
102k
                                       std::string_view end) {
208
102k
    std::unique_ptr<Transaction> txn;
209
102k
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
102k
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
102k
    txn->remove(begin, end);
214
102k
    switch (txn->commit()) {
215
102k
    case TxnErrorCode::TXN_OK:
216
102k
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
102k
    }
222
102k
}
recycler.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
207
14
                                       std::string_view end) {
208
14
    std::unique_ptr<Transaction> txn;
209
14
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
14
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
14
    txn->remove(begin, end);
214
14
    switch (txn->commit()) {
215
14
    case TxnErrorCode::TXN_OK:
216
14
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
14
    }
222
14
}
recycler_test.cpp:_ZN5doris5cloudL10txn_removeEPNS0_5TxnKvESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
207
102k
                                       std::string_view end) {
208
102k
    std::unique_ptr<Transaction> txn;
209
102k
    TxnErrorCode err = txn_kv->create_txn(&txn);
210
102k
    if (err != TxnErrorCode::TXN_OK) {
211
0
        return -1;
212
0
    }
213
102k
    txn->remove(begin, end);
214
102k
    switch (txn->commit()) {
215
102k
    case TxnErrorCode::TXN_OK:
216
102k
        return 0;
217
0
    case TxnErrorCode::TXN_CONFLICT:
218
0
        return -1;
219
0
    default:
220
0
        return -1;
221
102k
    }
222
102k
}
223
224
// Remove versioned delete bitmap keys grouped by rowset.
225
// Each inner vector represents all DBM shard keys for one rowset that MUST be deleted
226
// atomically in the same txn. Transaction splitting only occurs between rowsets, never
227
// within a rowset's shard keys.
228
//
229
// This ensures that a DBM blob with multiple shards is either fully deleted or not
230
// deleted at all, preventing partial deletion that would leave the blob unrecoverable.
231
//
232
// return 0 for success otherwise error
233
static int delete_versioned_delete_bitmap_by_rowset(
234
15
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
235
15
    if (rowset_dbm_key_groups.empty()) {
236
1
        return 0;
237
1
    }
238
14
    size_t idx = 0;
239
29
    while (idx < rowset_dbm_key_groups.size()) {
240
15
        std::unique_ptr<Transaction> txn;
241
15
        TxnErrorCode err = txn_kv->create_txn(&txn);
242
15
        if (err != TxnErrorCode::TXN_OK) {
243
0
            return -1;
244
0
        }
245
246
15
        bool has_keys = false;
247
1.58k
        while (idx < rowset_dbm_key_groups.size()) {
248
1.57k
            const auto& keys = rowset_dbm_key_groups[idx];
249
1.57k
            const auto keys_bytes =
250
1.57k
                    std::accumulate(keys.begin(), keys.end(), size_t {0},
251
1.61k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EEENK3$_0clIS9_EEDamRKT_
recycler_test.cpp:_ZZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EEENK3$_0clIS9_EEDamRKT_
Line
Count
Source
251
1.61k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
252
253
1.57k
            if (has_keys && txn->approximate_bytes() + keys_bytes >= config::max_txn_commit_byte) {
254
1
                break;
255
1
            }
256
257
1.60k
            for (const auto& key : keys) {
258
1.60k
                txn->remove(key);
259
1.60k
            }
260
261
1.56k
            has_keys = true;
262
1.56k
            ++idx;
263
1.56k
        }
264
265
15
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
266
15
        err = txn->commit();
267
15
        if (err != TxnErrorCode::TXN_OK) {
268
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
269
0
            return -1;
270
0
        }
271
15
    }
272
14
    return 0;
273
14
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EE
recycler_test.cpp:_ZN5doris5cloudL40delete_versioned_delete_bitmap_by_rowsetEPNS0_5TxnKvERKSt6vectorIS3_INSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS9_EESaISB_EE
Line
Count
Source
234
15
        TxnKv* txn_kv, const std::vector<std::vector<std::string>>& rowset_dbm_key_groups) {
235
15
    if (rowset_dbm_key_groups.empty()) {
236
1
        return 0;
237
1
    }
238
14
    size_t idx = 0;
239
29
    while (idx < rowset_dbm_key_groups.size()) {
240
15
        std::unique_ptr<Transaction> txn;
241
15
        TxnErrorCode err = txn_kv->create_txn(&txn);
242
15
        if (err != TxnErrorCode::TXN_OK) {
243
0
            return -1;
244
0
        }
245
246
15
        bool has_keys = false;
247
1.58k
        while (idx < rowset_dbm_key_groups.size()) {
248
1.57k
            const auto& keys = rowset_dbm_key_groups[idx];
249
1.57k
            const auto keys_bytes =
250
1.57k
                    std::accumulate(keys.begin(), keys.end(), size_t {0},
251
1.57k
                                    [](size_t sum, const auto& key) { return sum + key.size(); });
252
253
1.57k
            if (has_keys && txn->approximate_bytes() + keys_bytes >= config::max_txn_commit_byte) {
254
1
                break;
255
1
            }
256
257
1.60k
            for (const auto& key : keys) {
258
1.60k
                txn->remove(key);
259
1.60k
            }
260
261
1.56k
            has_keys = true;
262
1.56k
            ++idx;
263
1.56k
        }
264
265
15
        TEST_SYNC_POINT_CALLBACK("delete_versioned_delete_bitmap_by_rowset::commit_result");
266
15
        err = txn->commit();
267
15
        if (err != TxnErrorCode::TXN_OK) {
268
0
            LOG(WARNING) << "failed to remove delete bitmap keys, err=" << err;
269
0
            return -1;
270
0
        }
271
15
    }
272
14
    return 0;
273
14
}
274
275
void scan_restore_job_rowset(
276
        Transaction* txn, const std::string& instance_id, int64_t tablet_id, MetaServiceCode& code,
277
        std::string& msg,
278
        std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>>* restore_job_rs_metas);
279
280
static inline void check_recycle_task(const std::string& instance_id, const std::string& task_name,
281
                                      int64_t num_scanned, int64_t num_recycled,
282
64
                                      int64_t start_time) {
283
64
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
284
0
        int64_t cost =
285
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
286
0
        if (cost > config::recycle_task_threshold_seconds) {
287
0
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
288
0
                    .tag("instance_id", instance_id)
289
0
                    .tag("task", task_name)
290
0
                    .tag("num_scanned", num_scanned)
291
0
                    .tag("num_recycled", num_recycled);
292
0
        }
293
0
    }
294
64
    return;
295
64
}
recycler.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
282
5
                                      int64_t start_time) {
283
5
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
284
0
        int64_t cost =
285
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
286
0
        if (cost > config::recycle_task_threshold_seconds) {
287
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
288
0
                    .tag("instance_id", instance_id)
289
0
                    .tag("task", task_name)
290
0
                    .tag("num_scanned", num_scanned)
291
0
                    .tag("num_recycled", num_recycled);
292
0
        }
293
0
    }
294
5
    return;
295
5
}
recycler_test.cpp:_ZN5doris5cloudL18check_recycle_taskERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_lll
Line
Count
Source
282
59
                                      int64_t start_time) {
283
59
    if ((num_scanned % 10000) == 0 && (num_scanned > 0)) [[unlikely]] {
284
0
        int64_t cost =
285
0
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
286
0
        if (cost > config::recycle_task_threshold_seconds) {
287
            LOG_WARNING("recycle task cost too much time cost={}s", cost)
288
0
                    .tag("instance_id", instance_id)
289
0
                    .tag("task", task_name)
290
0
                    .tag("num_scanned", num_scanned)
291
0
                    .tag("num_recycled", num_recycled);
292
0
        }
293
0
    }
294
59
    return;
295
59
}
296
297
6
Recycler::Recycler(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
298
6
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
299
300
6
    auto s3_producer_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
301
6
                                                               "s3_producer_pool");
302
6
    s3_producer_pool->start();
303
6
    auto recycle_tablet_pool = std::make_shared<SimpleThreadPool>(config::recycle_pool_parallelism,
304
6
                                                                  "recycle_tablet_pool");
305
6
    recycle_tablet_pool->start();
306
6
    auto group_recycle_function_pool = std::make_shared<SimpleThreadPool>(
307
6
            config::recycle_pool_parallelism, "group_recycle_function_pool");
308
6
    group_recycle_function_pool->start();
309
6
    _thread_pool_group =
310
6
            RecyclerThreadPoolGroup(std::move(s3_producer_pool), std::move(recycle_tablet_pool),
311
6
                                    std::move(group_recycle_function_pool));
312
313
6
    auto resource_mgr = std::make_shared<ResourceManager>(txn_kv_);
314
6
    txn_lazy_committer_ = std::make_shared<TxnLazyCommitter>(txn_kv_, std::move(resource_mgr));
315
6
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
316
6
}
317
318
6
Recycler::~Recycler() {
319
6
    if (!stopped()) {
320
0
        stop();
321
0
    }
322
6
}
323
324
5
void Recycler::instance_scanner_callback() {
325
    // sleep 60 seconds before scheduling for the launch procedure to complete:
326
    // some bad hdfs connection may cause some log to stdout stderr
327
    // which may pollute .out file and affect the script to check success
328
5
    std::this_thread::sleep_for(
329
5
            std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
330
637
    while (!stopped()) {
331
632
        if (config::enable_recycler) {
332
4
            std::vector<InstanceInfoPB> instances;
333
4
            get_all_instances(txn_kv_.get(), instances);
334
            // TODO(plat1ko): delete job recycle kv of non-existent instances
335
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
336
4
                std::stringstream ss;
337
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
338
4
                return ss.str();
339
4
            }();
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_0clB5cxx11Ev
Line
Count
Source
335
4
            LOG(INFO) << "Recycler get instances: " << [&instances] {
336
4
                std::stringstream ss;
337
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
338
4
                return ss.str();
339
4
            }();
340
4
            if (!instances.empty()) {
341
                // enqueue instances
342
3
                std::lock_guard lock(mtx_);
343
30
                for (auto& instance : instances) {
344
30
                    if (filter_out_instance(instance.instance_id())) continue;
345
30
                    auto [_, success] = pending_instance_set_.insert(instance.instance_id());
346
                    // skip instance already in pending queue
347
30
                    if (success) {
348
30
                        pending_instance_queue_.push_back(std::move(instance));
349
30
                    }
350
30
                }
351
3
                pending_instance_cond_.notify_all();
352
3
            }
353
628
        } else {
354
628
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
355
628
        }
356
632
        {
357
632
            std::unique_lock lock(mtx_);
358
632
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
359
1.26k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
359
1.26k
                               [&]() { return stopped(); });
360
632
        }
361
632
    }
362
5
}
363
364
9
void Recycler::recycle_callback() {
365
40
    while (!stopped()) {
366
38
        InstanceInfoPB instance;
367
38
        {
368
38
            std::unique_lock lock(mtx_);
369
38
            pending_instance_cond_.wait(
370
51
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
370
51
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
371
38
            if (stopped()) {
372
7
                return;
373
7
            }
374
31
            instance = std::move(pending_instance_queue_.front());
375
31
            pending_instance_queue_.pop_front();
376
31
            pending_instance_set_.erase(instance.instance_id());
377
31
        }
378
0
        auto& instance_id = instance.instance_id();
379
31
        {
380
31
            std::lock_guard lock(mtx_);
381
            // skip instance in recycling
382
31
            if (recycling_instance_map_.count(instance_id)) continue;
383
31
        }
384
31
        if (!config::enable_recycler) {
385
1
            LOG(WARNING) << "Skip recycle instance_id=" << instance_id
386
1
                         << " since enable_recycler is false";
387
1
            continue;
388
1
        }
389
30
        auto instance_recycler = std::make_shared<InstanceRecycler>(
390
30
                txn_kv_, instance, _thread_pool_group, txn_lazy_committer_);
391
392
30
        if (int r = instance_recycler->init(); r != 0) {
393
0
            LOG(WARNING) << "failed to init instance recycler, instance_id=" << instance_id
394
0
                         << " ret=" << r;
395
0
            continue;
396
0
        }
397
30
        std::string recycle_job_key;
398
30
        job_recycle_key({instance_id}, &recycle_job_key);
399
30
        int ret = prepare_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id,
400
30
                                               ip_port_, config::recycle_interval_seconds * 1000);
401
30
        if (ret != 0) { // Prepare failed
402
20
            LOG(WARNING) << "failed to prepare recycle_job, instance_id=" << instance_id
403
20
                         << " ret=" << ret;
404
20
            continue;
405
20
        } else {
406
10
            std::lock_guard lock(mtx_);
407
10
            recycling_instance_map_.emplace(instance_id, instance_recycler);
408
10
        }
409
10
        if (stopped()) return;
410
10
        LOG_WARNING("begin to recycle instance").tag("instance_id", instance_id);
411
10
        auto ctime_ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
412
10
        g_bvar_recycler_instance_recycle_start_ts.put({instance_id}, ctime_ms);
413
10
        g_bvar_recycler_instance_recycle_task_status.put({"submitted"}, 1);
414
10
        ret = instance_recycler->do_recycle();
415
        // If instance recycler has been aborted, don't finish this job
416
417
10
        if (!instance_recycler->stopped()) {
418
10
            finish_instance_recycle_job(txn_kv_.get(), recycle_job_key, instance_id, ip_port_,
419
10
                                        ret == 0, ctime_ms);
420
10
        }
421
10
        if (instance_recycler->stopped() || ret != 0) {
422
0
            g_bvar_recycler_instance_recycle_task_status.put({"error"}, 1);
423
0
        }
424
10
        {
425
10
            std::lock_guard lock(mtx_);
426
10
            recycling_instance_map_.erase(instance_id);
427
10
        }
428
429
10
        auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
430
10
        auto elpased_ms = now - ctime_ms;
431
10
        g_bvar_recycler_instance_recycle_end_ts.put({instance_id}, now);
432
10
        g_bvar_recycler_instance_last_round_recycle_duration.put({instance_id}, elpased_ms);
433
10
        g_bvar_recycler_instance_next_ts.put({instance_id},
434
10
                                             now + config::recycle_interval_seconds * 1000);
435
10
        g_bvar_recycler_instance_recycle_task_status.put({"completed"}, 1);
436
10
        LOG(INFO) << "recycle instance done, "
437
10
                  << "instance_id=" << instance_id << " ret=" << ret << " ctime_ms: " << ctime_ms
438
10
                  << " now: " << now;
439
440
10
        g_bvar_recycler_instance_recycle_last_success_ts.put({instance_id}, now);
441
442
10
        LOG_WARNING("finish recycle instance")
443
10
                .tag("instance_id", instance_id)
444
10
                .tag("cost_ms", elpased_ms);
445
10
    }
446
9
}
447
448
4
void Recycler::lease_recycle_jobs() {
449
54
    while (!stopped()) {
450
50
        std::vector<std::string> instances;
451
50
        instances.reserve(recycling_instance_map_.size());
452
50
        {
453
50
            std::lock_guard lock(mtx_);
454
50
            for (auto& [id, _] : recycling_instance_map_) {
455
30
                instances.push_back(id);
456
30
            }
457
50
        }
458
50
        for (auto& i : instances) {
459
30
            std::string recycle_job_key;
460
30
            job_recycle_key({i}, &recycle_job_key);
461
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), recycle_job_key, i, ip_port_);
462
30
            if (ret == 1) {
463
0
                std::lock_guard lock(mtx_);
464
0
                if (auto it = recycling_instance_map_.find(i);
465
0
                    it != recycling_instance_map_.end()) {
466
0
                    it->second->stop();
467
0
                }
468
0
            }
469
30
        }
470
50
        {
471
50
            std::unique_lock lock(mtx_);
472
50
            notifier_.wait_for(lock,
473
50
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
474
100
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler18lease_recycle_jobsEvENK3$_0clEv
Line
Count
Source
474
100
                               [&]() { return stopped(); });
475
50
        }
476
50
    }
477
4
}
478
479
4
void Recycler::check_recycle_tasks() {
480
7
    while (!stopped()) {
481
3
        std::unordered_map<std::string, std::shared_ptr<InstanceRecycler>> recycling_instance_map;
482
3
        {
483
3
            std::lock_guard lock(mtx_);
484
3
            recycling_instance_map = recycling_instance_map_;
485
3
        }
486
3
        for (auto& entry : recycling_instance_map) {
487
0
            entry.second->check_recycle_tasks();
488
0
        }
489
490
3
        std::unique_lock lock(mtx_);
491
3
        notifier_.wait_for(lock, std::chrono::seconds(config::check_recycle_task_interval_seconds),
492
6
                           [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler19check_recycle_tasksEvENK3$_0clEv
Line
Count
Source
492
6
                           [&]() { return stopped(); });
493
3
    }
494
4
}
495
496
4
int Recycler::start(brpc::Server* server) {
497
4
    g_bvar_recycler_task_max_concurrency.set_value(config::recycle_concurrency);
498
4
    S3Environment::getInstance();
499
500
4
    if (config::enable_checker) {
501
0
        checker_ = std::make_unique<Checker>(txn_kv_);
502
0
        int ret = checker_->start();
503
0
        std::string msg;
504
0
        if (ret != 0) {
505
0
            msg = "failed to start checker";
506
0
            LOG(ERROR) << msg;
507
0
            std::cerr << msg << std::endl;
508
0
            return ret;
509
0
        }
510
0
        msg = "checker started";
511
0
        LOG(INFO) << msg;
512
0
        std::cout << msg << std::endl;
513
0
    }
514
515
4
    if (server) {
516
        // Add service
517
1
        auto recycler_service =
518
1
                new RecyclerServiceImpl(txn_kv_, this, checker_.get(), txn_lazy_committer_);
519
1
        server->AddService(recycler_service, brpc::SERVER_OWNS_SERVICE);
520
1
    }
521
522
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_0clEv
Line
Count
Source
522
4
    workers_.emplace_back([this] { instance_scanner_callback(); });
523
12
    for (int i = 0; i < config::recycle_concurrency; ++i) {
524
8
        workers_.emplace_back([this] { recycle_callback(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler5startEPN4brpc6ServerEENK3$_1clEv
Line
Count
Source
524
8
        workers_.emplace_back([this] { recycle_callback(); });
525
8
    }
526
527
4
    workers_.emplace_back(std::mem_fn(&Recycler::lease_recycle_jobs), this);
528
4
    workers_.emplace_back(std::mem_fn(&Recycler::check_recycle_tasks), this);
529
530
4
    if (config::enable_snapshot_data_migrator) {
531
0
        snapshot_data_migrator_ = std::make_shared<SnapshotDataMigrator>(txn_kv_);
532
0
        int ret = snapshot_data_migrator_->start();
533
0
        if (ret != 0) {
534
0
            LOG(ERROR) << "failed to start snapshot data migrator";
535
0
            return ret;
536
0
        }
537
0
        LOG(INFO) << "snapshot data migrator started";
538
0
    }
539
540
4
    if (config::enable_snapshot_chain_compactor) {
541
0
        snapshot_chain_compactor_ = std::make_shared<SnapshotChainCompactor>(txn_kv_);
542
0
        int ret = snapshot_chain_compactor_->start();
543
0
        if (ret != 0) {
544
0
            LOG(ERROR) << "failed to start snapshot chain compactor";
545
0
            return ret;
546
0
        }
547
0
        LOG(INFO) << "snapshot chain compactor started";
548
0
    }
549
550
4
    return 0;
551
4
}
552
553
4
void Recycler::stop() {
554
4
    stopped_ = true;
555
4
    notifier_.notify_all();
556
4
    pending_instance_cond_.notify_all();
557
4
    {
558
4
        std::lock_guard lock(mtx_);
559
4
        for (auto& [_, recycler] : recycling_instance_map_) {
560
0
            recycler->stop();
561
0
        }
562
4
    }
563
20
    for (auto& w : workers_) {
564
20
        if (w.joinable()) w.join();
565
20
    }
566
4
    if (checker_) {
567
0
        checker_->stop();
568
0
    }
569
4
    if (snapshot_data_migrator_) {
570
0
        snapshot_data_migrator_->stop();
571
0
    }
572
4
    if (snapshot_chain_compactor_) {
573
0
        snapshot_chain_compactor_->stop();
574
0
    }
575
4
}
576
577
class InstanceRecycler::InvertedIndexIdCache {
578
public:
579
    InvertedIndexIdCache(std::string instance_id, std::shared_ptr<TxnKv> txn_kv)
580
184
            : instance_id_(std::move(instance_id)), txn_kv_(std::move(txn_kv)) {}
581
582
    // Return 0 if success, 1 if schema kv not found, negative for error
583
    // For the same index_id, schema_version, res, since `get` is not completely atomic
584
    // one thread has not finished inserting, and another thread has not get the index_id and schema_version,
585
    // resulting in repeated addition and inaccuracy.
586
    // however, this approach can reduce the lock range and sacrifice a bit of meta repeated get to improve concurrency performance.
587
    // repeated addition does not affect correctness.
588
28.4k
    int get(int64_t index_id, int32_t schema_version, InvertedIndexInfo& res) {
589
28.4k
        {
590
28.4k
            std::lock_guard lock(mtx_);
591
28.4k
            if (schemas_without_inverted_index_.count({index_id, schema_version})) {
592
4.67k
                return 0;
593
4.67k
            }
594
23.7k
            if (auto it = inverted_index_id_map_.find({index_id, schema_version});
595
23.7k
                it != inverted_index_id_map_.end()) {
596
18.1k
                res = it->second;
597
18.1k
                return 0;
598
18.1k
            }
599
23.7k
        }
600
        // Get schema from kv
601
        // TODO(plat1ko): Single flight
602
5.54k
        std::unique_ptr<Transaction> txn;
603
5.54k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
604
5.54k
        if (err != TxnErrorCode::TXN_OK) {
605
0
            LOG(WARNING) << "failed to create txn, err=" << err;
606
0
            return -1;
607
0
        }
608
5.54k
        auto schema_key = meta_schema_key({instance_id_, index_id, schema_version});
609
5.54k
        ValueBuf val_buf;
610
5.54k
        err = cloud::blob_get(txn.get(), schema_key, &val_buf);
611
5.54k
        if (err != TxnErrorCode::TXN_OK) {
612
500
            LOG(WARNING) << "failed to get schema, err=" << err;
613
500
            return static_cast<int>(err);
614
500
        }
615
5.04k
        doris::TabletSchemaCloudPB schema;
616
5.04k
        if (!parse_schema_value(val_buf, &schema)) {
617
0
            LOG(WARNING) << "malformed schema value, key=" << hex(schema_key);
618
0
            return -1;
619
0
        }
620
5.04k
        if (schema.index_size() > 0) {
621
4.01k
            InvertedIndexStorageFormatPB index_format = InvertedIndexStorageFormatPB::V1;
622
4.01k
            if (schema.has_inverted_index_storage_format()) {
623
4.00k
                index_format = schema.inverted_index_storage_format();
624
4.00k
            }
625
4.01k
            res.first = index_format;
626
4.01k
            res.second.reserve(schema.index_size());
627
10.0k
            for (auto& i : schema.index()) {
628
10.0k
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
629
10.0k
                    res.second.push_back(std::make_pair(i.index_id(), i.index_suffix_name()));
630
10.0k
                }
631
10.0k
            }
632
4.01k
        }
633
5.04k
        insert(index_id, schema_version, res);
634
5.04k
        return 0;
635
5.04k
    }
636
637
    // Empty `ids` means this schema has no inverted index
638
5.04k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
639
5.04k
        if (index_info.second.empty()) {
640
1.02k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert1");
641
1.02k
            std::lock_guard lock(mtx_);
642
1.02k
            schemas_without_inverted_index_.emplace(index_id, schema_version);
643
4.01k
        } else {
644
4.01k
            TEST_SYNC_POINT("InvertedIndexIdCache::insert2");
645
4.01k
            std::lock_guard lock(mtx_);
646
4.01k
            inverted_index_id_map_.try_emplace({index_id, schema_version}, index_info);
647
4.01k
        }
648
5.04k
    }
649
650
private:
651
    std::string instance_id_;
652
    std::shared_ptr<TxnKv> txn_kv_;
653
654
    std::mutex mtx_;
655
    using Key = std::pair<int64_t, int32_t>; // <index_id, schema_version>
656
    struct HashOfKey {
657
57.1k
        size_t operator()(const Key& key) const {
658
57.1k
            size_t seed = 0;
659
57.1k
            seed = std::hash<int64_t> {}(key.first);
660
57.1k
            seed = std::hash<int32_t> {}(key.second);
661
57.1k
            return seed;
662
57.1k
        }
663
    };
664
    // <index_id, schema_version> -> inverted_index_ids
665
    std::unordered_map<Key, InvertedIndexInfo, HashOfKey> inverted_index_id_map_;
666
    // Store <index_id, schema_version> of schema which doesn't have inverted index
667
    std::unordered_set<Key, HashOfKey> schemas_without_inverted_index_;
668
};
669
670
InstanceRecycler::InstanceRecycler(std::shared_ptr<TxnKv> txn_kv, const InstanceInfoPB& instance,
671
                                   RecyclerThreadPoolGroup thread_pool_group,
672
                                   std::shared_ptr<TxnLazyCommitter> txn_lazy_committer)
673
184
        : txn_kv_(std::move(txn_kv)),
674
184
          instance_id_(instance.instance_id()),
675
184
          instance_info_(instance),
676
184
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
677
184
          _thread_pool_group(std::move(thread_pool_group)),
678
184
          txn_lazy_committer_(std::move(txn_lazy_committer)),
679
184
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
680
184
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)) {
681
184
    delete_bitmap_lock_white_list_->init();
682
184
    resource_mgr_->init();
683
684
184
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
685
686
    // Since the recycler's resource manager could not be notified when instance info changes,
687
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
688
184
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
689
184
};
690
691
184
InstanceRecycler::~InstanceRecycler() = default;
692
693
152
int InstanceRecycler::init_obj_store_accessors() {
694
152
    for (const auto& obj_info : instance_info_.obj_info()) {
695
104
#ifdef UNIT_TEST
696
104
        auto accessor = std::make_shared<MockAccessor>();
697
#else
698
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
699
        if (!s3_conf) {
700
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
701
            return -1;
702
        }
703
704
        std::shared_ptr<S3Accessor> accessor;
705
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
706
        if (ret != 0) {
707
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
708
                         << " resource_id=" << obj_info.id();
709
            return ret;
710
        }
711
#endif
712
104
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
713
104
    }
714
715
152
    return 0;
716
152
}
717
718
152
int InstanceRecycler::init_storage_vault_accessors() {
719
152
    if (instance_info_.resource_ids().empty()) {
720
145
        return 0;
721
145
    }
722
723
7
    FullRangeGetOptions opts(txn_kv_);
724
7
    opts.prefetch = true;
725
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
726
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
727
728
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
729
18
        auto [k, v] = *kv;
730
18
        StorageVaultPB vault;
731
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
732
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
733
0
            return -1;
734
0
        }
735
18
        std::string recycler_storage_vault_white_list = accumulate(
736
18
                config::recycler_storage_vault_white_list.begin(),
737
18
                config::recycler_storage_vault_white_list.end(), std::string(),
738
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28init_storage_vault_accessorsEvENK3$_0clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES8_
Line
Count
Source
738
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
739
18
        LOG_INFO("config::recycler_storage_vault_white_list")
740
18
                .tag("", recycler_storage_vault_white_list);
741
18
        if (!config::recycler_storage_vault_white_list.empty()) {
742
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
743
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
744
8
                it == config::recycler_storage_vault_white_list.end()) {
745
2
                LOG_WARNING(
746
2
                        "failed to init accessor for vault because this vault is not in "
747
2
                        "config::recycler_storage_vault_white_list. ")
748
2
                        .tag(" vault name:", vault.name())
749
2
                        .tag(" config::recycler_storage_vault_white_list:",
750
2
                             recycler_storage_vault_white_list);
751
2
                continue;
752
2
            }
753
8
        }
754
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
755
16
                                 &accessor_map_, &vault);
756
16
        if (vault.has_hdfs_info()) {
757
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
758
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
759
9
            int ret = accessor->init();
760
9
            if (ret != 0) {
761
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
762
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
763
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
764
4
                continue;
765
4
            }
766
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
767
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
768
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
769
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
770
#else
771
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
772
                       << "but HDFS storage vaults were detected";
773
#endif
774
7
        } else if (vault.has_obj_info()) {
775
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
776
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
777
7
            if (!s3_conf) {
778
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
779
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
780
1
                continue;
781
1
            }
782
783
6
            std::shared_ptr<S3Accessor> accessor;
784
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
785
6
            if (ret != 0) {
786
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
787
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
788
0
                             << " ret=" << ret
789
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
790
0
                continue;
791
0
            }
792
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
793
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
794
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
795
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
796
6
        }
797
16
    }
798
799
7
    if (!it->is_valid()) {
800
0
        LOG_WARNING("failed to get storage vault kv");
801
0
        return -1;
802
0
    }
803
804
7
    if (accessor_map_.empty()) {
805
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
806
1
        return -2;
807
1
    }
808
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
809
6
             instance_id_);
810
811
6
    return 0;
812
7
}
813
814
153
int InstanceRecycler::init() {
815
153
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
816
153
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
817
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
818
1
        return 0;
819
1
    }
820
821
152
    int ret = init_obj_store_accessors();
822
152
    if (ret != 0) {
823
0
        return ret;
824
0
    }
825
826
152
    return init_storage_vault_accessors();
827
152
}
828
829
template <typename... Func>
830
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
120
    return [funcs...]() {
832
120
        return [](std::initializer_list<int> ret_vals) {
833
120
            int i = 0;
834
140
            for (int ret : ret_vals) {
835
140
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
140
            }
839
120
            return i;
840
120
        }({funcs()...});
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
20
            for (int ret : ret_vals) {
835
20
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
20
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
20
            for (int ret : ret_vals) {
835
20
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
20
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
0
                    i = ret;
837
0
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
120
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
120
}
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Unexecuted instantiation: recycler.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_2EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
830
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
831
10
    return [funcs...]() {
832
10
        return [](std::initializer_list<int> ret_vals) {
833
10
            int i = 0;
834
10
            for (int ret : ret_vals) {
835
10
                if (ret != 0) {
836
10
                    i = ret;
837
10
                }
838
10
            }
839
10
            return i;
840
10
        }({funcs()...});
841
10
    };
842
10
}
843
844
11
int InstanceRecycler::do_recycle() {
845
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
846
11
    tablet_metrics_context_.reset();
847
11
    segment_metrics_context_.reset();
848
11
    DORIS_CLOUD_DEFER {
849
11
        tablet_metrics_context_.finish_report();
850
11
        segment_metrics_context_.finish_report();
851
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
848
11
    DORIS_CLOUD_DEFER {
849
11
        tablet_metrics_context_.finish_report();
850
11
        segment_metrics_context_.finish_report();
851
11
    };
852
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
853
1
        int res = recycle_cluster_snapshots();
854
1
        if (res != 0) {
855
0
            return -1;
856
0
        }
857
1
        return recycle_deleted_instance();
858
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
859
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
860
10
                                        fmt::format("instance id {}", instance_id_),
861
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
861
120
                                        [](int r) { return r != 0; });
862
10
        sync_executor
863
10
                .add(task_wrapper(
864
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
864
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
865
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_3clEv
Line
Count
Source
865
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
866
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
867
                                   // becase they may both recycle the same set of tablets
868
                        // recycle dropped table or idexes(mv, rollup)
869
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
869
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
870
                        // recycle dropped partitions
871
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
871
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
872
10
                .add(task_wrapper(
873
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
873
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
874
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_7clEv
Line
Count
Source
874
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
875
10
                .add(task_wrapper(
876
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
876
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
877
10
                .add(task_wrapper(
878
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
878
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
879
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
879
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
880
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_11clEv
Line
Count
Source
880
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
881
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_12clEv
Line
Count
Source
881
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
882
10
                .add(task_wrapper(
883
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
883
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
884
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_14clEv
Line
Count
Source
884
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
885
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_15clEv
Line
Count
Source
885
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
886
10
        bool finished = true;
887
10
        std::vector<int> rets = sync_executor.when_all(&finished);
888
120
        for (int ret : rets) {
889
120
            if (ret != 0) {
890
0
                return ret;
891
0
            }
892
120
        }
893
10
        return finished ? 0 : -1;
894
10
    } else {
895
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
896
0
                     << " instance_id=" << instance_id_;
897
0
        return -1;
898
0
    }
899
11
}
900
901
/**
902
* 1. delete all remote data
903
* 2. delete all kv
904
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
905
*/
906
13
int InstanceRecycler::recycle_deleted_instance() {
907
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
908
909
13
    int ret = 0;
910
13
    auto start_time = steady_clock::now();
911
13
    const auto recycle_state = instance_info_.recycle_state();
912
913
13
    if (config::retain_deleted_instance_tombstone &&
914
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
915
4
        return 0;
916
4
    }
917
918
9
    DORIS_CLOUD_DEFER {
919
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
920
9
        if (ret != 0) {
921
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
922
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
923
0
                         << "s, instance_id=" << instance_id_;
924
9
        } else if (recycle_state ==
925
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
926
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
927
0
                      << "s, instance_id=" << instance_id_;
928
9
        } else {
929
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
930
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
931
9
                      << "s, instance_id=" << instance_id_;
932
9
        }
933
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
918
9
    DORIS_CLOUD_DEFER {
919
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
920
9
        if (ret != 0) {
921
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
922
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
923
0
                         << "s, instance_id=" << instance_id_;
924
9
        } else if (recycle_state ==
925
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
926
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
927
0
                      << "s, instance_id=" << instance_id_;
928
9
        } else {
929
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
930
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
931
9
                      << "s, instance_id=" << instance_id_;
932
9
        }
933
9
    };
934
935
9
    switch (recycle_state) {
936
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
937
6
        ret = recycle_deleted_instance_data();
938
6
        break;
939
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
940
3
        ret = recycle_deleted_instance_metadata();
941
3
        break;
942
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
943
0
        ret = remove_instance_key();
944
0
        break;
945
0
    default:
946
0
        LOG_WARNING("invalid instance recycle state")
947
0
                .tag("instance_id", instance_id_)
948
0
                .tag("recycle_state", instance_info_.recycle_state());
949
0
        ret = -1;
950
0
        break;
951
9
    }
952
953
9
    return ret;
954
9
}
955
956
6
int InstanceRecycler::recycle_deleted_instance_data() {
957
6
    int ret = 0;
958
959
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
960
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
961
6
        int res = recycle_tmp_rowsets();
962
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
963
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
964
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
965
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
966
            // and cannot be recycled.
967
0
            res = recycle_tmp_rowsets();
968
0
        }
969
6
        return res;
970
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
960
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
961
6
        int res = recycle_tmp_rowsets();
962
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
963
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
964
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
965
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
966
            // and cannot be recycled.
967
0
            res = recycle_tmp_rowsets();
968
0
        }
969
6
        return res;
970
6
    };
971
972
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
973
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
974
0
        return -1;
975
0
    }
976
977
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
978
6
    if (recycle_versioned_rowsets() != 0) {
979
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
980
0
        return -1;
981
0
    }
982
983
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
984
6
    if (recycle_operation_logs() != 0) {
985
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
986
0
        return -1;
987
0
    }
988
989
    // Step 4: Check if there are still cluster snapshots
990
6
    bool has_snapshots = false;
991
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
992
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
993
0
        return -1;
994
6
    } else if (has_snapshots) {
995
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
996
1
        return 0;
997
1
    }
998
999
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
1000
5
                            instance_info().snapshot_switch_status() !=
1001
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
1002
5
    if (snapshot_enabled) {
1003
1
        bool has_unrecycled_rowsets = false;
1004
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
1005
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
1006
0
            return -1;
1007
1
        } else if (has_unrecycled_rowsets) {
1008
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
1009
0
                    .tag("instance_id", instance_id_);
1010
0
            return ret;
1011
0
        }
1012
4
    } else { // delete all remote data if snapshot is disabled
1013
4
        for (auto& [_, accessor] : accessor_map_) {
1014
4
            if (stopped()) {
1015
0
                return ret;
1016
0
            }
1017
1018
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
1019
4
            int del_ret = accessor->delete_all();
1020
4
            if (del_ret == 0) {
1021
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
1022
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
1023
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
1024
                // so the recycling has been successful.
1025
0
                ret = -1;
1026
0
            }
1027
4
        }
1028
1029
4
        if (ret != 0) {
1030
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
1031
0
            return ret;
1032
0
        }
1033
4
    }
1034
1035
5
    if (update_instance_recycle_state(
1036
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
1037
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
1038
0
        return -1;
1039
0
    }
1040
1041
5
    return 0;
1042
5
}
1043
1044
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
1045
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
1046
7
    if (instance_info_.has_successor_instance_id() &&
1047
7
        !instance_info_.successor_instance_id().empty()) {
1048
4
        std::string key = instance_key(instance_info_.successor_instance_id());
1049
4
        std::unique_ptr<Transaction> txn;
1050
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1051
4
        if (err != TxnErrorCode::TXN_OK) {
1052
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1053
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1054
0
                         << " err=" << err;
1055
0
            return -1;
1056
0
        }
1057
1058
4
        InstanceInfoPB successor_instance;
1059
4
        std::string value;
1060
4
        err = txn->get(key, &value);
1061
4
        if (err == TxnErrorCode::TXN_OK) {
1062
3
            InstanceInfoPB successor_instance;
1063
3
            if (!successor_instance.ParseFromString(value)) {
1064
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1065
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1066
0
                return -1;
1067
0
            }
1068
3
            if (!successor_instance.has_recycle_state() ||
1069
3
                successor_instance.recycle_state() !=
1070
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1071
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1072
2
                          << " instance_id=" << instance_id_
1073
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1074
2
                          << " successor_status=" << successor_instance.status()
1075
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1076
2
                return 0;
1077
2
            }
1078
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1079
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1080
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1081
0
                         << " err=" << err;
1082
0
            return -1;
1083
0
        }
1084
4
    }
1085
1086
    // delete all kv
1087
5
    std::unique_ptr<Transaction> txn;
1088
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1089
5
    if (err != TxnErrorCode::TXN_OK) {
1090
0
        LOG(WARNING) << "failed to create txn";
1091
0
        return -1;
1092
0
    }
1093
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1094
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1095
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1096
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1097
5
    txn->remove(start_txn_key, end_txn_key);
1098
5
    std::string start_version_key = version_key_prefix(instance_id_);
1099
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1100
5
    txn->remove(start_version_key, end_version_key);
1101
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1102
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1103
5
    txn->remove(start_meta_key, end_meta_key);
1104
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1105
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1106
5
    txn->remove(start_recycle_key, end_recycle_key);
1107
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1108
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1109
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1110
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1111
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1112
5
    txn->remove(start_copy_key, end_copy_key);
1113
    // should not remove job key range, because we need to reserve job recycle kv
1114
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1115
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1116
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1117
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1118
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1119
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1120
5
    std::string start_vault_key = storage_vault_key(key_info0);
1121
5
    std::string end_vault_key = storage_vault_key(key_info1);
1122
5
    txn->remove(start_vault_key, end_vault_key);
1123
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1124
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1125
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1126
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1127
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1128
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1129
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1130
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1131
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1132
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1133
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1134
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1135
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1136
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1137
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1138
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1139
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1140
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1141
1142
    // Updating the recycle state also commits this transaction, making the metadata deletions
1143
    // and state transition atomic.
1144
5
    if (update_instance_recycle_state(
1145
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1146
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1147
0
        return -1;
1148
0
    }
1149
1150
5
    return 0;
1151
5
}
1152
1153
0
int InstanceRecycler::remove_instance_key() {
1154
0
    std::unique_ptr<Transaction> txn;
1155
0
    std::string key = instance_key(instance_info_.instance_id());
1156
0
    std::string value;
1157
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1158
0
    if (err != TxnErrorCode::TXN_OK) {
1159
0
        LOG(WARNING) << "failed to create txn";
1160
0
        return -1;
1161
0
    }
1162
1163
0
    err = txn->get(key, &value);
1164
0
    if (err != TxnErrorCode::TXN_OK) {
1165
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1166
0
                     << ", err=" << err;
1167
0
        return -1;
1168
0
    }
1169
1170
0
    InstanceInfoPB instance;
1171
0
    if (!instance.ParseFromString(value)) {
1172
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1173
0
        return -1;
1174
0
    }
1175
1176
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1177
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1178
0
                     << instance_id_ << ", status=" << instance.status();
1179
0
        return -1;
1180
0
    }
1181
1182
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1183
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1184
0
                     << instance_id_
1185
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1186
0
                     << ", expected_state="
1187
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1188
0
        return -1;
1189
0
    }
1190
1191
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1192
0
    txn->remove(key);
1193
0
    err = txn->commit();
1194
0
    if (err != TxnErrorCode::TXN_OK) {
1195
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1196
0
                     << " err=" << err;
1197
0
        return -1;
1198
0
    }
1199
0
    return 0;
1200
0
}
1201
1202
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1203
7
                                                    InstanceRecycleState target_state) {
1204
7
    std::unique_ptr<Transaction> txn;
1205
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1206
7
    if (err != TxnErrorCode::TXN_OK) {
1207
0
        LOG(WARNING) << "failed to create txn";
1208
0
        return -1;
1209
0
    }
1210
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1211
7
}
1212
1213
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1214
                                                    InstanceRecycleState target_state,
1215
12
                                                    Transaction* txn) {
1216
12
    const bool valid_transition =
1217
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1218
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1219
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1220
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1221
1222
12
    if (!valid_transition) {
1223
1
        LOG_WARNING("invalid instance recycled state transition")
1224
1
                .tag("instance_id", instance_id_)
1225
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1226
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1227
1
        return -1;
1228
1
    }
1229
1230
11
    std::string key = instance_key({instance_id_});
1231
11
    std::string value;
1232
11
    TxnErrorCode err = txn->get(key, &value);
1233
11
    if (err != TxnErrorCode::TXN_OK) {
1234
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1235
0
                .tag("instance_id", instance_id_)
1236
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1237
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1238
0
                .tag("err", err);
1239
0
        return -1;
1240
0
    }
1241
1242
11
    InstanceInfoPB instance;
1243
11
    if (!instance.ParseFromString(value)) {
1244
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1245
0
                .tag("instance_id", instance_id_)
1246
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1247
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1248
0
        return -1;
1249
0
    }
1250
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1251
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1252
0
                .tag("instance_id", instance_id_)
1253
0
                .tag("status", instance.status())
1254
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1255
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1256
0
        return -1;
1257
0
    }
1258
11
    if (instance.recycle_state() != current_state) {
1259
1
        LOG_WARNING("instance recycled state changed before update")
1260
1
                .tag("instance_id", instance_id_)
1261
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1262
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1263
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1264
1
        return -1;
1265
1
    }
1266
1267
10
    instance.set_recycle_state(target_state);
1268
10
    instance.set_recycle_state_update_time_ms(
1269
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1270
10
    if (!instance.SerializeToString(&value)) {
1271
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1272
0
                .tag("instance_id", instance_id_)
1273
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1274
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1275
0
        return -1;
1276
0
    }
1277
1278
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1279
10
    txn->put(key, value);
1280
10
    err = txn->commit();
1281
10
    if (err != TxnErrorCode::TXN_OK) {
1282
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1283
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1284
0
        return -1;
1285
0
    }
1286
1287
10
    instance_info_.Swap(&instance);
1288
10
    LOG_INFO("updated instance recycled state")
1289
10
            .tag("instance_id", instance_id_)
1290
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1291
10
    return 0;
1292
10
}
1293
1294
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1295
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1296
9
    if (exists == nullptr) {
1297
0
        return -1;
1298
0
    }
1299
9
    *exists = false;
1300
1301
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1302
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1303
9
    std::string scan_begin = begin;
1304
1305
9
    while (true) {
1306
9
        std::unique_ptr<RangeGetIterator> it_range;
1307
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1308
9
        if (get_ret < 0) {
1309
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1310
0
                    .tag("instance_id", instance_id_)
1311
0
                    .tag("tablet_id", tablet_id)
1312
0
                    .tag("ret", get_ret);
1313
0
            return -1;
1314
0
        }
1315
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1316
6
            return 0;
1317
6
        }
1318
1319
3
        std::string last_key;
1320
3
        while (it_range->has_next()) {
1321
3
            auto [k, v] = it_range->next();
1322
3
            last_key.assign(k.data(), k.size());
1323
3
            doris::RowsetMetaCloudPB rowset_meta;
1324
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1325
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1326
0
                        .tag("instance_id", instance_id_)
1327
0
                        .tag("tablet_id", tablet_id)
1328
0
                        .tag("key", hex(k));
1329
0
                continue;
1330
0
            }
1331
3
            if (stats) {
1332
3
                ++stats->rowset_scan_count;
1333
3
            }
1334
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1335
3
                *exists = true;
1336
3
                return 0;
1337
3
            }
1338
3
        }
1339
1340
0
        if (!it_range->more()) {
1341
0
            return 0;
1342
0
        }
1343
1344
        // Continue scanning from the next key to keep each transaction short.
1345
0
        scan_begin = std::move(last_key);
1346
0
        scan_begin.push_back('\x00');
1347
0
    }
1348
9
}
1349
1350
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1351
                                                          const std::string& rowset_id,
1352
                                                          int64_t txn_id, bool* recycle_exists,
1353
11
                                                          bool* tmp_exists) {
1354
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1355
0
        return -1;
1356
0
    }
1357
11
    *recycle_exists = false;
1358
11
    *tmp_exists = false;
1359
1360
11
    if (txn_id <= 0) {
1361
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1362
0
                .tag("instance_id", instance_id_)
1363
0
                .tag("tablet_id", tablet_id)
1364
0
                .tag("rowset_id", rowset_id)
1365
0
                .tag("txn_id", txn_id);
1366
0
        return -1;
1367
0
    }
1368
1369
11
    std::unique_ptr<Transaction> txn;
1370
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1371
11
    if (err != TxnErrorCode::TXN_OK) {
1372
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1373
0
                .tag("instance_id", instance_id_)
1374
0
                .tag("tablet_id", tablet_id)
1375
0
                .tag("rowset_id", rowset_id)
1376
0
                .tag("txn_id", txn_id)
1377
0
                .tag("err", err);
1378
0
        return -1;
1379
0
    }
1380
1381
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1382
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1383
11
    if (ret == TxnErrorCode::TXN_OK) {
1384
1
        *recycle_exists = true;
1385
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1386
0
        LOG_WARNING("failed to check recycle rowset existence")
1387
0
                .tag("instance_id", instance_id_)
1388
0
                .tag("tablet_id", tablet_id)
1389
0
                .tag("rowset_id", rowset_id)
1390
0
                .tag("key", hex(recycle_key))
1391
0
                .tag("err", ret);
1392
0
        return -1;
1393
0
    }
1394
1395
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1396
11
    ret = key_exists(txn.get(), tmp_key, true);
1397
11
    if (ret == TxnErrorCode::TXN_OK) {
1398
1
        *tmp_exists = true;
1399
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1400
0
        LOG_WARNING("failed to check tmp rowset existence")
1401
0
                .tag("instance_id", instance_id_)
1402
0
                .tag("tablet_id", tablet_id)
1403
0
                .tag("txn_id", txn_id)
1404
0
                .tag("key", hex(tmp_key))
1405
0
                .tag("err", ret);
1406
0
        return -1;
1407
0
    }
1408
1409
11
    return 0;
1410
11
}
1411
1412
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1413
9
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1414
9
    if (!hint.empty()) {
1415
9
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1416
9
            return {hint, it->second};
1417
9
        }
1418
9
    }
1419
1420
0
    return {"", nullptr};
1421
9
}
1422
1423
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1424
                                               const std::string& packed_file_path,
1425
3
                                               PackedFileRecycleStats* stats) {
1426
3
    bool local_changed = false;
1427
3
    int64_t left_num = 0;
1428
3
    int64_t left_bytes = 0;
1429
3
    bool all_small_files_confirmed = true;
1430
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1431
1432
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1433
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1434
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1435
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1436
14
        LOG_INFO("packed slice correction status")
1437
14
                .tag("instance_id", instance_id_)
1438
14
                .tag("packed_file_path", packed_file_path)
1439
14
                .tag("small_file_path", file.path())
1440
14
                .tag("tablet_id", tablet_id)
1441
14
                .tag("rowset_id", rowset_id)
1442
14
                .tag("txn_id", txn_id)
1443
14
                .tag("size", file.size())
1444
14
                .tag("deleted", file.deleted())
1445
14
                .tag("corrected", file.corrected())
1446
14
                .tag("confirmed_this_round", confirmed_this_round);
1447
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24correct_packed_file_infoEPNS0_16PackedFileInfoPBEPbRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS1_22PackedFileRecycleStatsEENK3$_0clERKNS0_13PackedSlicePBEb
Line
Count
Source
1432
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1433
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1434
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1435
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1436
        LOG_INFO("packed slice correction status")
1437
14
                .tag("instance_id", instance_id_)
1438
14
                .tag("packed_file_path", packed_file_path)
1439
14
                .tag("small_file_path", file.path())
1440
14
                .tag("tablet_id", tablet_id)
1441
14
                .tag("rowset_id", rowset_id)
1442
14
                .tag("txn_id", txn_id)
1443
14
                .tag("size", file.size())
1444
14
                .tag("deleted", file.deleted())
1445
14
                .tag("corrected", file.corrected())
1446
14
                .tag("confirmed_this_round", confirmed_this_round);
1447
14
    };
1448
1449
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1450
14
        auto* small_file = packed_info->mutable_slices(i);
1451
14
        if (small_file->deleted()) {
1452
3
            log_small_file_status(*small_file, small_file->corrected());
1453
3
            continue;
1454
3
        }
1455
1456
11
        if (small_file->corrected()) {
1457
0
            left_num++;
1458
0
            left_bytes += small_file->size();
1459
0
            log_small_file_status(*small_file, true);
1460
0
            continue;
1461
0
        }
1462
1463
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1464
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1465
0
                    .tag("instance_id", instance_id_)
1466
0
                    .tag("small_file_path", small_file->path())
1467
0
                    .tag("index", i);
1468
0
            return -1;
1469
0
        }
1470
1471
11
        int64_t tablet_id = small_file->tablet_id();
1472
11
        const std::string& rowset_id = small_file->rowset_id();
1473
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1474
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1475
0
                    .tag("instance_id", instance_id_)
1476
0
                    .tag("small_file_path", small_file->path())
1477
0
                    .tag("index", i)
1478
0
                    .tag("tablet_id", tablet_id)
1479
0
                    .tag("rowset_id", rowset_id)
1480
0
                    .tag("has_txn_id", small_file->has_txn_id())
1481
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1482
0
            return -1;
1483
0
        }
1484
11
        int64_t txn_id = small_file->txn_id();
1485
11
        bool recycle_exists = false;
1486
11
        bool tmp_exists = false;
1487
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1488
11
                                                &tmp_exists) != 0) {
1489
0
            return -1;
1490
0
        }
1491
1492
11
        bool small_file_confirmed = false;
1493
11
        if (tmp_exists) {
1494
1
            left_num++;
1495
1
            left_bytes += small_file->size();
1496
1
            small_file_confirmed = true;
1497
10
        } else if (recycle_exists) {
1498
1
            left_num++;
1499
1
            left_bytes += small_file->size();
1500
            // keep small_file_confirmed=false so the packed file remains uncorrected
1501
9
        } else {
1502
9
            bool rowset_exists = false;
1503
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1504
0
                return -1;
1505
0
            }
1506
1507
9
            if (!rowset_exists) {
1508
6
                if (!small_file->deleted()) {
1509
6
                    small_file->set_deleted(true);
1510
6
                    local_changed = true;
1511
6
                }
1512
6
                if (!small_file->corrected()) {
1513
6
                    small_file->set_corrected(true);
1514
6
                    local_changed = true;
1515
6
                }
1516
6
                small_file_confirmed = true;
1517
6
            } else {
1518
3
                left_num++;
1519
3
                left_bytes += small_file->size();
1520
3
                small_file_confirmed = true;
1521
3
            }
1522
9
        }
1523
1524
11
        if (!small_file_confirmed) {
1525
1
            all_small_files_confirmed = false;
1526
1
        }
1527
1528
11
        if (small_file->corrected() != small_file_confirmed) {
1529
4
            small_file->set_corrected(small_file_confirmed);
1530
4
            local_changed = true;
1531
4
        }
1532
1533
11
        log_small_file_status(*small_file, small_file_confirmed);
1534
11
    }
1535
1536
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1537
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1538
3
        local_changed = true;
1539
3
    }
1540
3
    if (packed_info->ref_cnt() != left_num) {
1541
3
        auto old_ref_cnt = packed_info->ref_cnt();
1542
3
        packed_info->set_ref_cnt(left_num);
1543
3
        LOG_INFO("corrected packed file ref count")
1544
3
                .tag("instance_id", instance_id_)
1545
3
                .tag("resource_id", packed_info->resource_id())
1546
3
                .tag("packed_file_path", packed_file_path)
1547
3
                .tag("old_ref_cnt", old_ref_cnt)
1548
3
                .tag("new_ref_cnt", left_num);
1549
3
        local_changed = true;
1550
3
    }
1551
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1552
2
        packed_info->set_corrected(all_small_files_confirmed);
1553
2
        local_changed = true;
1554
2
    }
1555
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1556
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1557
1
        local_changed = true;
1558
1
    }
1559
1560
3
    if (changed != nullptr) {
1561
3
        *changed = local_changed;
1562
3
    }
1563
3
    return 0;
1564
3
}
1565
1566
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1567
                                                 const std::string& packed_file_path,
1568
3
                                                 PackedFileRecycleStats* stats) {
1569
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1570
3
    bool correction_ok = false;
1571
3
    cloud::PackedFileInfoPB packed_info;
1572
1573
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1574
3
        if (stopped()) {
1575
0
            LOG_WARNING("recycler stopped before processing packed file")
1576
0
                    .tag("instance_id", instance_id_)
1577
0
                    .tag("packed_file_path", packed_file_path)
1578
0
                    .tag("attempt", attempt);
1579
0
            return -1;
1580
0
        }
1581
1582
3
        std::unique_ptr<Transaction> txn;
1583
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1584
3
        if (err != TxnErrorCode::TXN_OK) {
1585
0
            LOG_WARNING("failed to create txn when processing packed file")
1586
0
                    .tag("instance_id", instance_id_)
1587
0
                    .tag("packed_file_path", packed_file_path)
1588
0
                    .tag("attempt", attempt)
1589
0
                    .tag("err", err);
1590
0
            return -1;
1591
0
        }
1592
1593
3
        std::string packed_val;
1594
3
        err = txn->get(packed_key, &packed_val);
1595
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1596
0
            return 0;
1597
0
        }
1598
3
        if (err != TxnErrorCode::TXN_OK) {
1599
0
            LOG_WARNING("failed to get packed file kv")
1600
0
                    .tag("instance_id", instance_id_)
1601
0
                    .tag("packed_file_path", packed_file_path)
1602
0
                    .tag("attempt", attempt)
1603
0
                    .tag("err", err);
1604
0
            return -1;
1605
0
        }
1606
1607
3
        if (!packed_info.ParseFromString(packed_val)) {
1608
0
            LOG_WARNING("failed to parse packed file info")
1609
0
                    .tag("instance_id", instance_id_)
1610
0
                    .tag("packed_file_path", packed_file_path)
1611
0
                    .tag("attempt", attempt);
1612
0
            return -1;
1613
0
        }
1614
1615
3
        int64_t now_sec = ::time(nullptr);
1616
3
        bool corrected = packed_info.corrected();
1617
3
        bool due = config::force_immediate_recycle ||
1618
3
                   now_sec - packed_info.created_at_sec() >=
1619
3
                           config::packed_file_correction_delay_seconds;
1620
1621
3
        if (!corrected && due) {
1622
3
            bool changed = false;
1623
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1624
0
                LOG_WARNING("correct_packed_file_info failed")
1625
0
                        .tag("instance_id", instance_id_)
1626
0
                        .tag("packed_file_path", packed_file_path)
1627
0
                        .tag("attempt", attempt);
1628
0
                return -1;
1629
0
            }
1630
3
            if (changed) {
1631
3
                std::string updated;
1632
3
                if (!packed_info.SerializeToString(&updated)) {
1633
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1634
0
                            .tag("instance_id", instance_id_)
1635
0
                            .tag("packed_file_path", packed_file_path)
1636
0
                            .tag("attempt", attempt);
1637
0
                    return -1;
1638
0
                }
1639
3
                txn->put(packed_key, updated);
1640
3
                err = txn->commit();
1641
3
                if (err == TxnErrorCode::TXN_OK) {
1642
3
                    if (stats) {
1643
3
                        ++stats->num_corrected;
1644
3
                    }
1645
3
                } else {
1646
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1647
0
                        LOG_WARNING(
1648
0
                                "failed to commit correction for packed file due to conflict, "
1649
0
                                "retrying")
1650
0
                                .tag("instance_id", instance_id_)
1651
0
                                .tag("packed_file_path", packed_file_path)
1652
0
                                .tag("attempt", attempt);
1653
0
                        sleep_for_packed_file_retry();
1654
0
                        packed_info.Clear();
1655
0
                        continue;
1656
0
                    }
1657
0
                    LOG_WARNING("failed to commit correction for packed file")
1658
0
                            .tag("instance_id", instance_id_)
1659
0
                            .tag("packed_file_path", packed_file_path)
1660
0
                            .tag("attempt", attempt)
1661
0
                            .tag("err", err);
1662
0
                    return -1;
1663
0
                }
1664
3
            }
1665
3
        }
1666
1667
3
        correction_ok = true;
1668
3
        break;
1669
3
    }
1670
1671
3
    if (!correction_ok) {
1672
0
        return -1;
1673
0
    }
1674
1675
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1676
3
          packed_info.ref_cnt() == 0)) {
1677
2
        return 0;
1678
2
    }
1679
1680
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1681
0
        LOG_WARNING("packed file missing resource id when recycling")
1682
0
                .tag("instance_id", instance_id_)
1683
0
                .tag("packed_file_path", packed_file_path);
1684
0
        return -1;
1685
0
    }
1686
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1687
1
    if (!accessor) {
1688
0
        LOG_WARNING("no accessor available to delete packed file")
1689
0
                .tag("instance_id", instance_id_)
1690
0
                .tag("packed_file_path", packed_file_path)
1691
0
                .tag("resource_id", packed_info.resource_id());
1692
0
        return -1;
1693
0
    }
1694
1
    int del_ret = accessor->delete_file(packed_file_path);
1695
1
    if (del_ret != 0 && del_ret != 1) {
1696
0
        LOG_WARNING("failed to delete packed file")
1697
0
                .tag("instance_id", instance_id_)
1698
0
                .tag("packed_file_path", packed_file_path)
1699
0
                .tag("resource_id", resource_id)
1700
0
                .tag("ret", del_ret);
1701
0
        return -1;
1702
0
    }
1703
1
    if (del_ret == 1) {
1704
0
        LOG_INFO("packed file already removed")
1705
0
                .tag("instance_id", instance_id_)
1706
0
                .tag("packed_file_path", packed_file_path)
1707
0
                .tag("resource_id", resource_id);
1708
1
    } else {
1709
1
        LOG_INFO("deleted packed file")
1710
1
                .tag("instance_id", instance_id_)
1711
1
                .tag("packed_file_path", packed_file_path)
1712
1
                .tag("resource_id", resource_id);
1713
1
    }
1714
1715
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1716
1
        std::unique_ptr<Transaction> del_txn;
1717
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1718
1
        if (err != TxnErrorCode::TXN_OK) {
1719
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1720
0
                    .tag("instance_id", instance_id_)
1721
0
                    .tag("packed_file_path", packed_file_path)
1722
0
                    .tag("del_attempt", del_attempt)
1723
0
                    .tag("err", err);
1724
0
            return -1;
1725
0
        }
1726
1727
1
        std::string latest_val;
1728
1
        err = del_txn->get(packed_key, &latest_val);
1729
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1730
0
            return 0;
1731
0
        }
1732
1
        if (err != TxnErrorCode::TXN_OK) {
1733
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1734
0
                    .tag("instance_id", instance_id_)
1735
0
                    .tag("packed_file_path", packed_file_path)
1736
0
                    .tag("del_attempt", del_attempt)
1737
0
                    .tag("err", err);
1738
0
            return -1;
1739
0
        }
1740
1741
1
        cloud::PackedFileInfoPB latest_info;
1742
1
        if (!latest_info.ParseFromString(latest_val)) {
1743
0
            LOG_WARNING("failed to parse packed file info before removal")
1744
0
                    .tag("instance_id", instance_id_)
1745
0
                    .tag("packed_file_path", packed_file_path)
1746
0
                    .tag("del_attempt", del_attempt);
1747
0
            return -1;
1748
0
        }
1749
1750
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1751
1
              latest_info.ref_cnt() == 0)) {
1752
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1753
0
                    .tag("instance_id", instance_id_)
1754
0
                    .tag("packed_file_path", packed_file_path)
1755
0
                    .tag("del_attempt", del_attempt);
1756
0
            return 0;
1757
0
        }
1758
1759
1
        del_txn->remove(packed_key);
1760
1
        err = del_txn->commit();
1761
1
        if (err == TxnErrorCode::TXN_OK) {
1762
1
            if (stats) {
1763
1
                ++stats->num_deleted;
1764
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1765
1
                                        static_cast<int64_t>(latest_val.size());
1766
1
                if (del_ret == 0 || del_ret == 1) {
1767
1
                    ++stats->num_object_deleted;
1768
1
                    int64_t object_size = latest_info.total_slice_bytes();
1769
1
                    if (object_size <= 0) {
1770
0
                        object_size = packed_info.total_slice_bytes();
1771
0
                    }
1772
1
                    stats->bytes_object_deleted += object_size;
1773
1
                }
1774
1
            }
1775
1
            LOG_INFO("removed packed file metadata")
1776
1
                    .tag("instance_id", instance_id_)
1777
1
                    .tag("packed_file_path", packed_file_path);
1778
1
            return 0;
1779
1
        }
1780
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1781
0
            if (del_attempt >= max_retry_times) {
1782
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1783
0
                        .tag("instance_id", instance_id_)
1784
0
                        .tag("packed_file_path", packed_file_path)
1785
0
                        .tag("del_attempt", del_attempt);
1786
0
                return -1;
1787
0
            }
1788
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1789
0
                    .tag("instance_id", instance_id_)
1790
0
                    .tag("packed_file_path", packed_file_path)
1791
0
                    .tag("del_attempt", del_attempt);
1792
0
            sleep_for_packed_file_retry();
1793
0
            continue;
1794
0
        }
1795
0
        LOG_WARNING("failed to remove packed file kv")
1796
0
                .tag("instance_id", instance_id_)
1797
0
                .tag("packed_file_path", packed_file_path)
1798
0
                .tag("del_attempt", del_attempt)
1799
0
                .tag("err", err);
1800
0
        return -1;
1801
0
    }
1802
1803
0
    return -1;
1804
1
}
1805
1806
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1807
4
                                            PackedFileRecycleStats* stats, int* ret) {
1808
4
    if (stats) {
1809
4
        ++stats->num_scanned;
1810
4
    }
1811
4
    std::string packed_file_path;
1812
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1813
0
        LOG_WARNING("failed to decode packed file key")
1814
0
                .tag("instance_id", instance_id_)
1815
0
                .tag("key", hex(key));
1816
0
        if (stats) {
1817
0
            ++stats->num_failed;
1818
0
        }
1819
0
        if (ret) {
1820
0
            *ret = -1;
1821
0
        }
1822
0
        return 0;
1823
0
    }
1824
1825
4
    cloud::PackedFileInfoPB packed_info;
1826
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1827
0
        LOG_WARNING("failed to parse packed file info from scan")
1828
0
                .tag("instance_id", instance_id_)
1829
0
                .tag("packed_file_path", packed_file_path);
1830
0
        if (stats) {
1831
0
            ++stats->num_failed;
1832
0
        }
1833
0
        if (ret) {
1834
0
            *ret = -1;
1835
0
        }
1836
0
        return 0;
1837
0
    }
1838
1839
4
    const int64_t now_sec = ::time(nullptr);
1840
4
    const bool due =
1841
4
            config::force_immediate_recycle ||
1842
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1843
4
    const bool need_correction = !packed_info.corrected() && due;
1844
4
    const bool need_recycle =
1845
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1846
4
    if (!need_correction && !need_recycle) {
1847
1
        return 0;
1848
1
    }
1849
1850
3
    std::string packed_key(key);
1851
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1852
3
    if (process_ret != 0) {
1853
0
        if (stats) {
1854
0
            ++stats->num_failed;
1855
0
        }
1856
0
        if (ret) {
1857
0
            *ret = -1;
1858
0
        }
1859
0
    }
1860
3
    return 0;
1861
4
}
1862
1863
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1864
6.30k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1865
6.30k
    if (config::force_immediate_recycle) {
1866
295
        return 0L;
1867
295
    }
1868
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1869
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1870
6.00k
    int64_t retention_seconds = config::retention_seconds;
1871
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1872
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1873
4.70k
    }
1874
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1875
6.00k
    if (*earlest_ts > final_expiration) {
1876
6
        *earlest_ts = final_expiration;
1877
6
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1878
6
    }
1879
6.00k
    return final_expiration;
1880
6.30k
}
1881
1882
int64_t calculate_partition_expired_time(
1883
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1884
13
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1885
13
    if (config::force_immediate_recycle) {
1886
7
        return 0L;
1887
7
    }
1888
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1889
6
                                                            : partition_meta_pb.creation_time();
1890
6
    int64_t retention_seconds = config::retention_seconds;
1891
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1892
6
        retention_seconds =
1893
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1894
6
    }
1895
6
    int64_t final_expiration = expiration + retention_seconds;
1896
6
    if (*earlest_ts > final_expiration) {
1897
2
        *earlest_ts = final_expiration;
1898
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1899
2
    }
1900
6
    return final_expiration;
1901
13
}
1902
1903
int64_t calculate_index_expired_time(const std::string& instance_id_,
1904
                                     const RecycleIndexPB& index_meta_pb,
1905
19
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1906
19
    if (config::force_immediate_recycle) {
1907
13
        return 0L;
1908
13
    }
1909
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1910
6
                                                        : index_meta_pb.creation_time();
1911
6
    int64_t retention_seconds = config::retention_seconds;
1912
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1913
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1914
6
    }
1915
6
    int64_t final_expiration = expiration + retention_seconds;
1916
6
    if (*earlest_ts > final_expiration) {
1917
2
        *earlest_ts = final_expiration;
1918
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1919
2
    }
1920
6
    return final_expiration;
1921
19
}
1922
1923
int64_t calculate_tmp_rowset_expired_time(
1924
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1925
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1926
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1927
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1928
    //  duration or timeout always < `retention_time` in practice.
1929
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1930
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1931
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1932
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1933
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1934
53.2k
    if (*earlest_ts > final_expiration) {
1935
20
        *earlest_ts = final_expiration;
1936
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1937
20
    }
1938
53.2k
    return final_expiration;
1939
53.2k
}
1940
1941
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1942
50.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1943
50.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1944
50.0k
    if (*earlest_ts > final_expiration / 1000) {
1945
11
        *earlest_ts = final_expiration / 1000;
1946
11
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1947
11
    }
1948
50.0k
    return final_expiration;
1949
50.0k
}
1950
1951
int64_t calculate_restore_job_expired_time(
1952
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1953
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1954
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1955
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1956
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1957
        // final state, recycle immediately
1958
41
        return 0L;
1959
41
    }
1960
    // not final state, wait much longer than the FE's timeout(1 day)
1961
0
    int64_t last_modified_s =
1962
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1963
0
    int64_t expiration = restore_job.expired_at_s() > 0
1964
0
                                 ? last_modified_s + restore_job.expired_at_s()
1965
0
                                 : last_modified_s;
1966
0
    int64_t final_expiration = expiration + config::retention_seconds;
1967
0
    if (*earlest_ts > final_expiration) {
1968
0
        *earlest_ts = final_expiration;
1969
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1970
0
    }
1971
0
    return final_expiration;
1972
41
}
1973
1974
537
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1975
537
    AbortTxnRequest req;
1976
537
    TxnInfoPB txn_info;
1977
537
    MetaServiceCode code = MetaServiceCode::OK;
1978
537
    std::string msg;
1979
537
    std::stringstream ss;
1980
537
    std::unique_ptr<Transaction> txn;
1981
537
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1982
537
    if (err != TxnErrorCode::TXN_OK) {
1983
0
        LOG_WARNING("failed to create txn").tag("err", err);
1984
0
        return -1;
1985
0
    }
1986
1987
    // get txn index
1988
537
    TxnIndexPB txn_idx_pb;
1989
537
    auto index_key = txn_index_key({instance_id_, txn_id});
1990
537
    std::string index_val;
1991
537
    err = txn->get(index_key, &index_val);
1992
537
    if (err != TxnErrorCode::TXN_OK) {
1993
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1994
            // maybe recycled
1995
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1996
2
                    .tag("key", hex(index_key))
1997
2
                    .tag("txn_id", txn_id);
1998
2
            return 0;
1999
2
        }
2000
0
        LOG_WARNING("failed to get txn index")
2001
0
                .tag("err", err)
2002
0
                .tag("key", hex(index_key))
2003
0
                .tag("txn_id", txn_id);
2004
0
        return -1;
2005
2
    }
2006
535
    if (!txn_idx_pb.ParseFromString(index_val)) {
2007
1
        LOG_WARNING("failed to parse txn index")
2008
1
                .tag("err", err)
2009
1
                .tag("key", hex(index_key))
2010
1
                .tag("txn_id", txn_id);
2011
1
        return -1;
2012
1
    }
2013
534
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
2014
534
        txn_idx_pb.tablet_index().db_id() <= 0) {
2015
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
2016
3
                .tag("key", hex(index_key))
2017
3
                .tag("txn_id", txn_id)
2018
3
                .tag("db_id",
2019
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
2020
3
        return -1;
2021
3
    }
2022
2023
531
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
2024
531
    const int64_t owner_txn_id =
2025
531
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
2026
531
    if (owner_txn_id <= 0) {
2027
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
2028
1
                .tag("key", hex(index_key))
2029
1
                .tag("txn_id", txn_id)
2030
1
                .tag("owner_txn_id", owner_txn_id);
2031
1
        return -1;
2032
1
    }
2033
2034
530
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
2035
530
    std::string info_val;
2036
530
    err = txn->get(info_key, &info_val);
2037
530
    if (err != TxnErrorCode::TXN_OK) {
2038
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2039
            // maybe recycled
2040
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
2041
1
                        owner_txn_id, instance_id_)
2042
1
                    .tag("key", hex(info_key))
2043
1
                    .tag("txn_id", txn_id)
2044
1
                    .tag("owner_txn_id", owner_txn_id);
2045
1
            return 0;
2046
1
        }
2047
0
        LOG_WARNING("failed to get txn info")
2048
0
                .tag("err", err)
2049
0
                .tag("key", hex(info_key))
2050
0
                .tag("txn_id", txn_id)
2051
0
                .tag("owner_txn_id", owner_txn_id);
2052
0
        return -1;
2053
1
    }
2054
529
    if (!txn_info.ParseFromString(info_val)) {
2055
1
        LOG_WARNING("failed to parse txn info")
2056
1
                .tag("err", err)
2057
1
                .tag("key", hex(info_key))
2058
1
                .tag("txn_id", txn_id)
2059
1
                .tag("owner_txn_id", owner_txn_id);
2060
1
        return -1;
2061
1
    }
2062
528
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2063
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2064
1
                .tag("key", hex(info_key))
2065
1
                .tag("txn_id", txn_id)
2066
1
                .tag("owner_txn_id", owner_txn_id)
2067
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2068
1
        return -1;
2069
1
    }
2070
2071
527
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2072
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2073
514
                .tag("key", hex(info_key))
2074
514
                .tag("txn_id", txn_id)
2075
514
                .tag("owner_txn_id", owner_txn_id);
2076
514
        return 0;
2077
514
    }
2078
13
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2079
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2080
4
                    owner_txn_id, txn_info.status())
2081
4
                .tag("key", hex(info_key))
2082
4
                .tag("txn_id", txn_id)
2083
4
                .tag("owner_txn_id", owner_txn_id);
2084
4
        return -1;
2085
4
    }
2086
2087
9
    req.set_txn_id(owner_txn_id);
2088
9
    req.set_db_id(db_id);
2089
2090
9
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2091
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2092
9
                 << " txn_info=" << txn_info.ShortDebugString();
2093
2094
9
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2095
9
    if (code != MetaServiceCode::OK) {
2096
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2097
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2098
0
                     << " code=" << code << " msg=" << msg;
2099
0
        return -1;
2100
0
    }
2101
2102
9
    err = txn->commit();
2103
9
    if (err != TxnErrorCode::TXN_OK) {
2104
0
        code = cast_as<ErrCategory::COMMIT>(err);
2105
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2106
0
        msg = ss.str();
2107
0
        return -1;
2108
0
    }
2109
2110
9
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2111
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2112
9
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2113
9
                 << " msg=" << msg;
2114
2115
9
    return 0;
2116
9
}
2117
2118
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2119
11
                                                   const std::string& job_id) {
2120
11
    FinishTabletJobRequest req;
2121
11
    FinishTabletJobResponse res;
2122
11
    req.set_action(FinishTabletJobRequest::ABORT);
2123
11
    MetaServiceCode code = MetaServiceCode::OK;
2124
11
    std::string msg;
2125
11
    std::stringstream ss;
2126
2127
11
    TabletIndexPB tablet_idx;
2128
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2129
11
    if (ret == 1) {
2130
        // tablet maybe recycled, directly return 0
2131
1
        return 0;
2132
10
    } else if (ret != 0) {
2133
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2134
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2135
0
        return ret;
2136
0
    }
2137
2138
10
    std::unique_ptr<Transaction> txn;
2139
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2140
10
    if (err != TxnErrorCode::TXN_OK) {
2141
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2142
0
        return -1;
2143
0
    }
2144
2145
10
    std::string job_key =
2146
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2147
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2148
10
    std::string job_val;
2149
10
    err = txn->get(job_key, &job_val);
2150
10
    if (err != TxnErrorCode::TXN_OK) {
2151
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2152
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2153
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2154
            // A previous recycler round may have aborted the job. The caller must recheck the
2155
            // recycle key before deleting object data.
2156
1
            return 0;
2157
1
        }
2158
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2159
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2160
0
                     << " key=" << hex(job_key);
2161
0
        return -1;
2162
1
    }
2163
2164
9
    TabletJobInfoPB job_pb;
2165
9
    if (!job_pb.ParseFromString(job_val)) {
2166
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2167
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2168
0
        return -1;
2169
0
    }
2170
2171
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2172
9
    for (const auto& compaction : job_pb.compaction()) {
2173
9
        if (compaction.id() == job_id) {
2174
5
            matched_compaction = &compaction;
2175
5
            break;
2176
5
        }
2177
9
    }
2178
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2179
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2180
9
        job_pb.schema_change().id() == job_id) {
2181
3
        matched_schema_change = &job_pb.schema_change();
2182
3
    }
2183
2184
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2185
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2186
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2187
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2188
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2189
        // both the base and mirrored schema-change records.
2190
8
        if (matched_compaction != nullptr) {
2191
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2192
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2193
5
        } else {
2194
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2195
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2196
3
        }
2197
8
        req.set_action(FinishTabletJobRequest::ABORT);
2198
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2199
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2200
8
                           ss);
2201
8
        if (code != MetaServiceCode::OK) {
2202
            // These two codes mean that the job cannot be aborted anymore.
2203
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2204
            // There is no running job that still owns the PREPARE rowset, so the caller may
2205
            // recheck the recycle key.
2206
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2207
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2208
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2209
            // job again and continue recycling only when the target job id no longer exists.
2210
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2211
0
                std::unique_ptr<Transaction> check_txn;
2212
0
                err = txn_kv_->create_txn(&check_txn);
2213
0
                if (err != TxnErrorCode::TXN_OK) {
2214
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2215
0
                                 << instance_id_ << " err=" << err;
2216
0
                    return -1;
2217
0
                }
2218
2219
0
                const auto& idx = req.job().idx();
2220
0
                std::string current_job_key =
2221
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2222
0
                                        idx.partition_id(), idx.tablet_id()});
2223
0
                std::string current_job_val;
2224
0
                err = check_txn->get(current_job_key, &current_job_val);
2225
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2226
0
                    no_job_to_abort = true;
2227
0
                } else if (err != TxnErrorCode::TXN_OK) {
2228
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2229
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2230
0
                                 << " key=" << hex(current_job_key);
2231
0
                    return -1;
2232
0
                } else {
2233
0
                    TabletJobInfoPB current_job;
2234
0
                    if (!current_job.ParseFromString(current_job_val)) {
2235
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2236
0
                                     << " tablet_id=" << idx.tablet_id()
2237
0
                                     << " key=" << hex(current_job_key);
2238
0
                        return -1;
2239
0
                    }
2240
0
                    if (matched_compaction != nullptr) {
2241
0
                        no_job_to_abort = true;
2242
0
                        for (const auto& compaction : current_job.compaction()) {
2243
0
                            if (compaction.id() == job_id) {
2244
0
                                no_job_to_abort = false;
2245
0
                                break;
2246
0
                            }
2247
0
                        }
2248
0
                    } else {
2249
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2250
0
                                          current_job.schema_change().id() != job_id;
2251
0
                    }
2252
0
                }
2253
0
            }
2254
0
            if (no_job_to_abort) {
2255
0
                return 0;
2256
0
            }
2257
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2258
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2259
0
                         << " msg=" << msg;
2260
0
            return -1;
2261
0
        }
2262
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2263
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2264
8
                     << " code=" << code << " msg=" << msg;
2265
8
    } else {
2266
        // clang-format off
2267
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2268
1
                  << ", instance_id=" << instance_id_ 
2269
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2270
1
                  << ", job_id=" << job_id
2271
1
                  << ", rowset_id=" << rowset_id;
2272
        // clang-format on
2273
1
    }
2274
2275
9
    return 0;
2276
9
}
2277
2278
template <typename T>
2279
22
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2280
22
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2281
13
        return rowset_meta_pb.mutable_rowset_meta();
2282
13
    } else {
2283
9
        return &rowset_meta_pb;
2284
9
    }
2285
22
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2279
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2280
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2281
13
        return rowset_meta_pb.mutable_rowset_meta();
2282
    } else {
2283
        return &rowset_meta_pb;
2284
    }
2285
13
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2279
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2280
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2281
        return rowset_meta_pb.mutable_rowset_meta();
2282
9
    } else {
2283
9
        return &rowset_meta_pb;
2284
9
    }
2285
9
}
2286
2287
template <typename T>
2288
1.63k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2289
1.63k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2290
833
        return rowset_meta_pb.rowset_meta();
2291
833
    } else {
2292
799
        return rowset_meta_pb;
2293
799
    }
2294
1.63k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2288
833
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2289
833
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2290
833
        return rowset_meta_pb.rowset_meta();
2291
    } else {
2292
        return rowset_meta_pb;
2293
    }
2294
833
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2288
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2289
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2290
        return rowset_meta_pb.rowset_meta();
2291
799
    } else {
2292
799
        return rowset_meta_pb;
2293
799
    }
2294
799
}
2295
2296
template <typename T>
2297
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2298
1.07k
        const T& rowset_meta_pb) {
2299
1.07k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
0
            return std::nullopt;
2302
0
        }
2303
545
    }
2304
2305
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
1.07k
    RelatedTxnOrJobAbortTask task;
2307
1.07k
    task.tablet_id = rs_meta.tablet_id();
2308
1.07k
    task.start_version = rs_meta.start_version();
2309
1.07k
    task.end_version = rs_meta.end_version();
2310
1.07k
    task.rowset_id = rs_meta.rowset_id_v2();
2311
1.07k
    if (rs_meta.has_load_id()) {
2312
1.05k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2313
1.05k
        task.txn_id = rs_meta.txn_id();
2314
1.05k
        return task;
2315
1.05k
    }
2316
19
    if (rs_meta.has_job_id()) {
2317
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2318
14
        task.job_id = rs_meta.job_id();
2319
14
        return task;
2320
14
    }
2321
5
    return std::nullopt;
2322
19
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2298
545
        const T& rowset_meta_pb) {
2299
545
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
0
            return std::nullopt;
2302
0
        }
2303
545
    }
2304
2305
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
545
    RelatedTxnOrJobAbortTask task;
2307
545
    task.tablet_id = rs_meta.tablet_id();
2308
545
    task.start_version = rs_meta.start_version();
2309
545
    task.end_version = rs_meta.end_version();
2310
545
    task.rowset_id = rs_meta.rowset_id_v2();
2311
545
    if (rs_meta.has_load_id()) {
2312
534
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2313
534
        task.txn_id = rs_meta.txn_id();
2314
534
        return task;
2315
534
    }
2316
11
    if (rs_meta.has_job_id()) {
2317
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2318
10
        task.job_id = rs_meta.job_id();
2319
10
        return task;
2320
10
    }
2321
1
    return std::nullopt;
2322
11
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2298
526
        const T& rowset_meta_pb) {
2299
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2300
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2301
            return std::nullopt;
2302
        }
2303
    }
2304
2305
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2306
526
    RelatedTxnOrJobAbortTask task;
2307
526
    task.tablet_id = rs_meta.tablet_id();
2308
526
    task.start_version = rs_meta.start_version();
2309
526
    task.end_version = rs_meta.end_version();
2310
526
    task.rowset_id = rs_meta.rowset_id_v2();
2311
526
    if (rs_meta.has_load_id()) {
2312
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2313
518
        task.txn_id = rs_meta.txn_id();
2314
518
        return task;
2315
518
    }
2316
8
    if (rs_meta.has_job_id()) {
2317
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2318
4
        task.job_id = rs_meta.job_id();
2319
4
        return task;
2320
4
    }
2321
4
    return std::nullopt;
2322
8
}
2323
2324
template <typename T>
2325
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2326
529
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2327
529
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2328
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2329
0
            return false;
2330
0
        }
2331
268
    }
2332
2333
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2334
529
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2335
529
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2336
0
        return false;
2337
0
    }
2338
529
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2339
523
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2340
523
    }
2341
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2342
529
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2326
268
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2327
268
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2328
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2329
0
            return false;
2330
0
        }
2331
268
    }
2332
2333
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2334
268
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2335
268
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2336
0
        return false;
2337
0
    }
2338
268
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2339
264
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2340
264
    }
2341
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2342
268
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2326
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2327
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2328
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2329
            return false;
2330
        }
2331
    }
2332
2333
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2334
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2335
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2336
0
        return false;
2337
0
    }
2338
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2339
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2340
259
    }
2341
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2342
261
}
2343
2344
71
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2345
71
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2346
71
}
2347
2348
template <typename T>
2349
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2350
18
                                   const std::vector<std::string>& keys) {
2351
35
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2352
18
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2353
18
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2354
18
        std::unique_ptr<Transaction> txn;
2355
18
        TxnErrorCode err = txn_kv->create_txn(&txn);
2356
18
        if (err != TxnErrorCode::TXN_OK) {
2357
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2358
0
            return -1;
2359
0
        }
2360
18
        std::vector<std::optional<std::string>> values;
2361
18
        err = txn->batch_get(&values, batch_keys);
2362
18
        if (err != TxnErrorCode::TXN_OK) {
2363
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2364
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2365
0
            return -1;
2366
0
        }
2367
18
        DCHECK_EQ(values.size(), batch_keys.size());
2368
40
        for (size_t i = 0; i < batch_keys.size(); i++) {
2369
22
            if (!values[i].has_value()) {
2370
                // has already been removed by commit_rowset
2371
0
                continue;
2372
0
            }
2373
22
            const auto& key = batch_keys[i];
2374
22
            auto val = values[i].value();
2375
22
            T rowset_meta_pb;
2376
22
            if (!rowset_meta_pb.ParseFromString(val)) {
2377
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2378
0
                             << " key=" << hex(key);
2379
0
                return -1;
2380
0
            }
2381
22
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2382
0
                continue;
2383
0
            }
2384
22
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2385
22
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2386
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2387
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2388
13
            }
2389
22
            val.clear();
2390
22
            rowset_meta_pb.SerializeToString(&val);
2391
22
            txn->put(key, val);
2392
22
        }
2393
18
        err = txn->commit();
2394
18
        if (err != TxnErrorCode::TXN_OK) {
2395
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2396
1
            return -1;
2397
1
        }
2398
18
    }
2399
2400
17
    return 0;
2401
18
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2350
11
                                   const std::vector<std::string>& keys) {
2351
21
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2352
11
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2353
11
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2354
11
        std::unique_ptr<Transaction> txn;
2355
11
        TxnErrorCode err = txn_kv->create_txn(&txn);
2356
11
        if (err != TxnErrorCode::TXN_OK) {
2357
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2358
0
            return -1;
2359
0
        }
2360
11
        std::vector<std::optional<std::string>> values;
2361
11
        err = txn->batch_get(&values, batch_keys);
2362
11
        if (err != TxnErrorCode::TXN_OK) {
2363
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2364
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2365
0
            return -1;
2366
0
        }
2367
11
        DCHECK_EQ(values.size(), batch_keys.size());
2368
24
        for (size_t i = 0; i < batch_keys.size(); i++) {
2369
13
            if (!values[i].has_value()) {
2370
                // has already been removed by commit_rowset
2371
0
                continue;
2372
0
            }
2373
13
            const auto& key = batch_keys[i];
2374
13
            auto val = values[i].value();
2375
13
            T rowset_meta_pb;
2376
13
            if (!rowset_meta_pb.ParseFromString(val)) {
2377
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2378
0
                             << " key=" << hex(key);
2379
0
                return -1;
2380
0
            }
2381
13
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2382
0
                continue;
2383
0
            }
2384
13
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2385
13
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2386
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2387
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2388
13
            }
2389
13
            val.clear();
2390
13
            rowset_meta_pb.SerializeToString(&val);
2391
13
            txn->put(key, val);
2392
13
        }
2393
11
        err = txn->commit();
2394
11
        if (err != TxnErrorCode::TXN_OK) {
2395
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2396
1
            return -1;
2397
1
        }
2398
11
    }
2399
2400
10
    return 0;
2401
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2350
7
                                   const std::vector<std::string>& keys) {
2351
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2352
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2353
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2354
7
        std::unique_ptr<Transaction> txn;
2355
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2356
7
        if (err != TxnErrorCode::TXN_OK) {
2357
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2358
0
            return -1;
2359
0
        }
2360
7
        std::vector<std::optional<std::string>> values;
2361
7
        err = txn->batch_get(&values, batch_keys);
2362
7
        if (err != TxnErrorCode::TXN_OK) {
2363
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2364
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2365
0
            return -1;
2366
0
        }
2367
7
        DCHECK_EQ(values.size(), batch_keys.size());
2368
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2369
9
            if (!values[i].has_value()) {
2370
                // has already been removed by commit_rowset
2371
0
                continue;
2372
0
            }
2373
9
            const auto& key = batch_keys[i];
2374
9
            auto val = values[i].value();
2375
9
            T rowset_meta_pb;
2376
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2377
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2378
0
                             << " key=" << hex(key);
2379
0
                return -1;
2380
0
            }
2381
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2382
0
                continue;
2383
0
            }
2384
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2385
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2386
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2387
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2388
            }
2389
9
            val.clear();
2390
9
            rowset_meta_pb.SerializeToString(&val);
2391
9
            txn->put(key, val);
2392
9
        }
2393
7
        err = txn->commit();
2394
7
        if (err != TxnErrorCode::TXN_OK) {
2395
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2396
0
            return -1;
2397
0
        }
2398
7
    }
2399
2400
7
    return 0;
2401
7
}
2402
2403
template <typename T>
2404
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2405
18
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2406
18
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
18
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
1
        }
2411
18
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2406
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
1
        }
2411
11
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2406
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
0
        }
2411
7
    });
2412
18
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2405
11
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2406
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
11
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
11
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
11
        }
2411
11
    });
2412
11
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2405
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2406
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2407
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2408
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2409
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2410
7
        }
2411
7
    });
2412
7
}
2413
2414
template <typename T>
2415
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2416
                                 const std::vector<std::string>& keys,
2417
20
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2418
42
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2419
22
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2420
22
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2421
22
        std::unique_ptr<Transaction> txn;
2422
22
        TxnErrorCode err = txn_kv->create_txn(&txn);
2423
22
        if (err != TxnErrorCode::TXN_OK) {
2424
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2425
0
            return -1;
2426
0
        }
2427
22
        std::vector<std::optional<std::string>> values;
2428
22
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2429
22
        if (err != TxnErrorCode::TXN_OK) {
2430
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2431
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2432
0
            return -1;
2433
0
        }
2434
22
        DCHECK_EQ(values.size(), batch_keys.size());
2435
555
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2436
533
            const std::string& key = batch_keys[idx];
2437
533
            if (!values[idx].has_value()) {
2438
                // has already been removed
2439
0
                continue;
2440
0
            }
2441
533
            T rowset_meta_pb;
2442
533
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2443
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2444
0
                             << " key=" << hex(key);
2445
0
                return -1;
2446
0
            }
2447
533
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2448
533
                abort_task.has_value()) {
2449
533
                abort_task->key = key;
2450
533
                abort_tasks->emplace_back(std::move(*abort_task));
2451
533
            }
2452
533
        }
2453
22
    }
2454
20
    return 0;
2455
20
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2417
15
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2418
31
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2419
16
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2420
16
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2421
16
        std::unique_ptr<Transaction> txn;
2422
16
        TxnErrorCode err = txn_kv->create_txn(&txn);
2423
16
        if (err != TxnErrorCode::TXN_OK) {
2424
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2425
0
            return -1;
2426
0
        }
2427
16
        std::vector<std::optional<std::string>> values;
2428
16
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2429
16
        if (err != TxnErrorCode::TXN_OK) {
2430
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2431
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2432
0
            return -1;
2433
0
        }
2434
16
        DCHECK_EQ(values.size(), batch_keys.size());
2435
288
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2436
272
            const std::string& key = batch_keys[idx];
2437
272
            if (!values[idx].has_value()) {
2438
                // has already been removed
2439
0
                continue;
2440
0
            }
2441
272
            T rowset_meta_pb;
2442
272
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2443
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2444
0
                             << " key=" << hex(key);
2445
0
                return -1;
2446
0
            }
2447
272
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2448
272
                abort_task.has_value()) {
2449
272
                abort_task->key = key;
2450
272
                abort_tasks->emplace_back(std::move(*abort_task));
2451
272
            }
2452
272
        }
2453
16
    }
2454
15
    return 0;
2455
15
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2417
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2418
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2419
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2420
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2421
6
        std::unique_ptr<Transaction> txn;
2422
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2423
6
        if (err != TxnErrorCode::TXN_OK) {
2424
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2425
0
            return -1;
2426
0
        }
2427
6
        std::vector<std::optional<std::string>> values;
2428
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2429
6
        if (err != TxnErrorCode::TXN_OK) {
2430
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2431
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2432
0
            return -1;
2433
0
        }
2434
6
        DCHECK_EQ(values.size(), batch_keys.size());
2435
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2436
261
            const std::string& key = batch_keys[idx];
2437
261
            if (!values[idx].has_value()) {
2438
                // has already been removed
2439
0
                continue;
2440
0
            }
2441
261
            T rowset_meta_pb;
2442
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2443
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2444
0
                             << " key=" << hex(key);
2445
0
                return -1;
2446
0
            }
2447
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2448
261
                abort_task.has_value()) {
2449
261
                abort_task->key = key;
2450
261
                abort_tasks->emplace_back(std::move(*abort_task));
2451
261
            }
2452
261
        }
2453
6
    }
2454
5
    return 0;
2455
5
}
2456
2457
template <typename T>
2458
int batch_recheck_rowsets_after_abort(
2459
        TxnKv* txn_kv, const std::string& instance_id,
2460
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2461
18
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2462
18
    int ret = 0;
2463
38
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2464
20
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2465
20
        std::vector<std::string> batch_keys;
2466
20
        batch_keys.reserve(limit - offset);
2467
550
        for (size_t idx = offset; idx < limit; ++idx) {
2468
530
            batch_keys.push_back(keys_to_recheck[idx].first);
2469
530
        }
2470
2471
20
        std::unique_ptr<Transaction> txn;
2472
20
        TxnErrorCode err = txn_kv->create_txn(&txn);
2473
20
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2475
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2476
0
            ret = -1;
2477
0
            continue;
2478
0
        }
2479
2480
20
        std::vector<std::optional<std::string>> values;
2481
20
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2482
20
        if (err != TxnErrorCode::TXN_OK) {
2483
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2484
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2485
0
            ret = -1;
2486
0
            continue;
2487
0
        }
2488
20
        DCHECK_EQ(values.size(), batch_keys.size());
2489
20
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2490
20
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2491
20
                                 &batch_size);
2492
2493
550
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2494
530
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2495
530
            if (!values[idx].has_value()) {
2496
1
                continue;
2497
1
            }
2498
2499
529
            T rowset_meta_pb;
2500
529
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2501
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2502
0
                             << instance_id << " key=" << hex(key);
2503
0
                ret = -1;
2504
0
                continue;
2505
0
            }
2506
529
            if (config::enable_mark_delete_rowset_before_recycle &&
2507
529
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2508
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2509
0
                             << instance_id << " key=" << hex(key);
2510
0
                continue;
2511
0
            }
2512
529
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2513
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2514
1
                             << instance_id << " key=" << hex(key);
2515
1
                continue;
2516
1
            }
2517
528
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2518
528
        }
2519
20
    }
2520
18
    return ret;
2521
18
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2461
13
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2462
13
    int ret = 0;
2463
27
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2464
14
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2465
14
        std::vector<std::string> batch_keys;
2466
14
        batch_keys.reserve(limit - offset);
2467
283
        for (size_t idx = offset; idx < limit; ++idx) {
2468
269
            batch_keys.push_back(keys_to_recheck[idx].first);
2469
269
        }
2470
2471
14
        std::unique_ptr<Transaction> txn;
2472
14
        TxnErrorCode err = txn_kv->create_txn(&txn);
2473
14
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2475
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2476
0
            ret = -1;
2477
0
            continue;
2478
0
        }
2479
2480
14
        std::vector<std::optional<std::string>> values;
2481
14
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2482
14
        if (err != TxnErrorCode::TXN_OK) {
2483
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2484
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2485
0
            ret = -1;
2486
0
            continue;
2487
0
        }
2488
14
        DCHECK_EQ(values.size(), batch_keys.size());
2489
14
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2490
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2491
14
                                 &batch_size);
2492
2493
283
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2494
269
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2495
269
            if (!values[idx].has_value()) {
2496
1
                continue;
2497
1
            }
2498
2499
268
            T rowset_meta_pb;
2500
268
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2501
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2502
0
                             << instance_id << " key=" << hex(key);
2503
0
                ret = -1;
2504
0
                continue;
2505
0
            }
2506
268
            if (config::enable_mark_delete_rowset_before_recycle &&
2507
268
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2508
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2509
0
                             << instance_id << " key=" << hex(key);
2510
0
                continue;
2511
0
            }
2512
268
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2513
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2514
1
                             << instance_id << " key=" << hex(key);
2515
1
                continue;
2516
1
            }
2517
267
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2518
267
        }
2519
14
    }
2520
13
    return ret;
2521
13
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2461
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2462
5
    int ret = 0;
2463
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2464
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2465
6
        std::vector<std::string> batch_keys;
2466
6
        batch_keys.reserve(limit - offset);
2467
267
        for (size_t idx = offset; idx < limit; ++idx) {
2468
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2469
261
        }
2470
2471
6
        std::unique_ptr<Transaction> txn;
2472
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2473
6
        if (err != TxnErrorCode::TXN_OK) {
2474
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2475
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2476
0
            ret = -1;
2477
0
            continue;
2478
0
        }
2479
2480
6
        std::vector<std::optional<std::string>> values;
2481
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2482
6
        if (err != TxnErrorCode::TXN_OK) {
2483
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2484
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2485
0
            ret = -1;
2486
0
            continue;
2487
0
        }
2488
6
        DCHECK_EQ(values.size(), batch_keys.size());
2489
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2490
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2491
6
                                 &batch_size);
2492
2493
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2494
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2495
261
            if (!values[idx].has_value()) {
2496
0
                continue;
2497
0
            }
2498
2499
261
            T rowset_meta_pb;
2500
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2501
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2502
0
                             << instance_id << " key=" << hex(key);
2503
0
                ret = -1;
2504
0
                continue;
2505
0
            }
2506
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2507
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2508
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2509
0
                             << instance_id << " key=" << hex(key);
2510
0
                continue;
2511
0
            }
2512
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2513
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2514
0
                             << instance_id << " key=" << hex(key);
2515
0
                continue;
2516
0
            }
2517
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2518
261
        }
2519
6
    }
2520
5
    return ret;
2521
5
}
2522
2523
template <typename T>
2524
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2525
        const std::vector<std::string>& keys,
2526
20
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2527
20
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2528
20
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2529
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2530
0
        return -1;
2531
0
    }
2532
20
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2533
20
    int ret = 0;
2534
533
    for (const auto& abort_task : abort_tasks) {
2535
533
        int abort_ret = 0;
2536
533
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2537
526
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2538
526
        } else {
2539
7
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2540
7
                                                     abort_task.job_id);
2541
7
        }
2542
533
        if (abort_ret != 0) {
2543
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2544
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2545
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2546
3
            ret = abort_ret;
2547
3
            continue;
2548
3
        }
2549
530
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2550
530
    }
2551
20
    return ret;
2552
20
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2526
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2527
15
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2528
15
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2529
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2530
0
        return -1;
2531
0
    }
2532
15
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2533
15
    int ret = 0;
2534
272
    for (const auto& abort_task : abort_tasks) {
2535
272
        int abort_ret = 0;
2536
272
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2537
267
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2538
267
        } else {
2539
5
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2540
5
                                                     abort_task.job_id);
2541
5
        }
2542
272
        if (abort_ret != 0) {
2543
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2544
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2545
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2546
3
            ret = abort_ret;
2547
3
            continue;
2548
3
        }
2549
269
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2550
269
    }
2551
15
    return ret;
2552
15
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2526
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2527
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2528
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2529
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2530
0
        return -1;
2531
0
    }
2532
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2533
5
    int ret = 0;
2534
261
    for (const auto& abort_task : abort_tasks) {
2535
261
        int abort_ret = 0;
2536
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2537
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2538
259
        } else {
2539
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2540
2
                                                     abort_task.job_id);
2541
2
        }
2542
261
        if (abort_ret != 0) {
2543
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2544
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2545
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2546
0
            ret = abort_ret;
2547
0
            continue;
2548
0
        }
2549
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2550
261
    }
2551
5
    return ret;
2552
5
}
2553
2554
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2555
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2556
15
        std::atomic_long* num_recycled) {
2557
15
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2558
15
                                  num_recycled]() mutable {
2559
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2560
15
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2561
15
                                                                            keys_to_recheck);
2562
15
        if (abort_ret != 0) {
2563
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2564
2
                            "instance_id="
2565
2
                         << instance_id_;
2566
2
        }
2567
15
        if (keys_to_recheck.empty()) {
2568
2
            return;
2569
2
        }
2570
2571
13
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2572
13
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2573
13
                                                            keys_to_recheck, &rowsets_to_recycle);
2574
13
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
267
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2579
267
            const auto& current_meta = current_rowset.rowset_meta();
2580
267
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2581
267
                                   current_meta.rowset_id_v2()) != 0) {
2582
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2583
1
                continue;
2584
1
            }
2585
266
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2586
266
                                                   current_meta.tablet_id(),
2587
266
                                                   current_meta.rowset_id_v2()) != 0) {
2588
0
                continue;
2589
0
            }
2590
266
            std::vector<std::string> keys {key};
2591
266
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2592
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2593
0
                continue;
2594
0
            }
2595
266
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2596
266
        }
2597
13
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2558
2
                                  num_recycled]() mutable {
2559
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2560
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2561
2
                                                                            keys_to_recheck);
2562
2
        if (abort_ret != 0) {
2563
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2564
0
                            "instance_id="
2565
0
                         << instance_id_;
2566
0
        }
2567
2
        if (keys_to_recheck.empty()) {
2568
0
            return;
2569
0
        }
2570
2571
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2572
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2573
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2574
2
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2579
2
            const auto& current_meta = current_rowset.rowset_meta();
2580
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2581
2
                                   current_meta.rowset_id_v2()) != 0) {
2582
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2583
0
                continue;
2584
0
            }
2585
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2586
2
                                                   current_meta.tablet_id(),
2587
2
                                                   current_meta.rowset_id_v2()) != 0) {
2588
0
                continue;
2589
0
            }
2590
2
            std::vector<std::string> keys {key};
2591
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2592
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2593
0
                continue;
2594
0
            }
2595
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2596
2
        }
2597
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEEN3$_0clEv
Line
Count
Source
2558
13
                                  num_recycled]() mutable {
2559
13
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2560
13
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2561
13
                                                                            keys_to_recheck);
2562
13
        if (abort_ret != 0) {
2563
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2564
2
                            "instance_id="
2565
2
                         << instance_id_;
2566
2
        }
2567
13
        if (keys_to_recheck.empty()) {
2568
2
            return;
2569
2
        }
2570
2571
11
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2572
11
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2573
11
                                                            keys_to_recheck, &rowsets_to_recycle);
2574
11
        if (recheck_ret != 0) {
2575
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2576
0
                         << instance_id_;
2577
0
        }
2578
265
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2579
265
            const auto& current_meta = current_rowset.rowset_meta();
2580
265
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2581
265
                                   current_meta.rowset_id_v2()) != 0) {
2582
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2583
1
                continue;
2584
1
            }
2585
264
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2586
264
                                                   current_meta.tablet_id(),
2587
264
                                                   current_meta.rowset_id_v2()) != 0) {
2588
0
                continue;
2589
0
            }
2590
264
            std::vector<std::string> keys {key};
2591
264
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2592
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2593
0
                continue;
2594
0
            }
2595
264
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2596
264
        }
2597
11
    });
2598
15
    if (ret != 0) {
2599
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2600
0
    }
2601
15
}
2602
2603
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2604
                                                      std::vector<std::string> rowset_keys_to_abort,
2605
                                                      std::atomic_long* num_recycled,
2606
5
                                                      RecyclerMetricsContext* metrics_context) {
2607
5
    if (rowset_keys_to_abort.empty()) {
2608
0
        return;
2609
0
    }
2610
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2611
5
                        metrics_context]() mutable {
2612
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2613
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2614
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2615
5
        if (abort_ret != 0) {
2616
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2617
0
                            "instance_id="
2618
0
                         << instance_id_;
2619
0
        }
2620
2621
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2622
5
        std::vector<std::string> keys_to_delete;
2623
5
        std::vector<std::string> ref_count_keys_to_delete;
2624
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2625
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2626
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2627
5
        if (recheck_ret != 0) {
2628
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2629
0
                         << instance_id_;
2630
0
        }
2631
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2632
261
            keys_to_delete.push_back(key);
2633
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2634
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2635
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2636
261
        }
2637
2638
5
        if (keys_to_delete.empty()) {
2639
0
            return;
2640
0
        }
2641
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2642
5
                               *metrics_context) != 0) {
2643
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2644
0
            return;
2645
0
        }
2646
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2647
261
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2648
261
                                                   rowset.rowset_id_v2()) != 0) {
2649
0
                return;
2650
0
            }
2651
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2652
0
                return;
2653
0
            }
2654
261
        }
2655
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2656
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2657
0
            return;
2658
0
        }
2659
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2661
0
                         << instance_id_;
2662
0
            return;
2663
0
        }
2664
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2665
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2611
3
                        metrics_context]() mutable {
2612
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2613
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2614
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2615
3
        if (abort_ret != 0) {
2616
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2617
0
                            "instance_id="
2618
0
                         << instance_id_;
2619
0
        }
2620
2621
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2622
3
        std::vector<std::string> keys_to_delete;
2623
3
        std::vector<std::string> ref_count_keys_to_delete;
2624
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2625
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2626
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2627
3
        if (recheck_ret != 0) {
2628
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2629
0
                         << instance_id_;
2630
0
        }
2631
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2632
3
            keys_to_delete.push_back(key);
2633
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2634
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2635
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2636
3
        }
2637
2638
3
        if (keys_to_delete.empty()) {
2639
0
            return;
2640
0
        }
2641
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2642
3
                               *metrics_context) != 0) {
2643
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2644
0
            return;
2645
0
        }
2646
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2647
3
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2648
3
                                                   rowset.rowset_id_v2()) != 0) {
2649
0
                return;
2650
0
            }
2651
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2652
0
                return;
2653
0
            }
2654
3
        }
2655
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2656
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2657
0
            return;
2658
0
        }
2659
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2661
0
                         << instance_id_;
2662
0
            return;
2663
0
        }
2664
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2665
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2611
2
                        metrics_context]() mutable {
2612
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2613
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2614
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2615
2
        if (abort_ret != 0) {
2616
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2617
0
                            "instance_id="
2618
0
                         << instance_id_;
2619
0
        }
2620
2621
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2622
2
        std::vector<std::string> keys_to_delete;
2623
2
        std::vector<std::string> ref_count_keys_to_delete;
2624
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2625
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2626
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2627
2
        if (recheck_ret != 0) {
2628
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2629
0
                         << instance_id_;
2630
0
        }
2631
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2632
258
            keys_to_delete.push_back(key);
2633
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2634
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2635
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2636
258
        }
2637
2638
2
        if (keys_to_delete.empty()) {
2639
0
            return;
2640
0
        }
2641
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2642
2
                               *metrics_context) != 0) {
2643
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2644
0
            return;
2645
0
        }
2646
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2647
258
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2648
258
                                                   rowset.rowset_id_v2()) != 0) {
2649
0
                return;
2650
0
            }
2651
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2652
0
                return;
2653
0
            }
2654
258
        }
2655
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2656
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2657
0
            return;
2658
0
        }
2659
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2661
0
                         << instance_id_;
2662
0
            return;
2663
0
        }
2664
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2665
2
    });
2666
5
}
2667
2668
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2669
1
    const std::string task_name = "recycle_ref_rowsets";
2670
1
    *has_unrecycled_rowsets = false;
2671
2672
1
    std::string data_rowset_ref_count_key_start =
2673
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2674
1
    std::string data_rowset_ref_count_key_end =
2675
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2676
2677
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2678
2679
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2680
1
    register_recycle_task(task_name, start_time);
2681
2682
1
    DORIS_CLOUD_DEFER {
2683
1
        unregister_recycle_task(task_name);
2684
1
        int64_t cost =
2685
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2686
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2687
1
                .tag("instance_id", instance_id_);
2688
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2682
1
    DORIS_CLOUD_DEFER {
2683
1
        unregister_recycle_task(task_name);
2684
1
        int64_t cost =
2685
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2686
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2687
1
                .tag("instance_id", instance_id_);
2688
1
    };
2689
2690
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2691
1
    std::set<int64_t> tablets_with_refs;
2692
1
    int64_t num_scanned = 0;
2693
2694
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2695
0
        ++num_scanned;
2696
0
        int64_t tablet_id;
2697
0
        std::string rowset_id;
2698
0
        std::string_view key(k);
2699
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2700
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2701
0
            return 0; // Continue scanning
2702
0
        }
2703
2704
0
        tablets_with_refs.insert(tablet_id);
2705
0
        return 0;
2706
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2707
2708
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2709
1
                         std::move(scan_func)) != 0) {
2710
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2711
0
        return -1;
2712
0
    }
2713
2714
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2715
1
             tablets_with_refs.size(), num_scanned)
2716
1
            .tag("instance_id", instance_id_);
2717
2718
    // Phase 2: Recycle each tablet
2719
1
    int64_t num_recycled_tablets = 0;
2720
1
    for (int64_t tablet_id : tablets_with_refs) {
2721
0
        if (stopped()) {
2722
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2723
0
                    .tag("instance_id", instance_id_)
2724
0
                    .tag("tablets_processed", num_recycled_tablets)
2725
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2726
0
            break;
2727
0
        }
2728
2729
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2730
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2731
0
            LOG_WARNING("failed to recycle tablet")
2732
0
                    .tag("instance_id", instance_id_)
2733
0
                    .tag("tablet_id", tablet_id);
2734
0
            return -1;
2735
0
        }
2736
0
        ++num_recycled_tablets;
2737
0
    }
2738
2739
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2740
1
            .tag("instance_id", instance_id_)
2741
1
            .tag("total_tablets", tablets_with_refs.size());
2742
2743
    // Phase 3: Scan again to check if any ref count keys still exist
2744
1
    std::unique_ptr<Transaction> txn;
2745
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2746
1
    if (err != TxnErrorCode::TXN_OK) {
2747
0
        LOG_WARNING("failed to create txn for final check")
2748
0
                .tag("instance_id", instance_id_)
2749
0
                .tag("err", err);
2750
0
        return -1;
2751
0
    }
2752
2753
1
    std::unique_ptr<RangeGetIterator> iter;
2754
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2755
1
    if (err != TxnErrorCode::TXN_OK) {
2756
0
        LOG_WARNING("failed to create range iterator for final check")
2757
0
                .tag("instance_id", instance_id_)
2758
0
                .tag("err", err);
2759
0
        return -1;
2760
0
    }
2761
2762
1
    *has_unrecycled_rowsets = iter->has_next();
2763
1
    if (*has_unrecycled_rowsets) {
2764
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2765
0
                .tag("instance_id", instance_id_);
2766
0
    }
2767
2768
1
    return 0;
2769
1
}
2770
2771
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2772
16
                                                         RecyclerMetricsContext* metrics_context) {
2773
16
    std::string end = prefix;
2774
16
    end.push_back('\xff');
2775
16
    std::vector<std::string_view> keys;
2776
20.0k
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2777
20.0k
        keys.push_back(key);
2778
20.0k
        return 0;
2779
20.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2776
4
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2777
4
        keys.push_back(key);
2778
4
        return 0;
2779
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2776
20.0k
    auto collect_key = [&keys](std::string_view key, std::string_view) -> int {
2777
20.0k
        keys.push_back(key);
2778
20.0k
        return 0;
2779
20.0k
    };
2780
16
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2781
16
        if (keys.empty()) {
2782
0
            return 0;
2783
0
        }
2784
16
        DORIS_CLOUD_DEFER {
2785
16
            keys.clear();
2786
16
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2784
4
        DORIS_CLOUD_DEFER {
2785
4
            keys.clear();
2786
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2784
12
        DORIS_CLOUD_DEFER {
2785
12
            keys.clear();
2786
12
        };
2787
16
        const size_t num_keys = keys.size();
2788
16
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2789
0
            LOG_WARNING("failed to delete table stream offsets")
2790
0
                    .tag("instance_id", instance_id_)
2791
0
                    .tag("num_keys", num_keys);
2792
0
            return -1;
2793
0
        }
2794
16
        metrics_context->total_recycled_num += num_keys;
2795
16
        metrics_context->report();
2796
16
        return 0;
2797
16
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2780
4
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2781
4
        if (keys.empty()) {
2782
0
            return 0;
2783
0
        }
2784
4
        DORIS_CLOUD_DEFER {
2785
4
            keys.clear();
2786
4
        };
2787
4
        const size_t num_keys = keys.size();
2788
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2789
0
            LOG_WARNING("failed to delete table stream offsets")
2790
0
                    .tag("instance_id", instance_id_)
2791
0
                    .tag("num_keys", num_keys);
2792
0
            return -1;
2793
0
        }
2794
4
        metrics_context->total_recycled_num += num_keys;
2795
4
        metrics_context->report();
2796
4
        return 0;
2797
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2780
12
    auto remove_keys = [this, &keys, metrics_context]() -> int {
2781
12
        if (keys.empty()) {
2782
0
            return 0;
2783
0
        }
2784
12
        DORIS_CLOUD_DEFER {
2785
12
            keys.clear();
2786
12
        };
2787
12
        const size_t num_keys = keys.size();
2788
12
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2789
0
            LOG_WARNING("failed to delete table stream offsets")
2790
0
                    .tag("instance_id", instance_id_)
2791
0
                    .tag("num_keys", num_keys);
2792
0
            return -1;
2793
0
        }
2794
12
        metrics_context->total_recycled_num += num_keys;
2795
12
        metrics_context->report();
2796
12
        return 0;
2797
12
    };
2798
16
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2799
16
}
2800
2801
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2802
                                              const RecycleIndexPB& recycle_index,
2803
8
                                              std::string_view recycle_key) {
2804
8
    std::unique_ptr<Transaction> txn;
2805
8
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2806
8
    if (err != TxnErrorCode::TXN_OK) {
2807
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2808
0
                .tag("instance_id", instance_id_)
2809
0
                .tag("stream_id", stream_id)
2810
0
                .tag("err", err);
2811
0
        return -1;
2812
0
    }
2813
2814
8
    std::string current_recycle_value;
2815
8
    err = txn->get(recycle_key, &current_recycle_value);
2816
8
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2817
0
        return 0;
2818
0
    }
2819
8
    if (err != TxnErrorCode::TXN_OK) {
2820
0
        LOG_WARNING("failed to read table stream recycle index")
2821
0
                .tag("instance_id", instance_id_)
2822
0
                .tag("stream_id", stream_id)
2823
0
                .tag("err", err);
2824
0
        return -1;
2825
0
    }
2826
8
    RecycleIndexPB current_recycle_index;
2827
8
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2828
8
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2829
8
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2830
8
        current_recycle_index.db_id() != recycle_index.db_id() ||
2831
8
        current_recycle_index.table_id() != recycle_index.table_id() ||
2832
8
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2833
0
        LOG_WARNING("table stream recycle index changed during recycling")
2834
0
                .tag("instance_id", instance_id_)
2835
0
                .tag("stream_id", stream_id);
2836
0
        return -1;
2837
0
    }
2838
2839
8
    txn->remove(recycle_key);
2840
8
    err = txn->commit();
2841
8
    if (err != TxnErrorCode::TXN_OK) {
2842
0
        LOG_WARNING("failed to commit final table stream cleanup")
2843
0
                .tag("instance_id", instance_id_)
2844
0
                .tag("stream_id", stream_id)
2845
0
                .tag("err", err);
2846
0
        return -1;
2847
0
    }
2848
8
    return 0;
2849
8
}
2850
2851
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2852
8
                                     std::string_view recycle_key) {
2853
8
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2854
0
        LOG_WARNING("table stream recycle index is missing binding")
2855
0
                .tag("instance_id", instance_id_)
2856
0
                .tag("stream_id", stream_id);
2857
0
        return -1;
2858
0
    }
2859
2860
8
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2861
8
    DORIS_CLOUD_DEFER {
2862
8
        metrics_context.finish_report();
2863
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2861
3
    DORIS_CLOUD_DEFER {
2862
3
        metrics_context.finish_report();
2863
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_streamElRKNS0_14RecycleIndexPBESt17basic_string_viewIcSt11char_traitsIcEEENK3$_0clEv
Line
Count
Source
2861
5
    DORIS_CLOUD_DEFER {
2862
5
        metrics_context.finish_report();
2863
5
    };
2864
8
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2865
8
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2866
8
            recycle_index.stream_db_id(), stream_id);
2867
8
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2868
0
        return -1;
2869
0
    }
2870
8
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2871
8
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2872
8
            recycle_index.stream_db_id(), stream_id);
2873
8
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2874
8
        stopped()) {
2875
0
        return -1;
2876
0
    }
2877
8
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2878
8
}
2879
2880
int InstanceRecycler::recycle_partition_table_stream_offsets(
2881
        int64_t db_id, int64_t table_id, int64_t partition_id,
2882
12
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2883
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2884
12
    DORIS_CLOUD_DEFER {
2885
12
        metrics_context.finish_report();
2886
12
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2884
1
    DORIS_CLOUD_DEFER {
2885
1
        metrics_context.finish_report();
2886
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler38recycle_partition_table_stream_offsetsElllRKN6google8protobuf16RepeatedPtrFieldINS0_21TableStreamIdentityPBEEEENK3$_0clEv
Line
Count
Source
2884
11
    DORIS_CLOUD_DEFER {
2885
11
        metrics_context.finish_report();
2886
11
    };
2887
12
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2888
17
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2889
5
        const size_t end_index =
2890
5
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2891
5
        std::unique_ptr<Transaction> txn;
2892
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2893
5
        if (err != TxnErrorCode::TXN_OK) {
2894
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2895
0
                    .tag("instance_id", instance_id_)
2896
0
                    .tag("partition_id", partition_id)
2897
0
                    .tag("err", err);
2898
0
            return -1;
2899
0
        }
2900
12
        for (size_t i = begin_index; i < end_index; ++i) {
2901
7
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2902
7
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2903
7
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2904
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2905
0
                        .tag("instance_id", instance_id_)
2906
0
                        .tag("partition_id", partition_id)
2907
0
                        .tag("stream_id", stream.stream_id());
2908
0
                return -1;
2909
0
            }
2910
7
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2911
7
                                                 stream.base_table_id(), stream.stream_db_id(),
2912
7
                                                 stream.stream_id(), partition_id}));
2913
7
            versioned_remove_all(
2914
7
                    txn.get(), versioned::table_stream_offset_key(
2915
7
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2916
7
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2917
7
        }
2918
5
        err = txn->commit();
2919
5
        if (err != TxnErrorCode::TXN_OK) {
2920
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2921
0
                    .tag("instance_id", instance_id_)
2922
0
                    .tag("partition_id", partition_id)
2923
0
                    .tag("err", err);
2924
0
            return -1;
2925
0
        }
2926
5
        metrics_context.total_recycled_num += end_index - begin_index;
2927
5
        metrics_context.report();
2928
5
    }
2929
12
    return 0;
2930
12
}
2931
2932
25
int InstanceRecycler::recycle_indexes() {
2933
25
    const std::string task_name = "recycle_indexes";
2934
25
    int64_t num_scanned = 0;
2935
25
    int64_t num_expired = 0;
2936
25
    int64_t num_recycled = 0;
2937
25
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
2938
2939
25
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
2940
25
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
2941
25
    std::string index_key0;
2942
25
    std::string index_key1;
2943
25
    recycle_index_key(index_key_info0, &index_key0);
2944
25
    recycle_index_key(index_key_info1, &index_key1);
2945
2946
25
    LOG_WARNING("begin to recycle indexes").tag("instance_id", instance_id_);
2947
2948
25
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2949
25
    register_recycle_task(task_name, start_time);
2950
2951
25
    DORIS_CLOUD_DEFER {
2952
25
        unregister_recycle_task(task_name);
2953
25
        int64_t cost =
2954
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2955
25
        metrics_context.finish_report();
2956
25
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2957
25
                .tag("instance_id", instance_id_)
2958
25
                .tag("num_scanned", num_scanned)
2959
25
                .tag("num_expired", num_expired)
2960
25
                .tag("num_recycled", num_recycled);
2961
25
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2951
4
    DORIS_CLOUD_DEFER {
2952
4
        unregister_recycle_task(task_name);
2953
4
        int64_t cost =
2954
4
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2955
4
        metrics_context.finish_report();
2956
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2957
4
                .tag("instance_id", instance_id_)
2958
4
                .tag("num_scanned", num_scanned)
2959
4
                .tag("num_expired", num_expired)
2960
4
                .tag("num_recycled", num_recycled);
2961
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2951
21
    DORIS_CLOUD_DEFER {
2952
21
        unregister_recycle_task(task_name);
2953
21
        int64_t cost =
2954
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2955
21
        metrics_context.finish_report();
2956
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2957
21
                .tag("instance_id", instance_id_)
2958
21
                .tag("num_scanned", num_scanned)
2959
21
                .tag("num_expired", num_expired)
2960
21
                .tag("num_recycled", num_recycled);
2961
21
    };
2962
2963
25
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2964
2965
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2966
25
    std::vector<std::string_view> index_keys;
2967
25
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2968
18
        ++num_scanned;
2969
18
        RecycleIndexPB index_pb;
2970
18
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2971
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2972
0
            return -1;
2973
0
        }
2974
18
        int64_t current_time = ::time(nullptr);
2975
18
        if (current_time <
2976
18
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2977
0
            return 0;
2978
0
        }
2979
18
        ++num_expired;
2980
        // decode index_id
2981
18
        auto k1 = k;
2982
18
        k1.remove_prefix(1);
2983
18
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2984
18
        decode_key(&k1, &out);
2985
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2986
18
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2987
18
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2988
18
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2989
18
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2990
        // Change state to RECYCLING
2991
18
        std::unique_ptr<Transaction> txn;
2992
18
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2993
18
        if (err != TxnErrorCode::TXN_OK) {
2994
0
            LOG_WARNING("failed to create txn").tag("err", err);
2995
0
            return -1;
2996
0
        }
2997
18
        std::string val;
2998
18
        err = txn->get(k, &val);
2999
18
        if (err ==
3000
18
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3001
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3002
0
            return 0;
3003
0
        }
3004
18
        if (err != TxnErrorCode::TXN_OK) {
3005
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3006
0
            return -1;
3007
0
        }
3008
18
        index_pb.Clear();
3009
18
        if (!index_pb.ParseFromString(val)) {
3010
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3011
0
            return -1;
3012
0
        }
3013
18
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3014
16
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3015
16
            txn->put(k, index_pb.SerializeAsString());
3016
16
            err = txn->commit();
3017
16
            if (err != TxnErrorCode::TXN_OK) {
3018
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3019
0
                return -1;
3020
0
            }
3021
16
        }
3022
18
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3023
8
            if (recycle_stream(index_id, index_pb, k) != 0) {
3024
0
                LOG_WARNING("failed to recycle table stream")
3025
0
                        .tag("instance_id", instance_id_)
3026
0
                        .tag("stream_id", index_id);
3027
0
                return -1;
3028
0
            }
3029
8
            metrics_context.total_recycled_num = ++num_recycled;
3030
8
            metrics_context.report();
3031
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3032
8
            return 0;
3033
8
        }
3034
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3035
1
            LOG_WARNING("failed to recycle tablets under index")
3036
1
                    .tag("table_id", index_pb.table_id())
3037
1
                    .tag("instance_id", instance_id_)
3038
1
                    .tag("index_id", index_id);
3039
1
            return -1;
3040
1
        }
3041
3042
9
        if (index_pb.has_db_id()) {
3043
            // Recycle the versioned keys
3044
3
            std::unique_ptr<Transaction> txn;
3045
3
            err = txn_kv_->create_txn(&txn);
3046
3
            if (err != TxnErrorCode::TXN_OK) {
3047
0
                LOG_WARNING("failed to create txn").tag("err", err);
3048
0
                return -1;
3049
0
            }
3050
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3051
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3052
3
            std::string index_inverted_key = versioned::index_inverted_key(
3053
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3054
3
            versioned_remove_all(txn.get(), meta_key);
3055
3
            txn->remove(index_key);
3056
3
            txn->remove(index_inverted_key);
3057
3
            err = txn->commit();
3058
3
            if (err != TxnErrorCode::TXN_OK) {
3059
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3060
0
                return -1;
3061
0
            }
3062
3
        }
3063
3064
9
        metrics_context.total_recycled_num = ++num_recycled;
3065
9
        metrics_context.report();
3066
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3067
9
        index_keys.push_back(k);
3068
9
        return 0;
3069
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2967
5
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2968
5
        ++num_scanned;
2969
5
        RecycleIndexPB index_pb;
2970
5
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2971
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2972
0
            return -1;
2973
0
        }
2974
5
        int64_t current_time = ::time(nullptr);
2975
5
        if (current_time <
2976
5
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2977
0
            return 0;
2978
0
        }
2979
5
        ++num_expired;
2980
        // decode index_id
2981
5
        auto k1 = k;
2982
5
        k1.remove_prefix(1);
2983
5
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2984
5
        decode_key(&k1, &out);
2985
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2986
5
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2987
5
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2988
5
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2989
5
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2990
        // Change state to RECYCLING
2991
5
        std::unique_ptr<Transaction> txn;
2992
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2993
5
        if (err != TxnErrorCode::TXN_OK) {
2994
0
            LOG_WARNING("failed to create txn").tag("err", err);
2995
0
            return -1;
2996
0
        }
2997
5
        std::string val;
2998
5
        err = txn->get(k, &val);
2999
5
        if (err ==
3000
5
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3001
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3002
0
            return 0;
3003
0
        }
3004
5
        if (err != TxnErrorCode::TXN_OK) {
3005
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3006
0
            return -1;
3007
0
        }
3008
5
        index_pb.Clear();
3009
5
        if (!index_pb.ParseFromString(val)) {
3010
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3011
0
            return -1;
3012
0
        }
3013
5
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3014
4
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3015
4
            txn->put(k, index_pb.SerializeAsString());
3016
4
            err = txn->commit();
3017
4
            if (err != TxnErrorCode::TXN_OK) {
3018
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3019
0
                return -1;
3020
0
            }
3021
4
        }
3022
5
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3023
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
3024
0
                LOG_WARNING("failed to recycle table stream")
3025
0
                        .tag("instance_id", instance_id_)
3026
0
                        .tag("stream_id", index_id);
3027
0
                return -1;
3028
0
            }
3029
3
            metrics_context.total_recycled_num = ++num_recycled;
3030
3
            metrics_context.report();
3031
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3032
3
            return 0;
3033
3
        }
3034
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3035
1
            LOG_WARNING("failed to recycle tablets under index")
3036
1
                    .tag("table_id", index_pb.table_id())
3037
1
                    .tag("instance_id", instance_id_)
3038
1
                    .tag("index_id", index_id);
3039
1
            return -1;
3040
1
        }
3041
3042
1
        if (index_pb.has_db_id()) {
3043
            // Recycle the versioned keys
3044
1
            std::unique_ptr<Transaction> txn;
3045
1
            err = txn_kv_->create_txn(&txn);
3046
1
            if (err != TxnErrorCode::TXN_OK) {
3047
0
                LOG_WARNING("failed to create txn").tag("err", err);
3048
0
                return -1;
3049
0
            }
3050
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3051
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3052
1
            std::string index_inverted_key = versioned::index_inverted_key(
3053
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3054
1
            versioned_remove_all(txn.get(), meta_key);
3055
1
            txn->remove(index_key);
3056
1
            txn->remove(index_inverted_key);
3057
1
            err = txn->commit();
3058
1
            if (err != TxnErrorCode::TXN_OK) {
3059
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3060
0
                return -1;
3061
0
            }
3062
1
        }
3063
3064
1
        metrics_context.total_recycled_num = ++num_recycled;
3065
1
        metrics_context.report();
3066
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3067
1
        index_keys.push_back(k);
3068
1
        return 0;
3069
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2967
13
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2968
13
        ++num_scanned;
2969
13
        RecycleIndexPB index_pb;
2970
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2971
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2972
0
            return -1;
2973
0
        }
2974
13
        int64_t current_time = ::time(nullptr);
2975
13
        if (current_time <
2976
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2977
0
            return 0;
2978
0
        }
2979
13
        ++num_expired;
2980
        // decode index_id
2981
13
        auto k1 = k;
2982
13
        k1.remove_prefix(1);
2983
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2984
13
        decode_key(&k1, &out);
2985
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2986
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2987
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2988
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2989
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2990
        // Change state to RECYCLING
2991
13
        std::unique_ptr<Transaction> txn;
2992
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2993
13
        if (err != TxnErrorCode::TXN_OK) {
2994
0
            LOG_WARNING("failed to create txn").tag("err", err);
2995
0
            return -1;
2996
0
        }
2997
13
        std::string val;
2998
13
        err = txn->get(k, &val);
2999
13
        if (err ==
3000
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3001
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3002
0
            return 0;
3003
0
        }
3004
13
        if (err != TxnErrorCode::TXN_OK) {
3005
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3006
0
            return -1;
3007
0
        }
3008
13
        index_pb.Clear();
3009
13
        if (!index_pb.ParseFromString(val)) {
3010
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3011
0
            return -1;
3012
0
        }
3013
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3014
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3015
12
            txn->put(k, index_pb.SerializeAsString());
3016
12
            err = txn->commit();
3017
12
            if (err != TxnErrorCode::TXN_OK) {
3018
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3019
0
                return -1;
3020
0
            }
3021
12
        }
3022
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3023
5
            if (recycle_stream(index_id, index_pb, k) != 0) {
3024
0
                LOG_WARNING("failed to recycle table stream")
3025
0
                        .tag("instance_id", instance_id_)
3026
0
                        .tag("stream_id", index_id);
3027
0
                return -1;
3028
0
            }
3029
5
            metrics_context.total_recycled_num = ++num_recycled;
3030
5
            metrics_context.report();
3031
5
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3032
5
            return 0;
3033
5
        }
3034
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3035
0
            LOG_WARNING("failed to recycle tablets under index")
3036
0
                    .tag("table_id", index_pb.table_id())
3037
0
                    .tag("instance_id", instance_id_)
3038
0
                    .tag("index_id", index_id);
3039
0
            return -1;
3040
0
        }
3041
3042
8
        if (index_pb.has_db_id()) {
3043
            // Recycle the versioned keys
3044
2
            std::unique_ptr<Transaction> txn;
3045
2
            err = txn_kv_->create_txn(&txn);
3046
2
            if (err != TxnErrorCode::TXN_OK) {
3047
0
                LOG_WARNING("failed to create txn").tag("err", err);
3048
0
                return -1;
3049
0
            }
3050
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3051
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3052
2
            std::string index_inverted_key = versioned::index_inverted_key(
3053
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3054
2
            versioned_remove_all(txn.get(), meta_key);
3055
2
            txn->remove(index_key);
3056
2
            txn->remove(index_inverted_key);
3057
2
            err = txn->commit();
3058
2
            if (err != TxnErrorCode::TXN_OK) {
3059
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3060
0
                return -1;
3061
0
            }
3062
2
        }
3063
3064
8
        metrics_context.total_recycled_num = ++num_recycled;
3065
8
        metrics_context.report();
3066
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3067
8
        index_keys.push_back(k);
3068
8
        return 0;
3069
8
    };
3070
3071
25
    auto loop_done = [&index_keys, this]() -> int {
3072
13
        if (index_keys.empty()) return 0;
3073
5
        DORIS_CLOUD_DEFER {
3074
5
            index_keys.clear();
3075
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3073
1
        DORIS_CLOUD_DEFER {
3074
1
            index_keys.clear();
3075
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3073
4
        DORIS_CLOUD_DEFER {
3074
4
            index_keys.clear();
3075
4
        };
3076
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3077
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3078
0
            return -1;
3079
0
        }
3080
5
        return 0;
3081
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3071
4
    auto loop_done = [&index_keys, this]() -> int {
3072
4
        if (index_keys.empty()) return 0;
3073
1
        DORIS_CLOUD_DEFER {
3074
1
            index_keys.clear();
3075
1
        };
3076
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3077
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3078
0
            return -1;
3079
0
        }
3080
1
        return 0;
3081
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3071
9
    auto loop_done = [&index_keys, this]() -> int {
3072
9
        if (index_keys.empty()) return 0;
3073
4
        DORIS_CLOUD_DEFER {
3074
4
            index_keys.clear();
3075
4
        };
3076
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3077
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3078
0
            return -1;
3079
0
        }
3080
4
        return 0;
3081
4
    };
3082
3083
25
    if (config::enable_recycler_stats_metrics) {
3084
0
        scan_and_statistics_indexes();
3085
0
    }
3086
    // recycle_func and loop_done for scan and recycle
3087
25
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
3088
25
}
3089
3090
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
3091
8.25k
                             int64_t tablet_id) {
3092
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
3093
3094
8.25k
    std::unique_ptr<Transaction> txn;
3095
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
3096
8.25k
    if (err != TxnErrorCode::TXN_OK) {
3097
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
3098
0
                     << " tablet_id=" << tablet_id << " err=" << err;
3099
0
        return false;
3100
0
    }
3101
3102
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
3103
8.25k
    std::string tablet_idx_val;
3104
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
3105
8.25k
    if (TxnErrorCode::TXN_OK != err) {
3106
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
3107
0
                     << " tablet_id=" << tablet_id << " err=" << err
3108
0
                     << " key=" << hex(tablet_idx_key);
3109
0
        return false;
3110
0
    }
3111
3112
8.25k
    TabletIndexPB tablet_idx_pb;
3113
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
3114
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
3115
0
                     << " tablet_id=" << tablet_id;
3116
0
        return false;
3117
0
    }
3118
3119
8.25k
    if (!tablet_idx_pb.has_db_id()) {
3120
        // In the previous version, the db_id was not set in the index_pb.
3121
        // If updating to the version which enable txn lazy commit, the db_id will be set.
3122
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
3123
0
                  << " instance_id=" << instance_id
3124
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
3125
0
        return true;
3126
0
    }
3127
3128
8.25k
    std::string ver_val;
3129
8.25k
    std::string ver_key =
3130
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
3131
8.25k
                                   tablet_idx_pb.partition_id()});
3132
8.25k
    err = txn->get(ver_key, &ver_val);
3133
3134
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
3135
214
        LOG(INFO) << ""
3136
214
                     "partition version not found, instance_id="
3137
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
3138
214
                  << " table_id=" << tablet_idx_pb.table_id()
3139
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
3140
214
                  << " key=" << hex(ver_key);
3141
214
        return true;
3142
214
    }
3143
3144
8.03k
    if (TxnErrorCode::TXN_OK != err) {
3145
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
3146
0
                     << " db_id=" << tablet_idx_pb.db_id()
3147
0
                     << " table_id=" << tablet_idx_pb.table_id()
3148
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3149
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
3150
0
        return false;
3151
0
    }
3152
3153
8.03k
    VersionPB version_pb;
3154
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
3155
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
3156
0
                     << " db_id=" << tablet_idx_pb.db_id()
3157
0
                     << " table_id=" << tablet_idx_pb.table_id()
3158
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3159
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
3160
0
        return false;
3161
0
    }
3162
3163
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
3164
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
3165
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
3166
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
3167
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
3168
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
3169
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
3170
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
3171
4.00k
                     << " key=" << hex(ver_key);
3172
4.00k
        return false;
3173
4.00k
    }
3174
4.03k
    return true;
3175
8.03k
}
3176
3177
20
int InstanceRecycler::recycle_partitions() {
3178
20
    const std::string task_name = "recycle_partitions";
3179
20
    int64_t num_scanned = 0;
3180
20
    int64_t num_expired = 0;
3181
20
    int64_t num_recycled = 0;
3182
20
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
3183
3184
20
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
3185
20
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
3186
20
    std::string part_key0;
3187
20
    std::string part_key1;
3188
20
    recycle_partition_key(part_key_info0, &part_key0);
3189
20
    recycle_partition_key(part_key_info1, &part_key1);
3190
3191
20
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
3192
3193
20
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3194
20
    register_recycle_task(task_name, start_time);
3195
3196
20
    DORIS_CLOUD_DEFER {
3197
20
        unregister_recycle_task(task_name);
3198
20
        int64_t cost =
3199
20
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3200
20
        metrics_context.finish_report();
3201
20
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3202
20
                .tag("instance_id", instance_id_)
3203
20
                .tag("num_scanned", num_scanned)
3204
20
                .tag("num_expired", num_expired)
3205
20
                .tag("num_recycled", num_recycled);
3206
20
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3196
2
    DORIS_CLOUD_DEFER {
3197
2
        unregister_recycle_task(task_name);
3198
2
        int64_t cost =
3199
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3200
2
        metrics_context.finish_report();
3201
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3202
2
                .tag("instance_id", instance_id_)
3203
2
                .tag("num_scanned", num_scanned)
3204
2
                .tag("num_expired", num_expired)
3205
2
                .tag("num_recycled", num_recycled);
3206
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3196
18
    DORIS_CLOUD_DEFER {
3197
18
        unregister_recycle_task(task_name);
3198
18
        int64_t cost =
3199
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3200
18
        metrics_context.finish_report();
3201
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3202
18
                .tag("instance_id", instance_id_)
3203
18
                .tag("num_scanned", num_scanned)
3204
18
                .tag("num_expired", num_expired)
3205
18
                .tag("num_recycled", num_recycled);
3206
18
    };
3207
3208
20
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3209
3210
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3211
20
    std::vector<std::string_view> partition_keys;
3212
20
    std::vector<std::string> partition_version_keys;
3213
20
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3214
13
        ++num_scanned;
3215
13
        RecyclePartitionPB part_pb;
3216
13
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3217
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3218
0
            return -1;
3219
0
        }
3220
13
        int64_t current_time = ::time(nullptr);
3221
13
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3222
13
                                                            &earlest_ts)) { // not expired
3223
0
            return 0;
3224
0
        }
3225
13
        ++num_expired;
3226
        // decode partition_id
3227
13
        auto k1 = k;
3228
13
        k1.remove_prefix(1);
3229
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3230
13
        decode_key(&k1, &out);
3231
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3232
13
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3233
13
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3234
13
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3235
13
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3236
        // Change state to RECYCLING
3237
13
        std::unique_ptr<Transaction> txn;
3238
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3239
13
        if (err != TxnErrorCode::TXN_OK) {
3240
0
            LOG_WARNING("failed to create txn").tag("err", err);
3241
0
            return -1;
3242
0
        }
3243
13
        std::string val;
3244
13
        err = txn->get(k, &val);
3245
13
        if (err ==
3246
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3247
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3248
0
            return 0;
3249
0
        }
3250
13
        if (err != TxnErrorCode::TXN_OK) {
3251
0
            LOG_WARNING("failed to get kv");
3252
0
            return -1;
3253
0
        }
3254
13
        part_pb.Clear();
3255
13
        if (!part_pb.ParseFromString(val)) {
3256
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3257
0
            return -1;
3258
0
        }
3259
        // Partitions with PREPARED state MUST have no data
3260
13
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3261
11
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3262
11
            txn->put(k, part_pb.SerializeAsString());
3263
11
            err = txn->commit();
3264
11
            if (err != TxnErrorCode::TXN_OK) {
3265
0
                LOG_WARNING("failed to commit txn: {}", err);
3266
0
                return -1;
3267
0
            }
3268
11
        }
3269
3270
13
        int ret = 0;
3271
37
        for (int64_t index_id : part_pb.index_id()) {
3272
37
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3273
1
                LOG_WARNING("failed to recycle tablets under partition")
3274
1
                        .tag("table_id", part_pb.table_id())
3275
1
                        .tag("instance_id", instance_id_)
3276
1
                        .tag("index_id", index_id)
3277
1
                        .tag("partition_id", partition_id);
3278
1
                ret = -1;
3279
1
            }
3280
37
        }
3281
13
        if (ret == 0 && part_pb.has_db_id() &&
3282
13
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3283
12
                                                   partition_id, part_pb.table_streams()) != 0) {
3284
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3285
0
                    .tag("instance_id", instance_id_)
3286
0
                    .tag("table_id", part_pb.table_id())
3287
0
                    .tag("partition_id", partition_id);
3288
0
            ret = -1;
3289
0
        }
3290
13
        if (ret == 0 && part_pb.has_db_id()) {
3291
            // Recycle the versioned keys
3292
12
            std::unique_ptr<Transaction> txn;
3293
12
            err = txn_kv_->create_txn(&txn);
3294
12
            if (err != TxnErrorCode::TXN_OK) {
3295
0
                LOG_WARNING("failed to create txn").tag("err", err);
3296
0
                return -1;
3297
0
            }
3298
12
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3299
12
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3300
12
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3301
12
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3302
12
            std::string partition_version_key =
3303
12
                    versioned::partition_version_key({instance_id_, partition_id});
3304
12
            versioned_remove_all(txn.get(), meta_key);
3305
12
            txn->remove(index_key);
3306
12
            txn->remove(inverted_index_key);
3307
12
            versioned_remove_all(txn.get(), partition_version_key);
3308
12
            err = txn->commit();
3309
12
            if (err != TxnErrorCode::TXN_OK) {
3310
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3311
0
                return -1;
3312
0
            }
3313
12
        }
3314
3315
13
        if (ret == 0) {
3316
12
            ++num_recycled;
3317
12
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3318
12
            partition_keys.push_back(k);
3319
12
            if (part_pb.db_id() > 0) {
3320
12
                partition_version_keys.push_back(partition_version_key(
3321
12
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3322
12
            }
3323
12
            metrics_context.total_recycled_num = num_recycled;
3324
12
            metrics_context.report();
3325
12
        }
3326
13
        return ret;
3327
13
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3213
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3214
2
        ++num_scanned;
3215
2
        RecyclePartitionPB part_pb;
3216
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3217
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3218
0
            return -1;
3219
0
        }
3220
2
        int64_t current_time = ::time(nullptr);
3221
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3222
2
                                                            &earlest_ts)) { // not expired
3223
0
            return 0;
3224
0
        }
3225
2
        ++num_expired;
3226
        // decode partition_id
3227
2
        auto k1 = k;
3228
2
        k1.remove_prefix(1);
3229
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3230
2
        decode_key(&k1, &out);
3231
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3232
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3233
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3234
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3235
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3236
        // Change state to RECYCLING
3237
2
        std::unique_ptr<Transaction> txn;
3238
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3239
2
        if (err != TxnErrorCode::TXN_OK) {
3240
0
            LOG_WARNING("failed to create txn").tag("err", err);
3241
0
            return -1;
3242
0
        }
3243
2
        std::string val;
3244
2
        err = txn->get(k, &val);
3245
2
        if (err ==
3246
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3247
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3248
0
            return 0;
3249
0
        }
3250
2
        if (err != TxnErrorCode::TXN_OK) {
3251
0
            LOG_WARNING("failed to get kv");
3252
0
            return -1;
3253
0
        }
3254
2
        part_pb.Clear();
3255
2
        if (!part_pb.ParseFromString(val)) {
3256
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3257
0
            return -1;
3258
0
        }
3259
        // Partitions with PREPARED state MUST have no data
3260
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3261
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3262
1
            txn->put(k, part_pb.SerializeAsString());
3263
1
            err = txn->commit();
3264
1
            if (err != TxnErrorCode::TXN_OK) {
3265
0
                LOG_WARNING("failed to commit txn: {}", err);
3266
0
                return -1;
3267
0
            }
3268
1
        }
3269
3270
2
        int ret = 0;
3271
2
        for (int64_t index_id : part_pb.index_id()) {
3272
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3273
1
                LOG_WARNING("failed to recycle tablets under partition")
3274
1
                        .tag("table_id", part_pb.table_id())
3275
1
                        .tag("instance_id", instance_id_)
3276
1
                        .tag("index_id", index_id)
3277
1
                        .tag("partition_id", partition_id);
3278
1
                ret = -1;
3279
1
            }
3280
2
        }
3281
2
        if (ret == 0 && part_pb.has_db_id() &&
3282
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3283
1
                                                   partition_id, part_pb.table_streams()) != 0) {
3284
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3285
0
                    .tag("instance_id", instance_id_)
3286
0
                    .tag("table_id", part_pb.table_id())
3287
0
                    .tag("partition_id", partition_id);
3288
0
            ret = -1;
3289
0
        }
3290
2
        if (ret == 0 && part_pb.has_db_id()) {
3291
            // Recycle the versioned keys
3292
1
            std::unique_ptr<Transaction> txn;
3293
1
            err = txn_kv_->create_txn(&txn);
3294
1
            if (err != TxnErrorCode::TXN_OK) {
3295
0
                LOG_WARNING("failed to create txn").tag("err", err);
3296
0
                return -1;
3297
0
            }
3298
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3299
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3300
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3301
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3302
1
            std::string partition_version_key =
3303
1
                    versioned::partition_version_key({instance_id_, partition_id});
3304
1
            versioned_remove_all(txn.get(), meta_key);
3305
1
            txn->remove(index_key);
3306
1
            txn->remove(inverted_index_key);
3307
1
            versioned_remove_all(txn.get(), partition_version_key);
3308
1
            err = txn->commit();
3309
1
            if (err != TxnErrorCode::TXN_OK) {
3310
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3311
0
                return -1;
3312
0
            }
3313
1
        }
3314
3315
2
        if (ret == 0) {
3316
1
            ++num_recycled;
3317
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3318
1
            partition_keys.push_back(k);
3319
1
            if (part_pb.db_id() > 0) {
3320
1
                partition_version_keys.push_back(partition_version_key(
3321
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3322
1
            }
3323
1
            metrics_context.total_recycled_num = num_recycled;
3324
1
            metrics_context.report();
3325
1
        }
3326
2
        return ret;
3327
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3213
11
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3214
11
        ++num_scanned;
3215
11
        RecyclePartitionPB part_pb;
3216
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3217
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3218
0
            return -1;
3219
0
        }
3220
11
        int64_t current_time = ::time(nullptr);
3221
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3222
11
                                                            &earlest_ts)) { // not expired
3223
0
            return 0;
3224
0
        }
3225
11
        ++num_expired;
3226
        // decode partition_id
3227
11
        auto k1 = k;
3228
11
        k1.remove_prefix(1);
3229
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3230
11
        decode_key(&k1, &out);
3231
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3232
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3233
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3234
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3235
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3236
        // Change state to RECYCLING
3237
11
        std::unique_ptr<Transaction> txn;
3238
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3239
11
        if (err != TxnErrorCode::TXN_OK) {
3240
0
            LOG_WARNING("failed to create txn").tag("err", err);
3241
0
            return -1;
3242
0
        }
3243
11
        std::string val;
3244
11
        err = txn->get(k, &val);
3245
11
        if (err ==
3246
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3247
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3248
0
            return 0;
3249
0
        }
3250
11
        if (err != TxnErrorCode::TXN_OK) {
3251
0
            LOG_WARNING("failed to get kv");
3252
0
            return -1;
3253
0
        }
3254
11
        part_pb.Clear();
3255
11
        if (!part_pb.ParseFromString(val)) {
3256
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3257
0
            return -1;
3258
0
        }
3259
        // Partitions with PREPARED state MUST have no data
3260
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3261
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3262
10
            txn->put(k, part_pb.SerializeAsString());
3263
10
            err = txn->commit();
3264
10
            if (err != TxnErrorCode::TXN_OK) {
3265
0
                LOG_WARNING("failed to commit txn: {}", err);
3266
0
                return -1;
3267
0
            }
3268
10
        }
3269
3270
11
        int ret = 0;
3271
35
        for (int64_t index_id : part_pb.index_id()) {
3272
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3273
0
                LOG_WARNING("failed to recycle tablets under partition")
3274
0
                        .tag("table_id", part_pb.table_id())
3275
0
                        .tag("instance_id", instance_id_)
3276
0
                        .tag("index_id", index_id)
3277
0
                        .tag("partition_id", partition_id);
3278
0
                ret = -1;
3279
0
            }
3280
35
        }
3281
11
        if (ret == 0 && part_pb.has_db_id() &&
3282
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3283
11
                                                   partition_id, part_pb.table_streams()) != 0) {
3284
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3285
0
                    .tag("instance_id", instance_id_)
3286
0
                    .tag("table_id", part_pb.table_id())
3287
0
                    .tag("partition_id", partition_id);
3288
0
            ret = -1;
3289
0
        }
3290
11
        if (ret == 0 && part_pb.has_db_id()) {
3291
            // Recycle the versioned keys
3292
11
            std::unique_ptr<Transaction> txn;
3293
11
            err = txn_kv_->create_txn(&txn);
3294
11
            if (err != TxnErrorCode::TXN_OK) {
3295
0
                LOG_WARNING("failed to create txn").tag("err", err);
3296
0
                return -1;
3297
0
            }
3298
11
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3299
11
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3300
11
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3301
11
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3302
11
            std::string partition_version_key =
3303
11
                    versioned::partition_version_key({instance_id_, partition_id});
3304
11
            versioned_remove_all(txn.get(), meta_key);
3305
11
            txn->remove(index_key);
3306
11
            txn->remove(inverted_index_key);
3307
11
            versioned_remove_all(txn.get(), partition_version_key);
3308
11
            err = txn->commit();
3309
11
            if (err != TxnErrorCode::TXN_OK) {
3310
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3311
0
                return -1;
3312
0
            }
3313
11
        }
3314
3315
11
        if (ret == 0) {
3316
11
            ++num_recycled;
3317
11
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3318
11
            partition_keys.push_back(k);
3319
11
            if (part_pb.db_id() > 0) {
3320
11
                partition_version_keys.push_back(partition_version_key(
3321
11
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3322
11
            }
3323
11
            metrics_context.total_recycled_num = num_recycled;
3324
11
            metrics_context.report();
3325
11
        }
3326
11
        return ret;
3327
11
    };
3328
3329
20
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3330
9
        if (partition_keys.empty()) return 0;
3331
8
        DORIS_CLOUD_DEFER {
3332
8
            partition_keys.clear();
3333
8
            partition_version_keys.clear();
3334
8
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3331
1
        DORIS_CLOUD_DEFER {
3332
1
            partition_keys.clear();
3333
1
            partition_version_keys.clear();
3334
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3331
7
        DORIS_CLOUD_DEFER {
3332
7
            partition_keys.clear();
3333
7
            partition_version_keys.clear();
3334
7
        };
3335
8
        std::unique_ptr<Transaction> txn;
3336
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3337
8
        if (err != TxnErrorCode::TXN_OK) {
3338
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3339
0
            return -1;
3340
0
        }
3341
12
        for (auto& k : partition_keys) {
3342
12
            txn->remove(k);
3343
12
        }
3344
12
        for (auto& k : partition_version_keys) {
3345
12
            txn->remove(k);
3346
12
        }
3347
8
        err = txn->commit();
3348
8
        if (err != TxnErrorCode::TXN_OK) {
3349
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3350
0
                         << " err=" << err;
3351
0
            return -1;
3352
0
        }
3353
8
        return 0;
3354
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3329
2
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3330
2
        if (partition_keys.empty()) return 0;
3331
1
        DORIS_CLOUD_DEFER {
3332
1
            partition_keys.clear();
3333
1
            partition_version_keys.clear();
3334
1
        };
3335
1
        std::unique_ptr<Transaction> txn;
3336
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3337
1
        if (err != TxnErrorCode::TXN_OK) {
3338
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3339
0
            return -1;
3340
0
        }
3341
1
        for (auto& k : partition_keys) {
3342
1
            txn->remove(k);
3343
1
        }
3344
1
        for (auto& k : partition_version_keys) {
3345
1
            txn->remove(k);
3346
1
        }
3347
1
        err = txn->commit();
3348
1
        if (err != TxnErrorCode::TXN_OK) {
3349
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3350
0
                         << " err=" << err;
3351
0
            return -1;
3352
0
        }
3353
1
        return 0;
3354
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3329
7
    auto loop_done = [&partition_keys, &partition_version_keys, this]() -> int {
3330
7
        if (partition_keys.empty()) return 0;
3331
7
        DORIS_CLOUD_DEFER {
3332
7
            partition_keys.clear();
3333
7
            partition_version_keys.clear();
3334
7
        };
3335
7
        std::unique_ptr<Transaction> txn;
3336
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3337
7
        if (err != TxnErrorCode::TXN_OK) {
3338
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3339
0
            return -1;
3340
0
        }
3341
11
        for (auto& k : partition_keys) {
3342
11
            txn->remove(k);
3343
11
        }
3344
11
        for (auto& k : partition_version_keys) {
3345
11
            txn->remove(k);
3346
11
        }
3347
7
        err = txn->commit();
3348
7
        if (err != TxnErrorCode::TXN_OK) {
3349
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3350
0
                         << " err=" << err;
3351
0
            return -1;
3352
0
        }
3353
7
        return 0;
3354
7
    };
3355
3356
20
    if (config::enable_recycler_stats_metrics) {
3357
0
        scan_and_statistics_partitions();
3358
0
    }
3359
    // recycle_func and loop_done for scan and recycle
3360
20
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3361
20
}
3362
3363
14
int InstanceRecycler::recycle_versions() {
3364
14
    if (should_recycle_versioned_keys()) {
3365
2
        return recycle_orphan_partitions();
3366
2
    }
3367
3368
12
    int64_t num_scanned = 0;
3369
12
    int64_t num_recycled = 0;
3370
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3371
3372
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3373
3374
12
    auto start_time = steady_clock::now();
3375
3376
12
    DORIS_CLOUD_DEFER {
3377
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3378
12
        metrics_context.finish_report();
3379
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3380
12
                .tag("instance_id", instance_id_)
3381
12
                .tag("num_scanned", num_scanned)
3382
12
                .tag("num_recycled", num_recycled);
3383
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3376
12
    DORIS_CLOUD_DEFER {
3377
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3378
12
        metrics_context.finish_report();
3379
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3380
12
                .tag("instance_id", instance_id_)
3381
12
                .tag("num_scanned", num_scanned)
3382
12
                .tag("num_recycled", num_recycled);
3383
12
    };
3384
3385
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3386
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3387
12
    int64_t last_scanned_table_id = 0;
3388
12
    bool is_recycled = false; // Is last scanned kv recycled
3389
12
    auto recycle_func = [&num_scanned, &num_recycled, &last_scanned_table_id, &is_recycled,
3390
12
                         &metrics_context, this](std::string_view k, std::string_view) {
3391
2
        ++num_scanned;
3392
2
        auto k1 = k;
3393
2
        k1.remove_prefix(1);
3394
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3395
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3396
2
        decode_key(&k1, &out);
3397
2
        DCHECK_EQ(out.size(), 6) << k;
3398
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3399
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3400
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3401
0
            return 0;
3402
0
        }
3403
2
        last_scanned_table_id = table_id;
3404
2
        is_recycled = false;
3405
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3406
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3407
2
        std::unique_ptr<Transaction> txn;
3408
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3409
2
        if (err != TxnErrorCode::TXN_OK) {
3410
0
            return -1;
3411
0
        }
3412
2
        std::unique_ptr<RangeGetIterator> iter;
3413
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3414
2
        if (err != TxnErrorCode::TXN_OK) {
3415
0
            return -1;
3416
0
        }
3417
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3418
1
            return 0;
3419
1
        }
3420
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3421
        // 1. Remove all partition version kvs of this table
3422
1
        auto partition_version_key_begin =
3423
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3424
1
        auto partition_version_key_end =
3425
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3426
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3427
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3428
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3429
1
                     << " table_id=" << table_id;
3430
        // 2. Remove the table version kv of this table
3431
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3432
1
        txn->remove(tbl_version_key);
3433
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3434
        // 3. Remove mow delete bitmap update lock and tablet job lock
3435
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3436
1
        txn->remove(lock_key);
3437
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3438
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3439
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3440
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3441
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3442
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3443
1
                     << " table_id=" << table_id;
3444
1
        err = txn->commit();
3445
1
        if (err != TxnErrorCode::TXN_OK) {
3446
0
            return -1;
3447
0
        }
3448
1
        metrics_context.total_recycled_num = ++num_recycled;
3449
1
        metrics_context.report();
3450
1
        is_recycled = true;
3451
1
        return 0;
3452
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3390
2
                         &metrics_context, this](std::string_view k, std::string_view) {
3391
2
        ++num_scanned;
3392
2
        auto k1 = k;
3393
2
        k1.remove_prefix(1);
3394
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3395
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3396
2
        decode_key(&k1, &out);
3397
2
        DCHECK_EQ(out.size(), 6) << k;
3398
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3399
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3400
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3401
0
            return 0;
3402
0
        }
3403
2
        last_scanned_table_id = table_id;
3404
2
        is_recycled = false;
3405
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3406
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3407
2
        std::unique_ptr<Transaction> txn;
3408
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3409
2
        if (err != TxnErrorCode::TXN_OK) {
3410
0
            return -1;
3411
0
        }
3412
2
        std::unique_ptr<RangeGetIterator> iter;
3413
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3414
2
        if (err != TxnErrorCode::TXN_OK) {
3415
0
            return -1;
3416
0
        }
3417
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3418
1
            return 0;
3419
1
        }
3420
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3421
        // 1. Remove all partition version kvs of this table
3422
1
        auto partition_version_key_begin =
3423
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3424
1
        auto partition_version_key_end =
3425
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3426
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3427
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3428
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3429
1
                     << " table_id=" << table_id;
3430
        // 2. Remove the table version kv of this table
3431
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3432
1
        txn->remove(tbl_version_key);
3433
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3434
        // 3. Remove mow delete bitmap update lock and tablet job lock
3435
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3436
1
        txn->remove(lock_key);
3437
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3438
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3439
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3440
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3441
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3442
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3443
1
                     << " table_id=" << table_id;
3444
1
        err = txn->commit();
3445
1
        if (err != TxnErrorCode::TXN_OK) {
3446
0
            return -1;
3447
0
        }
3448
1
        metrics_context.total_recycled_num = ++num_recycled;
3449
1
        metrics_context.report();
3450
1
        is_recycled = true;
3451
1
        return 0;
3452
1
    };
3453
3454
12
    if (config::enable_recycler_stats_metrics) {
3455
0
        scan_and_statistics_versions();
3456
0
    }
3457
    // recycle_func and loop_done for scan and recycle
3458
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func));
3459
14
}
3460
3461
3
int InstanceRecycler::recycle_orphan_partitions() {
3462
3
    int64_t num_scanned = 0;
3463
3
    int64_t num_recycled = 0;
3464
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3465
3466
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3467
3
            .tag("instance_id", instance_id_);
3468
3469
3
    auto start_time = steady_clock::now();
3470
3471
3
    DORIS_CLOUD_DEFER {
3472
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3473
3
        metrics_context.finish_report();
3474
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3475
3
                .tag("instance_id", instance_id_)
3476
3
                .tag("num_scanned", num_scanned)
3477
3
                .tag("num_recycled", num_recycled);
3478
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3471
3
    DORIS_CLOUD_DEFER {
3472
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3473
3
        metrics_context.finish_report();
3474
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3475
3
                .tag("instance_id", instance_id_)
3476
3
                .tag("num_scanned", num_scanned)
3477
3
                .tag("num_recycled", num_recycled);
3478
3
    };
3479
3480
3
    bool is_empty_table = false;        // whether the table has no indexes
3481
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3482
3
    int64_t current_table_id = 0;       // current scanning table id
3483
3
    auto recycle_func = [&num_scanned, &num_recycled, &metrics_context, &is_empty_table,
3484
3
                         &current_table_id, &is_table_kvs_recycled,
3485
3
                         this](std::string_view k, std::string_view) {
3486
2
        ++num_scanned;
3487
3488
2
        std::string_view k1(k);
3489
2
        int64_t db_id, table_id, partition_id;
3490
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3491
2
                                                            &partition_id)) {
3492
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3493
0
            return -1;
3494
2
        } else if (table_id != current_table_id) {
3495
2
            current_table_id = table_id;
3496
2
            is_table_kvs_recycled = false;
3497
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3498
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3499
2
            if (err != TxnErrorCode::TXN_OK) {
3500
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3501
0
                             << " table_id=" << table_id << " err=" << err;
3502
0
                return -1;
3503
0
            }
3504
2
        }
3505
3506
2
        if (!is_empty_table) {
3507
            // table is not empty, skip recycle
3508
1
            return 0;
3509
1
        }
3510
3511
1
        std::unique_ptr<Transaction> txn;
3512
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3513
1
        if (err != TxnErrorCode::TXN_OK) {
3514
0
            return -1;
3515
0
        }
3516
3517
        // 1. Remove all partition related kvs
3518
1
        std::string partition_meta_key =
3519
1
                versioned::meta_partition_key({instance_id_, partition_id});
3520
1
        std::string partition_index_key =
3521
1
                versioned::partition_index_key({instance_id_, partition_id});
3522
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3523
1
                {instance_id_, db_id, table_id, partition_id});
3524
1
        std::string partition_version_key =
3525
1
                versioned::partition_version_key({instance_id_, partition_id});
3526
1
        txn->remove(partition_index_key);
3527
1
        txn->remove(partition_inverted_key);
3528
1
        versioned_remove_all(txn.get(), partition_meta_key);
3529
1
        versioned_remove_all(txn.get(), partition_version_key);
3530
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3531
1
                     << " table_id=" << table_id << " db_id=" << db_id
3532
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3533
1
                     << " partition_version_key=" << hex(partition_version_key);
3534
3535
1
        if (!is_table_kvs_recycled) {
3536
1
            is_table_kvs_recycled = true;
3537
3538
            // 2. Remove the table version kv of this table
3539
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3540
1
            versioned_remove_all(txn.get(), table_version_key);
3541
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3542
            // 3. Remove mow delete bitmap update lock and tablet job lock
3543
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3544
1
            txn->remove(lock_key);
3545
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3546
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3547
1
            std::string tablet_job_key_end =
3548
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3549
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3550
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3551
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3552
1
                         << " table_id=" << table_id;
3553
1
        }
3554
3555
1
        err = txn->commit();
3556
1
        if (err != TxnErrorCode::TXN_OK) {
3557
0
            return -1;
3558
0
        }
3559
1
        metrics_context.total_recycled_num = ++num_recycled;
3560
1
        metrics_context.report();
3561
1
        return 0;
3562
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3485
2
                         this](std::string_view k, std::string_view) {
3486
2
        ++num_scanned;
3487
3488
2
        std::string_view k1(k);
3489
2
        int64_t db_id, table_id, partition_id;
3490
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3491
2
                                                            &partition_id)) {
3492
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3493
0
            return -1;
3494
2
        } else if (table_id != current_table_id) {
3495
2
            current_table_id = table_id;
3496
2
            is_table_kvs_recycled = false;
3497
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3498
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3499
2
            if (err != TxnErrorCode::TXN_OK) {
3500
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3501
0
                             << " table_id=" << table_id << " err=" << err;
3502
0
                return -1;
3503
0
            }
3504
2
        }
3505
3506
2
        if (!is_empty_table) {
3507
            // table is not empty, skip recycle
3508
1
            return 0;
3509
1
        }
3510
3511
1
        std::unique_ptr<Transaction> txn;
3512
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3513
1
        if (err != TxnErrorCode::TXN_OK) {
3514
0
            return -1;
3515
0
        }
3516
3517
        // 1. Remove all partition related kvs
3518
1
        std::string partition_meta_key =
3519
1
                versioned::meta_partition_key({instance_id_, partition_id});
3520
1
        std::string partition_index_key =
3521
1
                versioned::partition_index_key({instance_id_, partition_id});
3522
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3523
1
                {instance_id_, db_id, table_id, partition_id});
3524
1
        std::string partition_version_key =
3525
1
                versioned::partition_version_key({instance_id_, partition_id});
3526
1
        txn->remove(partition_index_key);
3527
1
        txn->remove(partition_inverted_key);
3528
1
        versioned_remove_all(txn.get(), partition_meta_key);
3529
1
        versioned_remove_all(txn.get(), partition_version_key);
3530
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3531
1
                     << " table_id=" << table_id << " db_id=" << db_id
3532
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3533
1
                     << " partition_version_key=" << hex(partition_version_key);
3534
3535
1
        if (!is_table_kvs_recycled) {
3536
1
            is_table_kvs_recycled = true;
3537
3538
            // 2. Remove the table version kv of this table
3539
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3540
1
            versioned_remove_all(txn.get(), table_version_key);
3541
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3542
            // 3. Remove mow delete bitmap update lock and tablet job lock
3543
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3544
1
            txn->remove(lock_key);
3545
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3546
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3547
1
            std::string tablet_job_key_end =
3548
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3549
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3550
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3551
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3552
1
                         << " table_id=" << table_id;
3553
1
        }
3554
3555
1
        err = txn->commit();
3556
1
        if (err != TxnErrorCode::TXN_OK) {
3557
0
            return -1;
3558
0
        }
3559
1
        metrics_context.total_recycled_num = ++num_recycled;
3560
1
        metrics_context.report();
3561
1
        return 0;
3562
1
    };
3563
3564
    // recycle_func and loop_done for scan and recycle
3565
3
    return scan_and_recycle(
3566
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3567
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3568
3
            std::move(recycle_func));
3569
3
}
3570
3571
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3572
                                      RecyclerMetricsContext& metrics_context,
3573
56
                                      int64_t partition_id) {
3574
56
    bool is_multi_version =
3575
56
            instance_info_.has_multi_version_status() &&
3576
56
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3577
56
    int64_t num_scanned = 0;
3578
56
    std::atomic_long num_recycled = 0;
3579
3580
56
    std::string tablet_key_begin, tablet_key_end;
3581
56
    std::string stats_key_begin, stats_key_end;
3582
56
    std::string job_key_begin, job_key_end;
3583
3584
56
    std::string tablet_belongs;
3585
56
    if (partition_id > 0) {
3586
        // recycle tablets in a partition belonging to the index
3587
37
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3588
37
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3589
37
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3590
37
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3591
37
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3592
37
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3593
37
        tablet_belongs = "partition";
3594
37
    } else {
3595
        // recycle tablets in the index
3596
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3597
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3598
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3599
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3600
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3601
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3602
19
        tablet_belongs = "index";
3603
19
    }
3604
3605
56
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3606
56
            .tag("table_id", table_id)
3607
56
            .tag("index_id", index_id)
3608
56
            .tag("partition_id", partition_id);
3609
3610
56
    auto start_time = steady_clock::now();
3611
3612
56
    DORIS_CLOUD_DEFER {
3613
56
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3614
56
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3615
56
                .tag("instance_id", instance_id_)
3616
56
                .tag("table_id", table_id)
3617
56
                .tag("index_id", index_id)
3618
56
                .tag("partition_id", partition_id)
3619
56
                .tag("num_scanned", num_scanned)
3620
56
                .tag("num_recycled", num_recycled);
3621
56
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3612
4
    DORIS_CLOUD_DEFER {
3613
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3614
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3615
4
                .tag("instance_id", instance_id_)
3616
4
                .tag("table_id", table_id)
3617
4
                .tag("index_id", index_id)
3618
4
                .tag("partition_id", partition_id)
3619
4
                .tag("num_scanned", num_scanned)
3620
4
                .tag("num_recycled", num_recycled);
3621
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3612
52
    DORIS_CLOUD_DEFER {
3613
52
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3614
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3615
52
                .tag("instance_id", instance_id_)
3616
52
                .tag("table_id", table_id)
3617
52
                .tag("index_id", index_id)
3618
52
                .tag("partition_id", partition_id)
3619
52
                .tag("num_scanned", num_scanned)
3620
52
                .tag("num_recycled", num_recycled);
3621
52
    };
3622
3623
    // The tablet key and id which have been recycled.
3624
56
    struct TabletInfo {
3625
56
        std::string_view tablet_meta_key;
3626
56
        int64_t tablet_id;
3627
56
    };
3628
56
    SyncExecutor<TabletInfo> sync_executor(
3629
56
            _thread_pool_group.recycle_tablet_pool,
3630
56
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3631
56
                        index_id, partition_id),
3632
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3632
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3632
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3633
3634
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3635
56
    std::vector<std::string> init_rs_keys;
3636
56
    bool has_failure = false;
3637
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3638
8.25k
        ++num_scanned;
3639
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3640
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3641
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3642
0
            has_failure = true;
3643
0
            return -1;
3644
0
        }
3645
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3646
3647
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3648
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3649
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3650
4.00k
            has_failure = true;
3651
4.00k
            return -1;
3652
4.00k
        }
3653
3654
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3655
4.25k
        sync_executor.add(
3656
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3657
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3658
2
                        LOG_WARNING("failed to recycle tablet")
3659
2
                                .tag("instance_id", instance_id_)
3660
2
                                .tag("tablet_id", tid);
3661
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3662
2
                    }
3663
4.25k
                    ++num_recycled;
3664
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3665
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3666
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3656
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3657
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3658
0
                        LOG_WARNING("failed to recycle tablet")
3659
0
                                .tag("instance_id", instance_id_)
3660
0
                                .tag("tablet_id", tid);
3661
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3662
0
                    }
3663
4.00k
                    ++num_recycled;
3664
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3665
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3666
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3656
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3657
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3658
2
                        LOG_WARNING("failed to recycle tablet")
3659
2
                                .tag("instance_id", instance_id_)
3660
2
                                .tag("tablet_id", tid);
3661
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3662
2
                    }
3663
248
                    ++num_recycled;
3664
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3665
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3666
250
                });
3667
4.25k
        return 0;
3668
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3637
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3638
8.00k
        ++num_scanned;
3639
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3640
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3641
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3642
0
            has_failure = true;
3643
0
            return -1;
3644
0
        }
3645
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3646
3647
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3648
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3649
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3650
4.00k
            has_failure = true;
3651
4.00k
            return -1;
3652
4.00k
        }
3653
3654
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3655
4.00k
        sync_executor.add(
3656
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3657
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3658
4.00k
                        LOG_WARNING("failed to recycle tablet")
3659
4.00k
                                .tag("instance_id", instance_id_)
3660
4.00k
                                .tag("tablet_id", tid);
3661
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3662
4.00k
                    }
3663
4.00k
                    ++num_recycled;
3664
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3665
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3666
4.00k
                });
3667
4.00k
        return 0;
3668
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3637
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3638
251
        ++num_scanned;
3639
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3640
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3641
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3642
0
            has_failure = true;
3643
0
            return -1;
3644
0
        }
3645
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3646
3647
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3648
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3649
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3650
1
            has_failure = true;
3651
1
            return -1;
3652
1
        }
3653
3654
251
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3655
250
        sync_executor.add(
3656
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3657
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3658
250
                        LOG_WARNING("failed to recycle tablet")
3659
250
                                .tag("instance_id", instance_id_)
3660
250
                                .tag("tablet_id", tid);
3661
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3662
250
                    }
3663
250
                    ++num_recycled;
3664
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3665
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3666
250
                });
3667
250
        return 0;
3668
250
    };
3669
3670
56
    auto loop_done = [&, this]() -> int {
3671
52
        int ret = 0;
3672
52
        bool finished = true;
3673
52
        bool has_empty_key = false;
3674
52
        DORIS_CLOUD_DEFER {
3675
52
            init_rs_keys.clear();
3676
52
            has_failure = false;
3677
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3674
4
        DORIS_CLOUD_DEFER {
3675
4
            init_rs_keys.clear();
3676
4
            has_failure = false;
3677
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3674
48
        DORIS_CLOUD_DEFER {
3675
48
            init_rs_keys.clear();
3676
48
            has_failure = false;
3677
48
        };
3678
52
        auto tablets_info = sync_executor.when_all(&finished);
3679
52
        if (!finished) {
3680
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3681
1
            return -1;
3682
1
        }
3683
3684
51
        size_t size_before_erase = tablets_info.size();
3685
4.25k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3685
4.00k
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKZNS1_15recycle_tabletsEllS3_lE10TabletInfoE_clES7_
Line
Count
Source
3685
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3686
51
        if (tablets_info.empty()) {
3687
2
            return size_before_erase == 0 ? 0 : -1;
3688
49
        } else if (size_before_erase != tablets_info.size()) {
3689
1
            has_empty_key = true;
3690
1
        }
3691
3692
49
        ret = has_empty_key ? -1 : 0;
3693
        // sort the vector using key's order
3694
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3695
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3696
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3694
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3695
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3696
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3694
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3695
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3696
958
        });
3697
49
        std::unique_ptr<Transaction> txn;
3698
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3699
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3700
0
            return -1;
3701
0
        }
3702
49
        std::string tablet_key_end;
3703
49
        if (!tablets_info.empty()) {
3704
49
            if (!has_empty_key && !has_failure) {
3705
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3706
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3707
47
            } else {
3708
8
                for (auto& tablet_info : tablets_info) {
3709
8
                    txn->remove(tablet_info.tablet_meta_key);
3710
8
                }
3711
2
            }
3712
49
        }
3713
49
        if (is_multi_version) {
3714
6
            for (auto& tablet_info : tablets_info) {
3715
                // Remove all versions of tablet compact stats for recycled tablet
3716
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3717
6
                LOG_INFO("remove versioned tablet compact stats key")
3718
6
                        .tag("compact_stats_key", hex(k));
3719
6
                versioned_remove_all(txn.get(), k);
3720
6
            }
3721
6
            for (auto& tablet_info : tablets_info) {
3722
                // Remove all versions of tablet load stats for recycled tablet
3723
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3724
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3725
6
                versioned_remove_all(txn.get(), k);
3726
6
            }
3727
6
            for (auto& tablet_info : tablets_info) {
3728
                // Remove all versions of meta tablet for recycled tablet
3729
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3730
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3731
6
                versioned_remove_all(txn.get(), k);
3732
6
            }
3733
5
        }
3734
4.25k
        for (auto& tablet_info : tablets_info) {
3735
4.25k
            std::string k;
3736
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3737
4.25k
            txn->remove(k);
3738
4.25k
        }
3739
4.25k
        for (auto& tablet_info : tablets_info) {
3740
4.25k
            std::string k;
3741
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3742
4.25k
            txn->remove(k);
3743
4.25k
        }
3744
49
        for (auto& k : init_rs_keys) {
3745
0
            txn->remove(k);
3746
0
        }
3747
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3748
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3749
0
                         << ", err=" << err;
3750
0
            return -1;
3751
0
        }
3752
49
        return ret;
3753
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3670
4
    auto loop_done = [&, this]() -> int {
3671
4
        int ret = 0;
3672
4
        bool finished = true;
3673
4
        bool has_empty_key = false;
3674
4
        DORIS_CLOUD_DEFER {
3675
4
            init_rs_keys.clear();
3676
4
            has_failure = false;
3677
4
        };
3678
4
        auto tablets_info = sync_executor.when_all(&finished);
3679
4
        if (!finished) {
3680
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3681
0
            return -1;
3682
0
        }
3683
3684
4
        size_t size_before_erase = tablets_info.size();
3685
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3686
4
        if (tablets_info.empty()) {
3687
2
            return size_before_erase == 0 ? 0 : -1;
3688
2
        } else if (size_before_erase != tablets_info.size()) {
3689
0
            has_empty_key = true;
3690
0
        }
3691
3692
2
        ret = has_empty_key ? -1 : 0;
3693
        // sort the vector using key's order
3694
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3695
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3696
2
        });
3697
2
        std::unique_ptr<Transaction> txn;
3698
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3699
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3700
0
            return -1;
3701
0
        }
3702
2
        std::string tablet_key_end;
3703
2
        if (!tablets_info.empty()) {
3704
2
            if (!has_empty_key && !has_failure) {
3705
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3706
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3707
2
            } else {
3708
0
                for (auto& tablet_info : tablets_info) {
3709
0
                    txn->remove(tablet_info.tablet_meta_key);
3710
0
                }
3711
0
            }
3712
2
        }
3713
2
        if (is_multi_version) {
3714
0
            for (auto& tablet_info : tablets_info) {
3715
                // Remove all versions of tablet compact stats for recycled tablet
3716
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3717
0
                LOG_INFO("remove versioned tablet compact stats key")
3718
0
                        .tag("compact_stats_key", hex(k));
3719
0
                versioned_remove_all(txn.get(), k);
3720
0
            }
3721
0
            for (auto& tablet_info : tablets_info) {
3722
                // Remove all versions of tablet load stats for recycled tablet
3723
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3724
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3725
0
                versioned_remove_all(txn.get(), k);
3726
0
            }
3727
0
            for (auto& tablet_info : tablets_info) {
3728
                // Remove all versions of meta tablet for recycled tablet
3729
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3730
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3731
0
                versioned_remove_all(txn.get(), k);
3732
0
            }
3733
0
        }
3734
4.00k
        for (auto& tablet_info : tablets_info) {
3735
4.00k
            std::string k;
3736
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3737
4.00k
            txn->remove(k);
3738
4.00k
        }
3739
4.00k
        for (auto& tablet_info : tablets_info) {
3740
4.00k
            std::string k;
3741
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3742
4.00k
            txn->remove(k);
3743
4.00k
        }
3744
2
        for (auto& k : init_rs_keys) {
3745
0
            txn->remove(k);
3746
0
        }
3747
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3748
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3749
0
                         << ", err=" << err;
3750
0
            return -1;
3751
0
        }
3752
2
        return ret;
3753
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3670
48
    auto loop_done = [&, this]() -> int {
3671
48
        int ret = 0;
3672
48
        bool finished = true;
3673
48
        bool has_empty_key = false;
3674
48
        DORIS_CLOUD_DEFER {
3675
48
            init_rs_keys.clear();
3676
48
            has_failure = false;
3677
48
        };
3678
48
        auto tablets_info = sync_executor.when_all(&finished);
3679
48
        if (!finished) {
3680
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3681
1
            return -1;
3682
1
        }
3683
3684
47
        size_t size_before_erase = tablets_info.size();
3685
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3686
47
        if (tablets_info.empty()) {
3687
0
            return size_before_erase == 0 ? 0 : -1;
3688
47
        } else if (size_before_erase != tablets_info.size()) {
3689
1
            has_empty_key = true;
3690
1
        }
3691
3692
47
        ret = has_empty_key ? -1 : 0;
3693
        // sort the vector using key's order
3694
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3695
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3696
47
        });
3697
47
        std::unique_ptr<Transaction> txn;
3698
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3699
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3700
0
            return -1;
3701
0
        }
3702
47
        std::string tablet_key_end;
3703
47
        if (!tablets_info.empty()) {
3704
47
            if (!has_empty_key && !has_failure) {
3705
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3706
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3707
45
            } else {
3708
8
                for (auto& tablet_info : tablets_info) {
3709
8
                    txn->remove(tablet_info.tablet_meta_key);
3710
8
                }
3711
2
            }
3712
47
        }
3713
47
        if (is_multi_version) {
3714
6
            for (auto& tablet_info : tablets_info) {
3715
                // Remove all versions of tablet compact stats for recycled tablet
3716
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3717
6
                LOG_INFO("remove versioned tablet compact stats key")
3718
6
                        .tag("compact_stats_key", hex(k));
3719
6
                versioned_remove_all(txn.get(), k);
3720
6
            }
3721
6
            for (auto& tablet_info : tablets_info) {
3722
                // Remove all versions of tablet load stats for recycled tablet
3723
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3724
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3725
6
                versioned_remove_all(txn.get(), k);
3726
6
            }
3727
6
            for (auto& tablet_info : tablets_info) {
3728
                // Remove all versions of meta tablet for recycled tablet
3729
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3730
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3731
6
                versioned_remove_all(txn.get(), k);
3732
6
            }
3733
5
        }
3734
248
        for (auto& tablet_info : tablets_info) {
3735
248
            std::string k;
3736
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3737
248
            txn->remove(k);
3738
248
        }
3739
248
        for (auto& tablet_info : tablets_info) {
3740
248
            std::string k;
3741
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3742
248
            txn->remove(k);
3743
248
        }
3744
47
        for (auto& k : init_rs_keys) {
3745
0
            txn->remove(k);
3746
0
        }
3747
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3748
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3749
0
                         << ", err=" << err;
3750
0
            return -1;
3751
0
        }
3752
47
        return ret;
3753
47
    };
3754
3755
56
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3756
56
                               std::move(loop_done));
3757
56
    if (ret != 0) {
3758
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3759
5
        return ret;
3760
5
    }
3761
3762
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3763
51
    std::unique_ptr<Transaction> txn;
3764
51
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3765
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3766
0
        return -1;
3767
0
    }
3768
51
    txn->remove(stats_key_begin, stats_key_end);
3769
51
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3770
51
                 << " end=" << hex(stats_key_end);
3771
51
    txn->remove(job_key_begin, job_key_end);
3772
51
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3773
51
    std::string schema_key_begin, schema_key_end;
3774
51
    std::string schema_dict_key;
3775
51
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3776
51
    if (partition_id <= 0) {
3777
        // Delete schema kv of this index
3778
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3779
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3780
15
        txn->remove(schema_key_begin, schema_key_end);
3781
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3782
15
                     << " end=" << hex(schema_key_end);
3783
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3784
15
        txn->remove(schema_dict_key);
3785
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3786
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3787
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3788
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3789
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3790
15
                     << " end=" << hex(versioned_schema_key_end);
3791
15
    }
3792
3793
51
    TxnErrorCode err = txn->commit();
3794
51
    if (err != TxnErrorCode::TXN_OK) {
3795
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3796
0
                     << " err=" << err;
3797
0
        return -1;
3798
0
    }
3799
3800
51
    return ret;
3801
51
}
3802
3803
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3804
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3805
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3806
5.61k
    if (num_segments <= 0) return 0;
3807
3808
5.61k
    std::vector<std::string> file_paths;
3809
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3810
0
        return -1;
3811
0
    }
3812
3813
    // Process inverted indexes
3814
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3815
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3816
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3817
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3818
5.61k
    bool delete_rowset_data_by_prefix = false;
3819
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3820
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3821
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3822
0
        delete_rowset_data_by_prefix = true;
3823
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3824
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3825
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3826
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3827
10.0k
            }
3828
10.0k
        }
3829
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3830
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3831
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3832
2.00k
        }
3833
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3834
        // schema version and index id are not found, delete rowset data by prefix directly.
3835
0
        delete_rowset_data_by_prefix = true;
3836
809
    } else {
3837
        // otherwise, try to get schema kv
3838
809
        InvertedIndexInfo index_info;
3839
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3840
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3841
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3842
809
                                 &inverted_index_get_ret);
3843
809
        if (inverted_index_get_ret == 0) {
3844
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3845
809
                index_format = index_info.first;
3846
809
            }
3847
809
            index_ids = index_info.second;
3848
809
        } else if (inverted_index_get_ret == 1) {
3849
            // 1. Schema kv not found means tablet has been recycled
3850
            // Maybe some tablet recycle failed by some bugs
3851
            // We need to delete again to double check
3852
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3853
            // because we are uncertain about the inverted index information.
3854
            // If there are inverted indexes, some data might not be deleted,
3855
            // but this is acceptable as we have made our best effort to delete the data.
3856
0
            LOG_INFO(
3857
0
                    "delete rowset data schema kv not found, need to delete again to double "
3858
0
                    "check")
3859
0
                    .tag("instance_id", instance_id_)
3860
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3861
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3862
            // Currently index_ids is guaranteed to be empty,
3863
            // but we clear it again here as a safeguard against future code changes
3864
            // that might cause index_ids to no longer be empty
3865
0
            index_format = InvertedIndexStorageFormatPB::V2;
3866
0
            index_ids.clear();
3867
0
        } else {
3868
            // failed to get schema kv, delete rowset data by prefix directly.
3869
0
            delete_rowset_data_by_prefix = true;
3870
0
        }
3871
809
    }
3872
3873
5.61k
    if (delete_rowset_data_by_prefix) {
3874
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3875
0
                                  rs_meta_pb.rowset_id_v2());
3876
0
    }
3877
3878
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3879
5.61k
    if (it == accessor_map_.end()) {
3880
1.59k
        LOG_WARNING("instance has no such resource id")
3881
1.59k
                .tag("instance_id", instance_id_)
3882
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3883
1.59k
        return -1;
3884
1.59k
    }
3885
4.01k
    auto& accessor = it->second;
3886
3887
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3888
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3889
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3890
20.0k
        auto segment_id = rowset_segment_id(rs_meta_pb, i);
3891
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, segment_id),
3892
20.0k
                                         &file_paths);
3893
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3894
40.0k
            for (const auto& index_id : index_ids) {
3895
40.0k
                add_file_to_delete_if_not_packed(
3896
40.0k
                        rs_meta_pb,
3897
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
3898
40.0k
                                               index_id.second),
3899
40.0k
                        &file_paths);
3900
40.0k
            }
3901
20.0k
        } else if (!index_ids.empty()) {
3902
2
            add_file_to_delete_if_not_packed(
3903
2
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, segment_id),
3904
2
                    &file_paths);
3905
2
        }
3906
20.0k
    }
3907
3908
    // Process delete bitmap - check where it's stored.
3909
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3910
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3911
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3912
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3913
0
                .tag("instance_id", instance_id_)
3914
0
                .tag("tablet_id", tablet_id)
3915
0
                .tag("rowset_id", rowset_id);
3916
0
        return -1;
3917
0
    }
3918
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3919
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3920
2.00k
    }
3921
    // TODO(AlexYue): seems could do do batch
3922
4.01k
    return accessor->delete_files(file_paths);
3923
4.01k
}
3924
3925
62.6k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3926
62.6k
    LOG_INFO("begin process_packed_file_location_index")
3927
62.6k
            .tag("instance_id", instance_id_)
3928
62.6k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3929
62.6k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3930
62.6k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3931
62.6k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3932
62.6k
    if (index_map.empty()) {
3933
62.6k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3934
62.6k
                .tag("instance_id", instance_id_)
3935
62.6k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3936
62.6k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3937
62.6k
        return 0;
3938
62.6k
    }
3939
3940
15
    struct PackedSmallFileInfo {
3941
15
        std::string small_file_path;
3942
15
    };
3943
15
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3944
15
    packed_file_updates.reserve(index_map.size());
3945
27
    for (const auto& [small_path, index_pb] : index_map) {
3946
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3947
0
            continue;
3948
0
        }
3949
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3950
27
                PackedSmallFileInfo {small_path});
3951
27
    }
3952
15
    if (packed_file_updates.empty()) {
3953
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3954
0
                .tag("instance_id", instance_id_)
3955
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3956
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3957
0
                .tag("index_map_size", index_map.size());
3958
0
        return 0;
3959
0
    }
3960
3961
15
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3962
15
    int ret = 0;
3963
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3964
24
        if (small_files.empty()) {
3965
0
            continue;
3966
0
        }
3967
3968
24
        bool success = false;
3969
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
3970
24
            std::unique_ptr<Transaction> txn;
3971
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
3972
24
            if (err != TxnErrorCode::TXN_OK) {
3973
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
3974
0
                        .tag("instance_id", instance_id_)
3975
0
                        .tag("packed_file_path", packed_file_path)
3976
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3977
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3978
0
                        .tag("err", err);
3979
0
                ret = -1;
3980
0
                break;
3981
0
            }
3982
3983
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
3984
24
            std::string packed_val;
3985
24
            err = txn->get(packed_key, &packed_val);
3986
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
3987
0
                LOG_WARNING("packed file info not found when recycling rowset")
3988
0
                        .tag("instance_id", instance_id_)
3989
0
                        .tag("packed_file_path", packed_file_path)
3990
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3991
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
3992
0
                        .tag("key", hex(packed_key))
3993
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
3994
                // Skip this packed file entry and continue with others
3995
0
                success = true;
3996
0
                break;
3997
0
            }
3998
24
            if (err != TxnErrorCode::TXN_OK) {
3999
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
4000
0
                        .tag("instance_id", instance_id_)
4001
0
                        .tag("packed_file_path", packed_file_path)
4002
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4003
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4004
0
                        .tag("err", err);
4005
0
                ret = -1;
4006
0
                break;
4007
0
            }
4008
4009
24
            cloud::PackedFileInfoPB packed_info;
4010
24
            if (!packed_info.ParseFromString(packed_val)) {
4011
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
4012
0
                        .tag("instance_id", instance_id_)
4013
0
                        .tag("packed_file_path", packed_file_path)
4014
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4015
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4016
0
                ret = -1;
4017
0
                break;
4018
0
            }
4019
4020
24
            LOG_INFO("packed file update check")
4021
24
                    .tag("instance_id", instance_id_)
4022
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4023
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4024
24
                    .tag("merged_file_path", packed_file_path)
4025
24
                    .tag("requested_small_files", small_files.size())
4026
24
                    .tag("merge_entries", packed_info.slices_size());
4027
4028
24
            auto* small_file_entries = packed_info.mutable_slices();
4029
24
            int64_t changed_files = 0;
4030
24
            int64_t missing_entries = 0;
4031
24
            int64_t already_deleted = 0;
4032
27
            for (const auto& small_file_info : small_files) {
4033
27
                bool found = false;
4034
87
                for (auto& small_file_entry : *small_file_entries) {
4035
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
4036
27
                        if (!small_file_entry.deleted()) {
4037
27
                            small_file_entry.set_deleted(true);
4038
27
                            if (!small_file_entry.corrected()) {
4039
27
                                small_file_entry.set_corrected(true);
4040
27
                            }
4041
27
                            ++changed_files;
4042
27
                        } else {
4043
0
                            ++already_deleted;
4044
0
                        }
4045
27
                        found = true;
4046
27
                        break;
4047
27
                    }
4048
87
                }
4049
27
                if (!found) {
4050
0
                    ++missing_entries;
4051
0
                    LOG_WARNING("packed file info missing small file entry")
4052
0
                            .tag("instance_id", instance_id_)
4053
0
                            .tag("packed_file_path", packed_file_path)
4054
0
                            .tag("small_file_path", small_file_info.small_file_path)
4055
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4056
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
4057
0
                }
4058
27
            }
4059
4060
24
            if (changed_files == 0) {
4061
0
                LOG_INFO("skip merge file update: no merge entries changed")
4062
0
                        .tag("instance_id", instance_id_)
4063
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4064
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4065
0
                        .tag("merged_file_path", packed_file_path)
4066
0
                        .tag("missing_entries", missing_entries)
4067
0
                        .tag("already_deleted", already_deleted)
4068
0
                        .tag("requested_small_files", small_files.size())
4069
0
                        .tag("merge_entries", packed_info.slices_size());
4070
0
                success = true;
4071
0
                break;
4072
0
            }
4073
4074
            // Calculate remaining files
4075
24
            int64_t left_file_count = 0;
4076
24
            int64_t left_file_bytes = 0;
4077
141
            for (const auto& small_file_entry : packed_info.slices()) {
4078
141
                if (!small_file_entry.deleted()) {
4079
57
                    ++left_file_count;
4080
57
                    left_file_bytes += small_file_entry.size();
4081
57
                }
4082
141
            }
4083
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
4084
24
            packed_info.set_ref_cnt(left_file_count);
4085
24
            LOG_INFO("updated packed file reference info")
4086
24
                    .tag("instance_id", instance_id_)
4087
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4088
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4089
24
                    .tag("packed_file_path", packed_file_path)
4090
24
                    .tag("ref_cnt", left_file_count)
4091
24
                    .tag("left_file_bytes", left_file_bytes);
4092
4093
24
            if (left_file_count == 0) {
4094
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4095
7
            }
4096
4097
24
            std::string updated_val;
4098
24
            if (!packed_info.SerializeToString(&updated_val)) {
4099
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
4100
0
                        .tag("instance_id", instance_id_)
4101
0
                        .tag("packed_file_path", packed_file_path)
4102
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4103
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4104
0
                ret = -1;
4105
0
                break;
4106
0
            }
4107
4108
24
            txn->put(packed_key, updated_val);
4109
24
            err = txn->commit();
4110
24
            if (err == TxnErrorCode::TXN_OK) {
4111
24
                success = true;
4112
24
                if (left_file_count == 0) {
4113
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
4114
7
                            .tag("instance_id", instance_id_)
4115
7
                            .tag("packed_file_path", packed_file_path);
4116
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4117
0
                        ret = -1;
4118
0
                    }
4119
7
                }
4120
24
                break;
4121
24
            }
4122
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
4123
0
                if (attempt >= max_retry_times) {
4124
0
                    LOG_WARNING("packed file info update conflict after max retry")
4125
0
                            .tag("instance_id", instance_id_)
4126
0
                            .tag("packed_file_path", packed_file_path)
4127
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4128
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
4129
0
                            .tag("changed_files", changed_files)
4130
0
                            .tag("attempt", attempt);
4131
0
                    ret = -1;
4132
0
                    break;
4133
0
                }
4134
0
                LOG_WARNING("packed file info update conflict, retrying")
4135
0
                        .tag("instance_id", instance_id_)
4136
0
                        .tag("packed_file_path", packed_file_path)
4137
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4138
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4139
0
                        .tag("changed_files", changed_files)
4140
0
                        .tag("attempt", attempt);
4141
0
                sleep_for_packed_file_retry();
4142
0
                continue;
4143
0
            }
4144
4145
0
            LOG_WARNING("failed to commit packed file info update")
4146
0
                    .tag("instance_id", instance_id_)
4147
0
                    .tag("packed_file_path", packed_file_path)
4148
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4149
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4150
0
                    .tag("err", err)
4151
0
                    .tag("changed_files", changed_files);
4152
0
            ret = -1;
4153
0
            break;
4154
0
        }
4155
4156
24
        if (!success) {
4157
0
            ret = -1;
4158
0
        }
4159
24
    }
4160
4161
15
    return ret;
4162
15
}
4163
4164
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
4165
        int64_t tablet_id, const std::string& rowset_id, DeleteBitmapStorageType* out_storage_type,
4166
61.0k
        std::vector<std::string>* keys) {
4167
61.0k
    if (out_storage_type) {
4168
58.4k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4169
58.4k
    }
4170
4171
    // Get delete bitmap storage info from FDB
4172
61.0k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4173
61.0k
    std::unique_ptr<Transaction> txn;
4174
61.0k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
4175
61.0k
    if (err != TxnErrorCode::TXN_OK) {
4176
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
4177
0
                .tag("instance_id", instance_id_)
4178
0
                .tag("tablet_id", tablet_id)
4179
0
                .tag("rowset_id", rowset_id)
4180
0
                .tag("err", err);
4181
0
        return -1;
4182
0
    }
4183
4184
61.0k
    ValueBuf dbm_val;
4185
61.0k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4186
61.0k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4187
        // No delete bitmap for this rowset, nothing to do
4188
6.19k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4189
6.19k
                .tag("instance_id", instance_id_)
4190
6.19k
                .tag("tablet_id", tablet_id)
4191
6.19k
                .tag("rowset_id", rowset_id);
4192
6.19k
        return 0;
4193
6.19k
    }
4194
54.8k
    if (err != TxnErrorCode::TXN_OK) {
4195
0
        LOG_WARNING("failed to get delete bitmap storage")
4196
0
                .tag("instance_id", instance_id_)
4197
0
                .tag("tablet_id", tablet_id)
4198
0
                .tag("rowset_id", rowset_id)
4199
0
                .tag("err", err);
4200
0
        return -1;
4201
0
    }
4202
4203
54.8k
    if (keys) {
4204
1.55k
        for (auto& key : dbm_val.keys()) {
4205
1.55k
            keys->push_back(std::move(key));
4206
1.55k
        }
4207
1.55k
    }
4208
4209
54.8k
    DeleteBitmapStoragePB storage;
4210
54.8k
    if (!dbm_val.to_pb(&storage)) {
4211
0
        LOG_WARNING("failed to parse delete bitmap storage")
4212
0
                .tag("instance_id", instance_id_)
4213
0
                .tag("tablet_id", tablet_id)
4214
0
                .tag("rowset_id", rowset_id);
4215
0
        return -1;
4216
0
    }
4217
4218
54.8k
    if (storage.store_in_fdb()) {
4219
1
        if (out_storage_type) {
4220
1
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4221
1
        }
4222
1
        return 0;
4223
1
    }
4224
4225
    // Check if delete bitmap is stored in standalone file.
4226
54.8k
    if (!storage.has_packed_slice_location() ||
4227
54.8k
        storage.packed_slice_location().packed_file_path().empty()) {
4228
54.8k
        if (out_storage_type) {
4229
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4230
53.5k
        }
4231
54.8k
        return 0;
4232
54.8k
    }
4233
4234
18.4E
    if (out_storage_type) {
4235
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4236
0
    }
4237
4238
18.4E
    const auto& packed_loc = storage.packed_slice_location();
4239
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
4240
4241
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
4242
18.4E
            .tag("instance_id", instance_id_)
4243
18.4E
            .tag("tablet_id", tablet_id)
4244
18.4E
            .tag("rowset_id", rowset_id)
4245
18.4E
            .tag("packed_file_path", packed_file_path);
4246
4247
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4248
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4249
1
        std::unique_ptr<Transaction> update_txn;
4250
1
        err = txn_kv_->create_txn(&update_txn);
4251
1
        if (err != TxnErrorCode::TXN_OK) {
4252
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4253
0
                    .tag("instance_id", instance_id_)
4254
0
                    .tag("tablet_id", tablet_id)
4255
0
                    .tag("rowset_id", rowset_id)
4256
0
                    .tag("err", err);
4257
0
            return -1;
4258
0
        }
4259
4260
1
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4261
1
        std::string packed_val;
4262
1
        err = update_txn->get(packed_key, &packed_val);
4263
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4264
0
            LOG_WARNING("packed file info not found for delete bitmap")
4265
0
                    .tag("instance_id", instance_id_)
4266
0
                    .tag("tablet_id", tablet_id)
4267
0
                    .tag("rowset_id", rowset_id)
4268
0
                    .tag("packed_file_path", packed_file_path);
4269
0
            return 0;
4270
0
        }
4271
1
        if (err != TxnErrorCode::TXN_OK) {
4272
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4273
0
                    .tag("instance_id", instance_id_)
4274
0
                    .tag("tablet_id", tablet_id)
4275
0
                    .tag("rowset_id", rowset_id)
4276
0
                    .tag("packed_file_path", packed_file_path)
4277
0
                    .tag("err", err);
4278
0
            return -1;
4279
0
        }
4280
4281
1
        cloud::PackedFileInfoPB packed_info;
4282
1
        if (!packed_info.ParseFromString(packed_val)) {
4283
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4284
0
                    .tag("instance_id", instance_id_)
4285
0
                    .tag("tablet_id", tablet_id)
4286
0
                    .tag("rowset_id", rowset_id)
4287
0
                    .tag("packed_file_path", packed_file_path);
4288
0
            return -1;
4289
0
        }
4290
4291
        // Find and mark the small file entry as deleted
4292
        // Use tablet_id and rowset_id to match entry instead of path,
4293
        // because path format may vary with path_version (with or without shard prefix)
4294
1
        auto* entries = packed_info.mutable_slices();
4295
1
        bool found = false;
4296
1
        bool already_deleted = false;
4297
1
        for (auto& entry : *entries) {
4298
1
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4299
1
                if (!entry.deleted()) {
4300
1
                    entry.set_deleted(true);
4301
1
                    if (!entry.corrected()) {
4302
1
                        entry.set_corrected(true);
4303
1
                    }
4304
1
                } else {
4305
0
                    already_deleted = true;
4306
0
                }
4307
1
                found = true;
4308
1
                break;
4309
1
            }
4310
1
        }
4311
4312
1
        if (!found) {
4313
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4314
0
                    .tag("instance_id", instance_id_)
4315
0
                    .tag("tablet_id", tablet_id)
4316
0
                    .tag("rowset_id", rowset_id)
4317
0
                    .tag("packed_file_path", packed_file_path);
4318
0
            return 0;
4319
0
        }
4320
4321
1
        if (already_deleted) {
4322
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4323
0
                    .tag("instance_id", instance_id_)
4324
0
                    .tag("tablet_id", tablet_id)
4325
0
                    .tag("rowset_id", rowset_id)
4326
0
                    .tag("packed_file_path", packed_file_path);
4327
0
            return 0;
4328
0
        }
4329
4330
        // Calculate remaining files
4331
1
        int64_t left_file_count = 0;
4332
1
        int64_t left_file_bytes = 0;
4333
1
        for (const auto& entry : packed_info.slices()) {
4334
1
            if (!entry.deleted()) {
4335
0
                ++left_file_count;
4336
0
                left_file_bytes += entry.size();
4337
0
            }
4338
1
        }
4339
1
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4340
1
        packed_info.set_ref_cnt(left_file_count);
4341
4342
1
        if (left_file_count == 0) {
4343
1
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4344
1
        }
4345
4346
1
        std::string updated_val;
4347
1
        if (!packed_info.SerializeToString(&updated_val)) {
4348
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4349
0
                    .tag("instance_id", instance_id_)
4350
0
                    .tag("tablet_id", tablet_id)
4351
0
                    .tag("rowset_id", rowset_id)
4352
0
                    .tag("packed_file_path", packed_file_path);
4353
0
            return -1;
4354
0
        }
4355
4356
1
        update_txn->put(packed_key, updated_val);
4357
1
        err = update_txn->commit();
4358
1
        if (err == TxnErrorCode::TXN_OK) {
4359
1
            LOG_INFO("delete bitmap packed file ref count decremented")
4360
1
                    .tag("instance_id", instance_id_)
4361
1
                    .tag("tablet_id", tablet_id)
4362
1
                    .tag("rowset_id", rowset_id)
4363
1
                    .tag("packed_file_path", packed_file_path)
4364
1
                    .tag("left_file_count", left_file_count);
4365
1
            if (left_file_count == 0) {
4366
1
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4367
0
                    return -1;
4368
0
                }
4369
1
            }
4370
1
            return 0;
4371
1
        }
4372
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4373
0
            if (attempt >= max_retry_times) {
4374
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4375
0
                        .tag("instance_id", instance_id_)
4376
0
                        .tag("tablet_id", tablet_id)
4377
0
                        .tag("rowset_id", rowset_id)
4378
0
                        .tag("packed_file_path", packed_file_path)
4379
0
                        .tag("attempt", attempt);
4380
0
                return -1;
4381
0
            }
4382
0
            sleep_for_packed_file_retry();
4383
0
            continue;
4384
0
        }
4385
4386
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4387
0
                .tag("instance_id", instance_id_)
4388
0
                .tag("tablet_id", tablet_id)
4389
0
                .tag("rowset_id", rowset_id)
4390
0
                .tag("packed_file_path", packed_file_path)
4391
0
                .tag("err", err);
4392
0
        return -1;
4393
0
    }
4394
4395
18.4E
    return -1;
4396
18.4E
}
4397
4398
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4399
                                                const std::string& packed_key,
4400
8
                                                const cloud::PackedFileInfoPB& packed_info) {
4401
8
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4402
0
        LOG_WARNING("packed file missing resource id when recycling")
4403
0
                .tag("instance_id", instance_id_)
4404
0
                .tag("packed_file_path", packed_file_path);
4405
0
        return -1;
4406
0
    }
4407
4408
8
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4409
8
    if (!accessor) {
4410
0
        LOG_WARNING("no accessor available to delete packed file")
4411
0
                .tag("instance_id", instance_id_)
4412
0
                .tag("packed_file_path", packed_file_path)
4413
0
                .tag("resource_id", packed_info.resource_id());
4414
0
        return -1;
4415
0
    }
4416
4417
8
    int del_ret = accessor->delete_file(packed_file_path);
4418
8
    if (del_ret != 0 && del_ret != 1) {
4419
0
        LOG_WARNING("failed to delete packed file")
4420
0
                .tag("instance_id", instance_id_)
4421
0
                .tag("packed_file_path", packed_file_path)
4422
0
                .tag("resource_id", resource_id)
4423
0
                .tag("ret", del_ret);
4424
0
        return -1;
4425
0
    }
4426
8
    if (del_ret == 1) {
4427
0
        LOG_INFO("packed file already removed")
4428
0
                .tag("instance_id", instance_id_)
4429
0
                .tag("packed_file_path", packed_file_path)
4430
0
                .tag("resource_id", resource_id);
4431
8
    } else {
4432
8
        LOG_INFO("deleted packed file")
4433
8
                .tag("instance_id", instance_id_)
4434
8
                .tag("packed_file_path", packed_file_path)
4435
8
                .tag("resource_id", resource_id);
4436
8
    }
4437
4438
8
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4439
8
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4440
8
        std::unique_ptr<Transaction> del_txn;
4441
8
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4442
8
        if (err != TxnErrorCode::TXN_OK) {
4443
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4444
0
                    .tag("instance_id", instance_id_)
4445
0
                    .tag("packed_file_path", packed_file_path)
4446
0
                    .tag("attempt", attempt)
4447
0
                    .tag("err", err);
4448
0
            return -1;
4449
0
        }
4450
4451
8
        std::string latest_val;
4452
8
        err = del_txn->get(packed_key, &latest_val);
4453
8
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4454
0
            return 0;
4455
0
        }
4456
8
        if (err != TxnErrorCode::TXN_OK) {
4457
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4458
0
                    .tag("instance_id", instance_id_)
4459
0
                    .tag("packed_file_path", packed_file_path)
4460
0
                    .tag("attempt", attempt)
4461
0
                    .tag("err", err);
4462
0
            return -1;
4463
0
        }
4464
4465
8
        cloud::PackedFileInfoPB latest_info;
4466
8
        if (!latest_info.ParseFromString(latest_val)) {
4467
0
            LOG_WARNING("failed to parse packed file info before removal")
4468
0
                    .tag("instance_id", instance_id_)
4469
0
                    .tag("packed_file_path", packed_file_path)
4470
0
                    .tag("attempt", attempt);
4471
0
            return -1;
4472
0
        }
4473
4474
8
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4475
8
              latest_info.ref_cnt() == 0)) {
4476
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4477
0
                    .tag("instance_id", instance_id_)
4478
0
                    .tag("packed_file_path", packed_file_path)
4479
0
                    .tag("attempt", attempt);
4480
0
            return 0;
4481
0
        }
4482
4483
8
        del_txn->remove(packed_key);
4484
8
        err = del_txn->commit();
4485
8
        if (err == TxnErrorCode::TXN_OK) {
4486
8
            LOG_INFO("removed packed file metadata")
4487
8
                    .tag("instance_id", instance_id_)
4488
8
                    .tag("packed_file_path", packed_file_path);
4489
8
            return 0;
4490
8
        }
4491
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4492
0
            if (attempt >= max_retry_times) {
4493
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4494
0
                        .tag("instance_id", instance_id_)
4495
0
                        .tag("packed_file_path", packed_file_path)
4496
0
                        .tag("attempt", attempt);
4497
0
                return -1;
4498
0
            }
4499
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4500
0
                    .tag("instance_id", instance_id_)
4501
0
                    .tag("packed_file_path", packed_file_path)
4502
0
                    .tag("attempt", attempt);
4503
0
            sleep_for_packed_file_retry();
4504
0
            continue;
4505
0
        }
4506
0
        LOG_WARNING("failed to remove packed file kv")
4507
0
                .tag("instance_id", instance_id_)
4508
0
                .tag("packed_file_path", packed_file_path)
4509
0
                .tag("attempt", attempt)
4510
0
                .tag("err", err);
4511
0
        return -1;
4512
0
    }
4513
0
    return -1;
4514
8
}
4515
4516
int InstanceRecycler::delete_rowset_data(
4517
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4518
        RecyclerMetricsContext& metrics_context,
4519
96
        std::vector<std::vector<std::string>>* delete_bitmap_key_groups) {
4520
96
    int ret = 0;
4521
    // resource_id -> file_paths
4522
96
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4523
    // (resource_id, tablet_id, rowset_id)
4524
96
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4525
96
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4526
4527
56.4k
    for (const auto& [_, rs] : rowsets) {
4528
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4529
        // due to aborted schema change.
4530
56.4k
        if (is_formal_rowset) {
4531
3.16k
            if (is_tablet_recycled(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4532
                // Tablet has been recycled and this rowset has no packed slices, so file data
4533
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4534
                // slice info must still run to decrement packed file ref counts.
4535
0
                continue;
4536
0
            }
4537
3.16k
        }
4538
4539
56.4k
        int64_t num_segments = rs.num_segments();
4540
        // Check num_segments before accessor lookup, because empty rowsets
4541
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4542
        // set. Skipping them early avoids a spurious "no such resource id" error
4543
        // that marks the entire batch as failed and prevents txn_remove from
4544
        // cleaning up recycle KV keys.
4545
56.4k
        if (num_segments <= 0) {
4546
0
            metrics_context.total_recycled_num++;
4547
0
            metrics_context.total_recycled_data_size += rs.total_disk_size();
4548
0
            continue;
4549
0
        }
4550
4551
56.4k
        auto it = accessor_map_.find(rs.resource_id());
4552
        // possible if the accessor is not initilized correctly
4553
56.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4554
2.00k
            LOG_WARNING("instance has no such resource id")
4555
2.00k
                    .tag("instance_id", instance_id_)
4556
2.00k
                    .tag("resource_id", rs.resource_id());
4557
2.00k
            ret = -1;
4558
2.00k
            continue;
4559
2.00k
        }
4560
4561
54.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4562
54.4k
        const auto& rowset_id = rs.rowset_id_v2();
4563
54.4k
        int64_t tablet_id = rs.tablet_id();
4564
54.4k
        LOG_INFO("recycle rowset merge index size")
4565
54.4k
                .tag("instance_id", instance_id_)
4566
54.4k
                .tag("tablet_id", tablet_id)
4567
54.4k
                .tag("rowset_id", rowset_id)
4568
54.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4569
54.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4570
0
            ret = -1;
4571
0
            continue;
4572
0
        }
4573
4574
54.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4575
54.4k
        std::vector<std::string> rowset_dbm_keys;
4576
54.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(
4577
54.4k
                    tablet_id, rowset_id, &delete_bitmap_storage_type,
4578
54.4k
                    delete_bitmap_key_groups ? &rowset_dbm_keys : nullptr) != 0) {
4579
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4580
0
                    .tag("instance_id", instance_id_)
4581
0
                    .tag("tablet_id", tablet_id)
4582
0
                    .tag("rowset_id", rowset_id);
4583
0
            ret = -1;
4584
0
            continue;
4585
0
        }
4586
54.4k
        if (!rowset_dbm_keys.empty() && delete_bitmap_key_groups) {
4587
1.55k
            delete_bitmap_key_groups->emplace_back(std::move(rowset_dbm_keys));
4588
1.55k
        }
4589
54.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4590
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4591
51.5k
        }
4592
4593
        // Process inverted indexes
4594
54.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4595
        // default format as v1.
4596
54.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4597
54.4k
                                                            ? rs.inverted_index_storage_format()
4598
54.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4599
54.4k
        int inverted_index_get_ret = 0;
4600
54.4k
        if (rs.has_tablet_schema()) {
4601
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4602
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4603
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4604
53.5k
                }
4605
53.5k
            }
4606
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4607
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4608
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4609
26.5k
            }
4610
27.5k
        } else {
4611
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4612
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4613
0
                                "instance_id="
4614
0
                             << instance_id_ << " tablet_id=" << tablet_id
4615
0
                             << " rowset_id=" << rowset_id;
4616
0
                ret = -1;
4617
0
                continue;
4618
0
            }
4619
27.5k
            InvertedIndexInfo index_info;
4620
27.5k
            inverted_index_get_ret =
4621
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4622
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4623
27.5k
                                     &inverted_index_get_ret);
4624
27.5k
            if (inverted_index_get_ret == 0) {
4625
27.0k
                if (!rs.has_inverted_index_storage_format()) {
4626
27.0k
                    index_format = index_info.first;
4627
27.0k
                }
4628
27.0k
                index_ids = index_info.second;
4629
27.0k
            } else if (inverted_index_get_ret == 1) {
4630
                // 1. Schema kv not found means tablet has been recycled
4631
                // Maybe some tablet recycle failed by some bugs
4632
                // We need to delete again to double check
4633
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4634
                // because we are uncertain about the inverted index information.
4635
                // If there are inverted indexes, some data might not be deleted,
4636
                // but this is acceptable as we have made our best effort to delete the data.
4637
503
                LOG_INFO(
4638
503
                        "delete rowset data schema kv not found, need to delete again to "
4639
503
                        "double "
4640
503
                        "check")
4641
503
                        .tag("instance_id", instance_id_)
4642
503
                        .tag("tablet_id", tablet_id)
4643
503
                        .tag("rowset", rs.ShortDebugString());
4644
                // Currently index_ids is guaranteed to be empty,
4645
                // but we clear it again here as a safeguard against future code changes
4646
                // that might cause index_ids to no longer be empty
4647
503
                index_format = InvertedIndexStorageFormatPB::V2;
4648
503
                index_ids.clear();
4649
18.4E
            } else {
4650
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4651
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4652
18.4E
                ret = -1;
4653
18.4E
                continue;
4654
18.4E
            }
4655
27.5k
        }
4656
54.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4657
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4658
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4659
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4660
5
            continue;
4661
5
        }
4662
324k
        for (int64_t i = 0; i < num_segments; ++i) {
4663
270k
            auto segment_id = rowset_segment_id(rs, i);
4664
270k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, segment_id),
4665
270k
                                             &file_paths);
4666
270k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4667
537k
                for (const auto& index_id : index_ids) {
4668
537k
                    add_file_to_delete_if_not_packed(
4669
537k
                            rs,
4670
537k
                            inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
4671
537k
                                                   index_id.second),
4672
537k
                            &file_paths);
4673
537k
                }
4674
268k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4675
                // try to recycle inverted index v2 when get_ret == 1
4676
                // we treat schema not found as if it has a v2 format inverted index
4677
                // to reduce chance of data leakage
4678
2.50k
                if (inverted_index_get_ret == 1) {
4679
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4680
2.50k
                            .tag("instance_id", instance_id_)
4681
2.50k
                            .tag("inverted index v2 path",
4682
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, segment_id));
4683
2.50k
                }
4684
2.50k
                add_file_to_delete_if_not_packed(
4685
2.50k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, segment_id), &file_paths);
4686
2.50k
            }
4687
270k
        }
4688
54.4k
    }
4689
4690
96
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4691
96
                                                 "delete_rowset_data",
4692
96
                                                 [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_0clERKi
Line
Count
Source
4692
6
                                                 [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_0clERKi
Line
Count
Source
4692
56
                                                 [](const int& ret) { return ret != 0; });
4693
96
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4694
57
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4695
57
            DCHECK(accessor_map_.count(*rid))
4696
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4697
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4698
57
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4699
57
                                     &accessor_map_);
4700
57
            if (!accessor_map_.contains(*rid)) {
4701
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4702
0
                        .tag("resource_id", resource_id)
4703
0
                        .tag("instance_id", instance_id_);
4704
0
                return -1;
4705
0
            }
4706
57
            auto& accessor = accessor_map_[*rid];
4707
57
            int ret = accessor->delete_files(*paths);
4708
57
            if (!ret) {
4709
                // deduplication of different files with the same rowset id
4710
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4711
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4712
57
                std::set<std::string> deleted_rowset_id;
4713
4714
57
                std::for_each(paths->begin(), paths->end(),
4715
57
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4716
862k
                               this](const std::string& path) {
4717
862k
                                  std::vector<std::string> str;
4718
862k
                                  butil::SplitString(path, '/', &str);
4719
862k
                                  std::string rowset_id;
4720
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4721
856k
                                      rowset_id = str.back().substr(0, pos);
4722
856k
                                  } else {
4723
5.95k
                                      if (path.find("packed_file/") != std::string::npos) {
4724
0
                                          return; // packed files do not have rowset_id encoded
4725
0
                                      }
4726
5.95k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4727
5.95k
                                      return;
4728
5.95k
                                  }
4729
856k
                                  auto rs_meta = rowsets.find(rowset_id);
4730
856k
                                  if (rs_meta != rowsets.end() &&
4731
859k
                                      !deleted_rowset_id.contains(rowset_id)) {
4732
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4733
54.4k
                                      metrics_context.total_recycled_data_size +=
4734
54.4k
                                              rs_meta->second.total_disk_size();
4735
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4736
54.4k
                                              rs_meta->second.num_segments();
4737
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4738
54.4k
                                              rs_meta->second.total_disk_size();
4739
54.4k
                                      metrics_context.total_recycled_num++;
4740
54.4k
                                  }
4741
856k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEvENKUlRSD_E_clEST_
Line
Count
Source
4716
7
                               this](const std::string& path) {
4717
7
                                  std::vector<std::string> str;
4718
7
                                  butil::SplitString(path, '/', &str);
4719
7
                                  std::string rowset_id;
4720
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4721
7
                                      rowset_id = str.back().substr(0, pos);
4722
7
                                  } else {
4723
0
                                      if (path.find("packed_file/") != std::string::npos) {
4724
0
                                          return; // packed files do not have rowset_id encoded
4725
0
                                      }
4726
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4727
0
                                      return;
4728
0
                                  }
4729
7
                                  auto rs_meta = rowsets.find(rowset_id);
4730
7
                                  if (rs_meta != rowsets.end() &&
4731
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4732
7
                                      deleted_rowset_id.emplace(rowset_id);
4733
7
                                      metrics_context.total_recycled_data_size +=
4734
7
                                              rs_meta->second.total_disk_size();
4735
7
                                      segment_metrics_context_.total_recycled_num +=
4736
7
                                              rs_meta->second.num_segments();
4737
7
                                      segment_metrics_context_.total_recycled_data_size +=
4738
7
                                              rs_meta->second.total_disk_size();
4739
7
                                      metrics_context.total_recycled_num++;
4740
7
                                  }
4741
7
                              });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEvENKUlRSD_E_clEST_
Line
Count
Source
4716
862k
                               this](const std::string& path) {
4717
862k
                                  std::vector<std::string> str;
4718
862k
                                  butil::SplitString(path, '/', &str);
4719
862k
                                  std::string rowset_id;
4720
862k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4721
856k
                                      rowset_id = str.back().substr(0, pos);
4722
856k
                                  } else {
4723
5.95k
                                      if (path.find("packed_file/") != std::string::npos) {
4724
0
                                          return; // packed files do not have rowset_id encoded
4725
0
                                      }
4726
5.95k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4727
5.95k
                                      return;
4728
5.95k
                                  }
4729
856k
                                  auto rs_meta = rowsets.find(rowset_id);
4730
856k
                                  if (rs_meta != rowsets.end() &&
4731
859k
                                      !deleted_rowset_id.contains(rowset_id)) {
4732
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4733
54.4k
                                      metrics_context.total_recycled_data_size +=
4734
54.4k
                                              rs_meta->second.total_disk_size();
4735
54.4k
                                      segment_metrics_context_.total_recycled_num +=
4736
54.4k
                                              rs_meta->second.num_segments();
4737
54.4k
                                      segment_metrics_context_.total_recycled_data_size +=
4738
54.4k
                                              rs_meta->second.total_disk_size();
4739
54.4k
                                      metrics_context.total_recycled_num++;
4740
54.4k
                                  }
4741
856k
                              });
4742
57
            }
4743
57
            return ret;
4744
57
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4694
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4695
6
            DCHECK(accessor_map_.count(*rid))
4696
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4697
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4698
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4699
6
                                     &accessor_map_);
4700
6
            if (!accessor_map_.contains(*rid)) {
4701
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4702
0
                        .tag("resource_id", resource_id)
4703
0
                        .tag("instance_id", instance_id_);
4704
0
                return -1;
4705
0
            }
4706
6
            auto& accessor = accessor_map_[*rid];
4707
6
            int ret = accessor->delete_files(*paths);
4708
6
            if (!ret) {
4709
                // deduplication of different files with the same rowset id
4710
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4711
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4712
6
                std::set<std::string> deleted_rowset_id;
4713
4714
6
                std::for_each(paths->begin(), paths->end(),
4715
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4716
6
                               this](const std::string& path) {
4717
6
                                  std::vector<std::string> str;
4718
6
                                  butil::SplitString(path, '/', &str);
4719
6
                                  std::string rowset_id;
4720
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4721
6
                                      rowset_id = str.back().substr(0, pos);
4722
6
                                  } else {
4723
6
                                      if (path.find("packed_file/") != std::string::npos) {
4724
6
                                          return; // packed files do not have rowset_id encoded
4725
6
                                      }
4726
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4727
6
                                      return;
4728
6
                                  }
4729
6
                                  auto rs_meta = rowsets.find(rowset_id);
4730
6
                                  if (rs_meta != rowsets.end() &&
4731
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4732
6
                                      deleted_rowset_id.emplace(rowset_id);
4733
6
                                      metrics_context.total_recycled_data_size +=
4734
6
                                              rs_meta->second.total_disk_size();
4735
6
                                      segment_metrics_context_.total_recycled_num +=
4736
6
                                              rs_meta->second.num_segments();
4737
6
                                      segment_metrics_context_.total_recycled_data_size +=
4738
6
                                              rs_meta->second.total_disk_size();
4739
6
                                      metrics_context.total_recycled_num++;
4740
6
                                  }
4741
6
                              });
4742
6
            }
4743
6
            return ret;
4744
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4694
51
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4695
51
            DCHECK(accessor_map_.count(*rid))
4696
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4697
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4698
51
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4699
51
                                     &accessor_map_);
4700
51
            if (!accessor_map_.contains(*rid)) {
4701
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4702
0
                        .tag("resource_id", resource_id)
4703
0
                        .tag("instance_id", instance_id_);
4704
0
                return -1;
4705
0
            }
4706
51
            auto& accessor = accessor_map_[*rid];
4707
51
            int ret = accessor->delete_files(*paths);
4708
51
            if (!ret) {
4709
                // deduplication of different files with the same rowset id
4710
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4711
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4712
51
                std::set<std::string> deleted_rowset_id;
4713
4714
51
                std::for_each(paths->begin(), paths->end(),
4715
51
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4716
51
                               this](const std::string& path) {
4717
51
                                  std::vector<std::string> str;
4718
51
                                  butil::SplitString(path, '/', &str);
4719
51
                                  std::string rowset_id;
4720
51
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4721
51
                                      rowset_id = str.back().substr(0, pos);
4722
51
                                  } else {
4723
51
                                      if (path.find("packed_file/") != std::string::npos) {
4724
51
                                          return; // packed files do not have rowset_id encoded
4725
51
                                      }
4726
51
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4727
51
                                      return;
4728
51
                                  }
4729
51
                                  auto rs_meta = rowsets.find(rowset_id);
4730
51
                                  if (rs_meta != rowsets.end() &&
4731
51
                                      !deleted_rowset_id.contains(rowset_id)) {
4732
51
                                      deleted_rowset_id.emplace(rowset_id);
4733
51
                                      metrics_context.total_recycled_data_size +=
4734
51
                                              rs_meta->second.total_disk_size();
4735
51
                                      segment_metrics_context_.total_recycled_num +=
4736
51
                                              rs_meta->second.num_segments();
4737
51
                                      segment_metrics_context_.total_recycled_data_size +=
4738
51
                                              rs_meta->second.total_disk_size();
4739
51
                                      metrics_context.total_recycled_num++;
4740
51
                                  }
4741
51
                              });
4742
51
            }
4743
51
            return ret;
4744
51
        });
4745
57
    }
4746
96
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4747
5
        LOG_INFO(
4748
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4749
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4750
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4751
5
        concurrent_delete_executor.add([&]() -> int {
4752
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4753
5
            if (!ret) {
4754
5
                auto rs = rowsets.at(rowset_id);
4755
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4756
5
                metrics_context.total_recycled_num++;
4757
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4758
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4759
5
            }
4760
5
            return ret;
4761
5
        });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_2clEv
Line
Count
Source
4751
5
        concurrent_delete_executor.add([&]() -> int {
4752
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4753
5
            if (!ret) {
4754
5
                auto rs = rowsets.at(rowset_id);
4755
5
                metrics_context.total_recycled_data_size += rs.total_disk_size();
4756
5
                metrics_context.total_recycled_num++;
4757
5
                segment_metrics_context_.total_recycled_data_size += rs.total_disk_size();
4758
5
                segment_metrics_context_.total_recycled_num += rs.num_segments();
4759
5
            }
4760
5
            return ret;
4761
5
        });
4762
5
    }
4763
4764
96
    bool finished = true;
4765
96
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4766
96
    for (int r : rets) {
4767
62
        if (r != 0) {
4768
0
            ret = -1;
4769
0
            break;
4770
0
        }
4771
62
    }
4772
96
    ret = finished ? ret : -1;
4773
96
    return ret;
4774
96
}
4775
4776
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4777
3.57k
                                         const std::string& rowset_id) {
4778
3.57k
    auto it = accessor_map_.find(resource_id);
4779
3.57k
    if (it == accessor_map_.end()) {
4780
400
        LOG_WARNING("instance has no such resource id")
4781
400
                .tag("instance_id", instance_id_)
4782
400
                .tag("resource_id", resource_id)
4783
400
                .tag("tablet_id", tablet_id)
4784
400
                .tag("rowset_id", rowset_id);
4785
400
        return -1;
4786
400
    }
4787
3.17k
    auto& accessor = it->second;
4788
3.17k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4789
3.57k
}
4790
4791
55.6k
bool InstanceRecycler::is_tablet_recycled(int64_t tablet_id) {
4792
55.6k
    std::lock_guard lock(recycled_tablets_mtx_);
4793
55.6k
    return recycled_tablets_.contains(tablet_id);
4794
55.6k
}
4795
4796
int InstanceRecycler::should_delete_versioned_delete_bitmap_kvs(int64_t partition_id,
4797
52.4k
                                                                int64_t tablet_id) {
4798
52.4k
    bool is_mow = true;
4799
52.4k
    if (partition_id != -1) {
4800
52.2k
        std::lock_guard lock(partition_mow_cache_mutex);
4801
52.2k
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4802
            // cache hit
4803
1
            is_mow = it->second;
4804
1
            return is_mow ? 1 : 0;
4805
1
        }
4806
52.2k
    }
4807
4808
52.4k
    TabletIndexPB tablet_index;
4809
52.4k
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_index);
4810
52.4k
    if (ret == 1) {
4811
        // maybe recycled
4812
52.4k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4813
52.4k
    }
4814
25
    if (ret != 0) {
4815
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id_
4816
0
                     << ", tablet_id=" << tablet_id;
4817
0
        return ret;
4818
0
    }
4819
4820
    // Legacy RecycleRowsetPB without type does not carry a partition ID. Check the cache after
4821
    // obtaining its partition ID from the tablet index.
4822
25
    if (partition_id == -1) {
4823
0
        partition_id = tablet_index.partition_id();
4824
0
        std::lock_guard lock(partition_mow_cache_mutex);
4825
0
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4826
0
            is_mow = it->second;
4827
0
            return is_mow ? 1 : 0;
4828
0
        }
4829
0
    }
4830
4831
25
    std::string tablet_meta_key =
4832
25
            meta_tablet_key({instance_id_, tablet_index.table_id(), tablet_index.index_id(),
4833
25
                             partition_id, tablet_id});
4834
25
    std::string tablet_meta_value;
4835
25
    ret = txn_get(txn_kv_.get(), tablet_meta_key, tablet_meta_value);
4836
25
    if (ret == 1) {
4837
        // maybe recycled
4838
10
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4839
10
    }
4840
15
    if (ret != 0) {
4841
0
        LOG(WARNING) << "failed to get tablet meta, instance_id=" << instance_id_
4842
0
                     << ", tablet_id=" << tablet_id;
4843
0
        return ret;
4844
0
    }
4845
4846
15
    TabletMetaCloudPB tablet_meta;
4847
15
    if (!tablet_meta.ParseFromString(tablet_meta_value)) {
4848
0
        LOG(WARNING) << "failed to parse tablet meta, instance_id=" << instance_id_
4849
0
                     << ", tablet_id=" << tablet_id;
4850
0
        return -1;
4851
0
    }
4852
    // The row-binlog companion of a MoW data tablet stores versioned delete bitmaps copied from
4853
    // that tablet, but its own MoW flag is deliberately false. Clean its DBMs without caching that
4854
    // false value as the MoW state of the whole partition.
4855
    // Rule: boolean enableUniqueKeyMergeOnWrite = !isRowBinlogIndex && tbl.getEnableUniqueKeyMergeOnWrite();
4856
15
    if (tablet_meta.tablet_role() == TabletRolePB::TABLET_ROLE_ROW_BINLOG) {
4857
1
        return 1;
4858
1
    }
4859
14
    bool tablet_is_mow = tablet_meta.enable_unique_key_merge_on_write();
4860
14
    std::lock_guard lock(partition_mow_cache_mutex);
4861
14
    auto [it, _] = partition_mow_cache.emplace(partition_id, tablet_is_mow);
4862
14
    return it->second ? 1 : 0;
4863
15
}
4864
4865
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t partition_id, int64_t tablet_id,
4866
52.4k
                                                         const std::string& rowset_id) {
4867
52.4k
    int ret = should_delete_versioned_delete_bitmap_kvs(partition_id, tablet_id);
4868
52.4k
    if (ret <= 0) {
4869
1.00k
        return ret;
4870
1.00k
    }
4871
4872
51.4k
    std::string dbm_start_key =
4873
51.4k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4874
51.4k
    std::string dbm_end_key = dbm_start_key;
4875
51.4k
    encode_int64(INT64_MAX, &dbm_end_key);
4876
51.4k
    ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4877
51.4k
    if (ret != 0) {
4878
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4879
0
                     << " partition_id=" << partition_id << " tablet_id=" << tablet_id
4880
0
                     << " rowset_id=" << rowset_id;
4881
0
    }
4882
51.4k
    return ret;
4883
52.4k
}
4884
4885
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4886
51.2k
    std::string delete_bitmap_start =
4887
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4888
51.2k
    std::string delete_bitmap_end =
4889
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4890
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4891
51.2k
    if (ret != 0) {
4892
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4893
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4894
0
    }
4895
51.2k
    return ret;
4896
51.2k
}
4897
4898
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4899
4
    if (key.empty()) {
4900
0
        return false;
4901
0
    }
4902
4
    std::string_view key_view = key;
4903
4
    key_view.remove_prefix(1); // remove keyspace prefix
4904
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4905
4
    if (decode_key(&key_view, &decoded) != 0) {
4906
0
        return false;
4907
0
    }
4908
4
    if (decoded.size() < 4) {
4909
0
        return false;
4910
0
    }
4911
4
    try {
4912
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4913
4
    } catch (const std::bad_variant_access&) {
4914
0
        return false;
4915
0
    }
4916
4
    return true;
4917
4
}
4918
4919
14
int InstanceRecycler::recycle_packed_files() {
4920
14
    const std::string task_name = "recycle_packed_files";
4921
14
    auto start_tp = steady_clock::now();
4922
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4923
14
    int ret = 0;
4924
14
    PackedFileRecycleStats stats;
4925
4926
14
    register_recycle_task(task_name, start_time);
4927
14
    DORIS_CLOUD_DEFER {
4928
14
        unregister_recycle_task(task_name);
4929
14
        int64_t cost =
4930
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4931
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4932
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4933
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4934
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4935
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4936
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4937
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4938
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4939
14
                                                             stats.bytes_object_deleted);
4940
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4941
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4942
14
                .tag("instance_id", instance_id_)
4943
14
                .tag("num_scanned", stats.num_scanned)
4944
14
                .tag("num_corrected", stats.num_corrected)
4945
14
                .tag("num_deleted", stats.num_deleted)
4946
14
                .tag("num_failed", stats.num_failed)
4947
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4948
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4949
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4950
14
                .tag("bytes_deleted", stats.bytes_deleted)
4951
14
                .tag("ret", ret);
4952
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4927
14
    DORIS_CLOUD_DEFER {
4928
14
        unregister_recycle_task(task_name);
4929
14
        int64_t cost =
4930
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4931
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4932
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4933
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4934
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4935
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4936
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4937
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4938
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4939
14
                                                             stats.bytes_object_deleted);
4940
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4941
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4942
14
                .tag("instance_id", instance_id_)
4943
14
                .tag("num_scanned", stats.num_scanned)
4944
14
                .tag("num_corrected", stats.num_corrected)
4945
14
                .tag("num_deleted", stats.num_deleted)
4946
14
                .tag("num_failed", stats.num_failed)
4947
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4948
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4949
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4950
14
                .tag("bytes_deleted", stats.bytes_deleted)
4951
14
                .tag("ret", ret);
4952
14
    };
4953
4954
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4955
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4956
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4957
4
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_1clISt17basic_string_viewIcSt11char_traitsIcEES7_EEDaOT_OT0_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_1clISt17basic_string_viewIcSt11char_traitsIcEES7_EEDaOT_OT0_
Line
Count
Source
4954
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4955
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4956
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4957
4
    };
4958
4959
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4960
4961
14
    std::string begin = packed_file_key({instance_id_, ""});
4962
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4963
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4964
0
        ret = -1;
4965
0
    }
4966
4967
14
    return ret;
4968
14
}
4969
4970
int InstanceRecycler::scan_tablets_and_statistics(int64_t table_id, int64_t index_id,
4971
                                                  RecyclerMetricsContext& metrics_context,
4972
0
                                                  int64_t partition_id, bool is_empty_tablet) {
4973
0
    std::string tablet_key_begin, tablet_key_end;
4974
4975
0
    if (partition_id > 0) {
4976
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
4977
0
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
4978
0
    } else {
4979
0
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
4980
0
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
4981
0
    }
4982
    // for calculate the total num or bytes of recyled objects
4983
0
    auto scan_and_statistics = [&, is_empty_tablet, this](std::string_view k,
4984
0
                                                          std::string_view v) -> int {
4985
0
        doris::TabletMetaCloudPB tablet_meta_pb;
4986
0
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
4987
0
            return 0;
4988
0
        }
4989
0
        int64_t tablet_id = tablet_meta_pb.tablet_id();
4990
4991
0
        if (config::enable_recycler_check_lazy_txn_finished &&
4992
0
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
4993
0
            return 0;
4994
0
        }
4995
4996
0
        if (!is_empty_tablet) {
4997
0
            if (scan_tablet_and_statistics(tablet_id, metrics_context) != 0) {
4998
0
                return 0;
4999
0
            }
5000
0
            tablet_metrics_context_.total_need_recycle_num++;
5001
0
        }
5002
0
        return 0;
5003
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_tablets_and_statisticsEllRNS0_22RecyclerMetricsContextElbENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_tablets_and_statisticsEllRNS0_22RecyclerMetricsContextElbENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES8_
5004
0
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(scan_and_statistics));
5005
0
    metrics_context.report(true);
5006
0
    tablet_metrics_context_.report(true);
5007
0
    segment_metrics_context_.report(true);
5008
0
    return ret;
5009
0
}
5010
5011
int InstanceRecycler::scan_tablet_and_statistics(int64_t tablet_id,
5012
0
                                                 RecyclerMetricsContext& metrics_context) {
5013
0
    int ret = 0;
5014
0
    std::map<std::string, RowsetMetaCloudPB> rowset_meta_map;
5015
0
    std::unique_ptr<Transaction> txn;
5016
0
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5017
0
        LOG_WARNING("failed to recycle tablet ")
5018
0
                .tag("tablet id", tablet_id)
5019
0
                .tag("instance_id", instance_id_)
5020
0
                .tag("reason", "failed to create txn");
5021
0
        ret = -1;
5022
0
    }
5023
0
    GetRowsetResponse resp;
5024
0
    std::string msg;
5025
0
    MetaServiceCode code = MetaServiceCode::OK;
5026
    // get rowsets in tablet
5027
0
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5028
0
                        tablet_id, code, msg, &resp);
5029
0
    if (code != MetaServiceCode::OK) {
5030
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5031
0
                .tag("tablet id", tablet_id)
5032
0
                .tag("msg", msg)
5033
0
                .tag("code", code)
5034
0
                .tag("instance id", instance_id_);
5035
0
        ret = -1;
5036
0
    }
5037
0
    for (const auto& rs_meta : resp.rowset_meta()) {
5038
        /*
5039
        * For compatibility, we skip the loop for [0-1] here.
5040
        * The purpose of this loop is to delete object files,
5041
        * and since [0-1] only has meta and doesn't have object files,
5042
        * skipping it doesn't affect system correctness.
5043
        *
5044
        * If not skipped, the check "if (!rs_meta.has_resource_id())" below
5045
        * would return error -1 directly, causing the recycle operation to fail.
5046
        *
5047
        * [0-1] doesn't have resource id is a bug.
5048
        * In the future, we will fix this problem, after that,
5049
        * we can remove this if statement.
5050
        *
5051
        * TODO(Yukang-Lian): remove this if statement when [0-1] has resource id in the future.
5052
        */
5053
5054
0
        if (rs_meta.end_version() == 1) {
5055
            // Assert that [0-1] has no resource_id to make sure
5056
            // this if statement will not be forgetted to remove
5057
            // when the resource id bug is fixed
5058
0
            DCHECK(!rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
5059
0
            continue;
5060
0
        }
5061
0
        if (!rs_meta.has_resource_id()) {
5062
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5063
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5064
0
                    .tag("instance_id", instance_id_)
5065
0
                    .tag("tablet_id", tablet_id);
5066
0
            continue;
5067
0
        }
5068
0
        DCHECK(rs_meta.has_resource_id()) << "rs_meta" << rs_meta.ShortDebugString();
5069
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5070
        // possible if the accessor is not initilized correctly
5071
0
        if (it == accessor_map_.end()) [[unlikely]] {
5072
0
            LOG_WARNING(
5073
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5074
0
                    "recycle process")
5075
0
                    .tag("tablet id", tablet_id)
5076
0
                    .tag("instance_id", instance_id_)
5077
0
                    .tag("resource_id", rs_meta.resource_id())
5078
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5079
0
            continue;
5080
0
        }
5081
5082
0
        metrics_context.total_need_recycle_data_size += rs_meta.total_disk_size();
5083
0
        tablet_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
5084
0
        segment_metrics_context_.total_need_recycle_data_size += rs_meta.total_disk_size();
5085
0
        segment_metrics_context_.total_need_recycle_num += rs_meta.num_segments();
5086
0
    }
5087
0
    return ret;
5088
0
}
5089
5090
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
5091
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
5092
4.26k
            .tag("instance_id", instance_id_)
5093
4.26k
            .tag("tablet_id", tablet_id);
5094
5095
4.26k
    if (should_recycle_versioned_keys()) {
5096
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
5097
14
        if (ret != 0) {
5098
0
            return ret;
5099
0
        }
5100
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
5101
        // during the recycle_versioned_tablet process.
5102
        //
5103
        // .. And remove restore job rowsets of this tablet too
5104
14
    }
5105
5106
4.26k
    int ret = 0;
5107
4.26k
    auto start_time = steady_clock::now();
5108
5109
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5110
5111
    // collect resource ids
5112
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5113
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5114
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5115
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5116
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5117
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5118
5119
260
    std::set<std::string> resource_ids;
5120
260
    int64_t recycle_rowsets_number = 0;
5121
260
    int64_t recycle_segments_number = 0;
5122
260
    int64_t recycle_rowsets_data_size = 0;
5123
260
    int64_t recycle_rowsets_index_size = 0;
5124
260
    int64_t recycle_restore_job_rowsets_number = 0;
5125
260
    int64_t recycle_restore_job_segments_number = 0;
5126
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
5127
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
5128
260
    int64_t max_rowset_version = 0;
5129
260
    int64_t min_rowset_creation_time = INT64_MAX;
5130
260
    int64_t max_rowset_creation_time = 0;
5131
260
    int64_t min_rowset_expiration_time = INT64_MAX;
5132
260
    int64_t max_rowset_expiration_time = 0;
5133
5134
260
    DORIS_CLOUD_DEFER {
5135
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5136
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5137
260
                .tag("instance_id", instance_id_)
5138
260
                .tag("tablet_id", tablet_id)
5139
260
                .tag("recycle rowsets number", recycle_rowsets_number)
5140
260
                .tag("recycle segments number", recycle_segments_number)
5141
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5142
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5143
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5144
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5145
260
                .tag("all restore job rowsets recycle data size",
5146
260
                     recycle_restore_job_rowsets_data_size)
5147
260
                .tag("all restore job rowsets recycle index size",
5148
260
                     recycle_restore_job_rowsets_index_size)
5149
260
                .tag("max rowset version", max_rowset_version)
5150
260
                .tag("min rowset creation time", min_rowset_creation_time)
5151
260
                .tag("max rowset creation time", max_rowset_creation_time)
5152
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5153
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5154
260
                .tag("task type", metrics_context.operation_type)
5155
260
                .tag("ret", ret);
5156
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5134
260
    DORIS_CLOUD_DEFER {
5135
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5136
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5137
260
                .tag("instance_id", instance_id_)
5138
260
                .tag("tablet_id", tablet_id)
5139
260
                .tag("recycle rowsets number", recycle_rowsets_number)
5140
260
                .tag("recycle segments number", recycle_segments_number)
5141
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5142
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5143
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5144
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5145
260
                .tag("all restore job rowsets recycle data size",
5146
260
                     recycle_restore_job_rowsets_data_size)
5147
260
                .tag("all restore job rowsets recycle index size",
5148
260
                     recycle_restore_job_rowsets_index_size)
5149
260
                .tag("max rowset version", max_rowset_version)
5150
260
                .tag("min rowset creation time", min_rowset_creation_time)
5151
260
                .tag("max rowset creation time", max_rowset_creation_time)
5152
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5153
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5154
260
                .tag("task type", metrics_context.operation_type)
5155
260
                .tag("ret", ret);
5156
260
    };
5157
5158
260
    std::unique_ptr<Transaction> txn;
5159
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5160
0
        LOG_WARNING("failed to recycle tablet ")
5161
0
                .tag("tablet id", tablet_id)
5162
0
                .tag("instance_id", instance_id_)
5163
0
                .tag("reason", "failed to create txn");
5164
0
        ret = -1;
5165
0
    }
5166
260
    GetRowsetResponse resp;
5167
260
    std::string msg;
5168
260
    MetaServiceCode code = MetaServiceCode::OK;
5169
    // get rowsets in tablet
5170
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5171
260
                        tablet_id, code, msg, &resp);
5172
260
    if (code != MetaServiceCode::OK) {
5173
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5174
0
                .tag("tablet id", tablet_id)
5175
0
                .tag("msg", msg)
5176
0
                .tag("code", code)
5177
0
                .tag("instance id", instance_id_);
5178
0
        ret = -1;
5179
0
    }
5180
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
5181
5182
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
5183
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
5184
3
            if (rs_meta.num_segments() <= 0) {
5185
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5186
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5187
2
                        .tag("instance_id", instance_id_)
5188
2
                        .tag("tablet_id", tablet_id);
5189
2
                recycle_rowsets_number += 1;
5190
2
                continue;
5191
2
            }
5192
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5193
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5194
1
                    .tag("instance_id", instance_id_)
5195
1
                    .tag("tablet_id", tablet_id);
5196
1
            return -1;
5197
3
        }
5198
2.55k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5199
1
                << "rs_meta" << rs_meta.ShortDebugString();
5200
2.55k
        auto it = accessor_map_.find(rs_meta.resource_id());
5201
        // possible if the accessor is not initilized correctly
5202
2.55k
        if (it == accessor_map_.end()) [[unlikely]] {
5203
1
            LOG_WARNING(
5204
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5205
1
                    "recycle process")
5206
1
                    .tag("tablet id", tablet_id)
5207
1
                    .tag("instance_id", instance_id_)
5208
1
                    .tag("resource_id", rs_meta.resource_id())
5209
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5210
1
            return -1;
5211
1
        }
5212
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5213
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5214
0
                    .tag("instance_id", instance_id_)
5215
0
                    .tag("tablet_id", tablet_id)
5216
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5217
0
            return -1;
5218
0
        }
5219
2.54k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5220
2.54k
                                                           nullptr) != 0) {
5221
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5222
0
                    .tag("instance_id", instance_id_)
5223
0
                    .tag("tablet_id", tablet_id)
5224
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5225
0
            return -1;
5226
0
        }
5227
2.54k
        recycle_rowsets_number += 1;
5228
2.54k
        recycle_segments_number += rs_meta.num_segments();
5229
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5230
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5231
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5232
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5233
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5234
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5235
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5236
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5237
2.54k
    }
5238
5239
    // get restore job rowset in tablet
5240
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5241
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5242
258
    if (code != MetaServiceCode::OK) {
5243
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5244
0
                .tag("tablet id", tablet_id)
5245
0
                .tag("msg", msg)
5246
0
                .tag("code", code)
5247
0
                .tag("instance id", instance_id_);
5248
0
        return -1;
5249
0
    }
5250
5251
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5252
0
        if (!rs_meta.has_resource_id()) {
5253
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5254
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5255
0
                    .tag("instance_id", instance_id_)
5256
0
                    .tag("tablet_id", tablet_id);
5257
0
            return -1;
5258
0
        }
5259
5260
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5261
        // possible if the accessor is not initilized correctly
5262
0
        if (it == accessor_map_.end()) [[unlikely]] {
5263
0
            LOG_WARNING(
5264
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5265
0
                    "recycle process")
5266
0
                    .tag("tablet id", tablet_id)
5267
0
                    .tag("instance_id", instance_id_)
5268
0
                    .tag("resource_id", rs_meta.resource_id())
5269
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5270
0
            return -1;
5271
0
        }
5272
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5273
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5274
0
                    .tag("instance_id", instance_id_)
5275
0
                    .tag("tablet_id", tablet_id)
5276
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5277
0
            return -1;
5278
0
        }
5279
0
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5280
0
                                                           nullptr) != 0) {
5281
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5282
0
                    .tag("instance_id", instance_id_)
5283
0
                    .tag("tablet_id", tablet_id)
5284
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5285
0
            return -1;
5286
0
        }
5287
0
        recycle_restore_job_rowsets_number += 1;
5288
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5289
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5290
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5291
0
        resource_ids.emplace(rs_meta.resource_id());
5292
0
    }
5293
5294
258
    LOG_INFO("recycle tablet start to delete object")
5295
258
            .tag("instance id", instance_id_)
5296
258
            .tag("tablet id", tablet_id)
5297
258
            .tag("recycle tablet resource ids are",
5298
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5299
258
                                 [](std::string rs_id, const auto& it) {
5300
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5301
217
                                 }));
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEEDaSB_RKT_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEEDaSB_RKT_
Line
Count
Source
5299
217
                                 [](std::string rs_id, const auto& it) {
5300
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5301
217
                                 }));
5302
5303
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5304
258
            _thread_pool_group.s3_producer_pool,
5305
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5306
258
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clERKSt4pairIiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE
Line
Count
Source
5306
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5307
5308
    // delete all rowset data in this tablet
5309
    // ATTN: there may be data leak if not all accessor initilized successfully
5310
    //       partial data deleted if the tablet is stored cross-storage vault
5311
    //       vault id is not attached to TabletMeta...
5312
258
    for (const auto& resource_id : resource_ids) {
5313
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5314
217
        concurrent_delete_executor.add(
5315
217
                [&, rs_id = resource_id,
5316
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5317
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5318
217
                    if (res != 0) {
5319
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5320
3
                                     << " path=" << accessor_ptr->uri()
5321
3
                                     << " task type=" << metrics_context.operation_type;
5322
3
                        return std::make_pair(-1, rs_id);
5323
3
                    }
5324
214
                    return std::make_pair(0, rs_id);
5325
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5316
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5317
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5318
217
                    if (res != 0) {
5319
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5320
3
                                     << " path=" << accessor_ptr->uri()
5321
3
                                     << " task type=" << metrics_context.operation_type;
5322
3
                        return std::make_pair(-1, rs_id);
5323
3
                    }
5324
214
                    return std::make_pair(0, rs_id);
5325
217
                });
5326
217
    }
5327
5328
258
    bool finished = true;
5329
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5330
258
    for (auto& r : rets) {
5331
217
        if (r.first != 0) {
5332
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5333
3
            ret = -1;
5334
3
        }
5335
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5336
217
    }
5337
258
    ret = finished ? ret : -1;
5338
5339
258
    if (ret != 0) { // failed recycle tablet data
5340
3
        LOG_WARNING("ret!=0")
5341
3
                .tag("finished", finished)
5342
3
                .tag("ret", ret)
5343
3
                .tag("instance_id", instance_id_)
5344
3
                .tag("tablet_id", tablet_id);
5345
3
        return ret;
5346
3
    }
5347
5348
255
    tablet_metrics_context_.total_recycled_data_size +=
5349
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5350
255
    tablet_metrics_context_.total_recycled_num += 1;
5351
255
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5352
255
    segment_metrics_context_.total_recycled_data_size +=
5353
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5354
255
    metrics_context.total_recycled_data_size +=
5355
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5356
255
    tablet_metrics_context_.report();
5357
255
    segment_metrics_context_.report();
5358
255
    metrics_context.report();
5359
5360
255
    txn.reset();
5361
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5362
0
        LOG_WARNING("failed to recycle tablet ")
5363
0
                .tag("tablet id", tablet_id)
5364
0
                .tag("instance_id", instance_id_)
5365
0
                .tag("reason", "failed to create txn");
5366
0
        ret = -1;
5367
0
    }
5368
    // delete all rowset kv in this tablet
5369
255
    txn->remove(rs_key0, rs_key1);
5370
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5371
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5372
5373
    // remove delete bitmap for MoW table
5374
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5375
255
    txn->remove(pending_key);
5376
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5377
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5378
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5379
5380
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5381
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5382
255
    txn->remove(dbm_start_key, dbm_end_key);
5383
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5384
255
              << " end=" << hex(dbm_end_key);
5385
5386
255
    TxnErrorCode err = txn->commit();
5387
255
    if (err != TxnErrorCode::TXN_OK) {
5388
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5389
0
        ret = -1;
5390
0
    }
5391
5392
255
    if (ret == 0) {
5393
        // All object files under tablet have been deleted
5394
255
        std::lock_guard lock(recycled_tablets_mtx_);
5395
255
        recycled_tablets_.insert(tablet_id);
5396
255
    }
5397
5398
255
    return ret;
5399
258
}
5400
5401
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5402
14
                                               RecyclerMetricsContext& metrics_context) {
5403
14
    int ret = 0;
5404
14
    auto start_time = steady_clock::now();
5405
5406
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5407
5408
    // collect resource ids
5409
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5410
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5411
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5412
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5413
5414
11
    int64_t recycle_rowsets_number = 0;
5415
11
    int64_t recycle_segments_number = 0;
5416
11
    int64_t recycle_rowsets_data_size = 0;
5417
11
    int64_t recycle_rowsets_index_size = 0;
5418
11
    int64_t max_rowset_version = 0;
5419
11
    int64_t min_rowset_creation_time = INT64_MAX;
5420
11
    int64_t max_rowset_creation_time = 0;
5421
11
    int64_t min_rowset_expiration_time = INT64_MAX;
5422
11
    int64_t max_rowset_expiration_time = 0;
5423
5424
11
    DORIS_CLOUD_DEFER {
5425
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5426
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5427
11
                .tag("instance_id", instance_id_)
5428
11
                .tag("tablet_id", tablet_id)
5429
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5430
11
                .tag("recycle segments number", recycle_segments_number)
5431
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5432
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5433
11
                .tag("max rowset version", max_rowset_version)
5434
11
                .tag("min rowset creation time", min_rowset_creation_time)
5435
11
                .tag("max rowset creation time", max_rowset_creation_time)
5436
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5437
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5438
11
                .tag("ret", ret);
5439
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5424
11
    DORIS_CLOUD_DEFER {
5425
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5426
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5427
11
                .tag("instance_id", instance_id_)
5428
11
                .tag("tablet_id", tablet_id)
5429
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5430
11
                .tag("recycle segments number", recycle_segments_number)
5431
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5432
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5433
11
                .tag("max rowset version", max_rowset_version)
5434
11
                .tag("min rowset creation time", min_rowset_creation_time)
5435
11
                .tag("max rowset creation time", max_rowset_creation_time)
5436
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5437
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5438
11
                .tag("ret", ret);
5439
11
    };
5440
5441
11
    std::unique_ptr<Transaction> txn;
5442
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5443
0
        LOG_WARNING("failed to recycle tablet ")
5444
0
                .tag("tablet id", tablet_id)
5445
0
                .tag("instance_id", instance_id_)
5446
0
                .tag("reason", "failed to create txn");
5447
0
        ret = -1;
5448
0
    }
5449
5450
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5451
    // by the related operation logs.
5452
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5453
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5454
11
    MetaReader meta_reader(instance_id_);
5455
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5456
11
    if (err == TxnErrorCode::TXN_OK) {
5457
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5458
11
    }
5459
11
    if (err != TxnErrorCode::TXN_OK) {
5460
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5461
0
                .tag("tablet id", tablet_id)
5462
0
                .tag("err", err)
5463
0
                .tag("instance id", instance_id_);
5464
0
        ret = -1;
5465
0
    }
5466
5467
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5468
11
             load_rowset_metas.size(), compact_rowset_metas.size())
5469
11
            .tag("instance_id", instance_id_)
5470
11
            .tag("tablet_id", tablet_id);
5471
5472
11
    SyncExecutor<int> concurrent_delete_executor(
5473
11
            _thread_pool_group.s3_producer_pool,
5474
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5475
11
            [](const int& ret) { return ret != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clERKi
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_1clERKi
5476
5477
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5478
60
        recycle_rowsets_number += 1;
5479
60
        recycle_segments_number += rs_meta.num_segments();
5480
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5481
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5482
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5483
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5484
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5485
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5486
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5487
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5477
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5478
60
        recycle_rowsets_number += 1;
5479
60
        recycle_segments_number += rs_meta.num_segments();
5480
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5481
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5482
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5483
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5484
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5485
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5486
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5487
60
    };
5488
5489
11
    std::vector<RowsetDeleteTask> all_tasks;
5490
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5491
60
        update_rowset_stats(rs_meta);
5492
        // Version 0-1 rowset has no resource_id and no actual data files,
5493
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5494
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5495
60
        RowsetDeleteTask task;
5496
60
        task.rowset_meta = rs_meta;
5497
60
        task.versioned_rowset_key =
5498
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5499
60
        task.non_versioned_rowset_key =
5500
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5501
60
        task.versionstamp = versionstamp;
5502
60
        all_tasks.push_back(std::move(task));
5503
60
    }
5504
5505
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5506
0
        update_rowset_stats(rs_meta);
5507
        // Version 0-1 rowset has no resource_id and no actual data files,
5508
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5509
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5510
0
        RowsetDeleteTask task;
5511
0
        task.rowset_meta = rs_meta;
5512
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5513
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5514
0
        task.non_versioned_rowset_key =
5515
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5516
0
        task.versionstamp = versionstamp;
5517
0
        all_tasks.push_back(std::move(task));
5518
0
    }
5519
5520
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5521
0
        RecycleRowsetPB recycle_rowset;
5522
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5523
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5524
0
            return -1;
5525
0
        }
5526
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5527
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5528
                // in old version, keep this key-value pair and it needs to be checked manually
5529
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5530
0
                return -1;
5531
0
            }
5532
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5533
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5534
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5535
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5536
0
                return -1;
5537
0
            }
5538
            // decode rowset_id
5539
0
            auto k1 = k;
5540
0
            k1.remove_prefix(1);
5541
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5542
0
            decode_key(&k1, &out);
5543
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5544
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5545
0
            LOG_INFO("delete old-version rowset data")
5546
0
                    .tag("instance_id", instance_id_)
5547
0
                    .tag("tablet_id", tablet_id)
5548
0
                    .tag("rowset_id", rowset_id);
5549
5550
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5551
            // so we must use prefix deletion directly instead of batch delete.
5552
0
            concurrent_delete_executor.add(
5553
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5554
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5555
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5556
0
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Unexecuted instantiation: recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
5557
0
        } else {
5558
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5559
            // Version 0-1 rowset has no resource_id and no actual data files,
5560
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5561
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5562
0
            RowsetDeleteTask task;
5563
0
            task.rowset_meta = rowset_meta;
5564
0
            task.recycle_rowset_key = k;
5565
0
            all_tasks.push_back(std::move(task));
5566
0
        }
5567
0
        return 0;
5568
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
5569
5570
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5571
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5572
0
                .tag("tablet id", tablet_id)
5573
0
                .tag("instance_id", instance_id_)
5574
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5575
0
        ret = -1;
5576
0
    }
5577
5578
    // Phase 1: Classify tasks by ref_count
5579
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5580
60
    for (auto& task : all_tasks) {
5581
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5582
60
        if (classify_ret < 0) {
5583
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5584
0
                    .tag("instance_id", instance_id_)
5585
0
                    .tag("tablet_id", tablet_id)
5586
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5587
0
            concurrent_delete_executor.add([this, t = std::move(task)]() mutable {
5588
0
                return recycle_rowset_meta_and_data(t);
5589
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5590
0
        }
5591
60
    }
5592
5593
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5594
5595
11
    LOG_INFO("batch delete plan created")
5596
11
            .tag("instance_id", instance_id_)
5597
11
            .tag("tablet_id", tablet_id)
5598
11
            .tag("plan_count", batch_delete_tasks.size());
5599
5600
    // Phase 2: Execute batch delete using existing delete_rowset_data
5601
11
    if (!batch_delete_tasks.empty()) {
5602
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5603
49
        for (const auto& task : batch_delete_tasks) {
5604
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5605
49
            if (task.rowset_meta.resource_id().empty()) {
5606
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5607
10
                        .tag("instance_id", instance_id_)
5608
10
                        .tag("tablet_id", tablet_id)
5609
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5610
10
                continue;
5611
10
            }
5612
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5613
39
        }
5614
5615
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5616
10
        bool delete_success = true;
5617
10
        if (!rowsets_to_delete.empty()) {
5618
9
            RecyclerMetricsContext batch_metrics_context(instance_id_,
5619
9
                                                         "batch_delete_versioned_tablet");
5620
9
            int delete_ret = delete_rowset_data(
5621
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, batch_metrics_context);
5622
9
            if (delete_ret != 0) {
5623
0
                LOG_WARNING("batch delete execution failed")
5624
0
                        .tag("instance_id", instance_id_)
5625
0
                        .tag("tablet_id", tablet_id);
5626
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5627
0
                ret = -1;
5628
0
                delete_success = false;
5629
0
            }
5630
9
        }
5631
5632
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5633
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5634
10
        if (delete_success) {
5635
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5636
10
            if (cleanup_ret != 0) {
5637
0
                LOG_WARNING("batch delete cleanup failed")
5638
0
                        .tag("instance_id", instance_id_)
5639
0
                        .tag("tablet_id", tablet_id);
5640
0
                ret = -1;
5641
0
            }
5642
10
        }
5643
10
    }
5644
5645
    // Always wait for fallback tasks to complete before returning
5646
11
    bool finished = true;
5647
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5648
11
    for (int r : rets) {
5649
0
        if (r != 0) {
5650
0
            ret = -1;
5651
0
        }
5652
0
    }
5653
5654
11
    ret = finished ? ret : -1;
5655
5656
11
    if (ret != 0) { // failed recycle tablet data
5657
0
        LOG_WARNING("recycle versioned tablet failed")
5658
0
                .tag("finished", finished)
5659
0
                .tag("ret", ret)
5660
0
                .tag("instance_id", instance_id_)
5661
0
                .tag("tablet_id", tablet_id);
5662
0
        return ret;
5663
0
    }
5664
5665
11
    tablet_metrics_context_.total_recycled_data_size +=
5666
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5667
11
    tablet_metrics_context_.total_recycled_num += 1;
5668
11
    segment_metrics_context_.total_recycled_num += recycle_segments_number;
5669
11
    segment_metrics_context_.total_recycled_data_size +=
5670
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5671
11
    metrics_context.total_recycled_data_size +=
5672
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5673
11
    tablet_metrics_context_.report();
5674
11
    segment_metrics_context_.report();
5675
11
    metrics_context.report();
5676
5677
11
    txn.reset();
5678
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5679
0
        LOG_WARNING("failed to recycle tablet ")
5680
0
                .tag("tablet id", tablet_id)
5681
0
                .tag("instance_id", instance_id_)
5682
0
                .tag("reason", "failed to create txn");
5683
0
        ret = -1;
5684
0
    }
5685
    // delete all rowset kv in this tablet
5686
11
    txn->remove(rs_key0, rs_key1);
5687
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5688
5689
    // remove delete bitmap for MoW table
5690
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5691
11
    txn->remove(pending_key);
5692
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5693
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5694
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5695
5696
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5697
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5698
11
    txn->remove(dbm_start_key, dbm_end_key);
5699
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5700
11
              << " end=" << hex(dbm_end_key);
5701
5702
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5703
11
    std::string tablet_index_val;
5704
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5705
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5706
0
        LOG_WARNING("failed to get tablet index kv")
5707
0
                .tag("instance_id", instance_id_)
5708
0
                .tag("tablet_id", tablet_id)
5709
0
                .tag("err", err);
5710
0
        ret = -1;
5711
11
    } else if (err == TxnErrorCode::TXN_OK) {
5712
        // If the tablet index kv exists, we need to delete it
5713
10
        TabletIndexPB tablet_index_pb;
5714
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5715
0
            LOG_WARNING("failed to parse tablet index pb")
5716
0
                    .tag("instance_id", instance_id_)
5717
0
                    .tag("tablet_id", tablet_id);
5718
0
            ret = -1;
5719
10
        } else {
5720
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5721
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5722
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5723
10
            txn->remove(versioned_inverted_idx_key);
5724
10
            txn->remove(versioned_idx_key);
5725
10
        }
5726
10
    }
5727
5728
11
    err = txn->commit();
5729
11
    if (err != TxnErrorCode::TXN_OK) {
5730
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5731
0
        ret = -1;
5732
0
    }
5733
5734
11
    if (ret == 0) {
5735
        // All object files under tablet have been deleted
5736
11
        std::lock_guard lock(recycled_tablets_mtx_);
5737
11
        recycled_tablets_.insert(tablet_id);
5738
11
    }
5739
5740
11
    return ret;
5741
11
}
5742
5743
47
int InstanceRecycler::recycle_rowsets() {
5744
47
    if (should_recycle_versioned_keys()) {
5745
5
        return recycle_versioned_rowsets();
5746
5
    }
5747
5748
42
    const std::string task_name = "recycle_rowsets";
5749
42
    int64_t num_scanned = 0;
5750
42
    int64_t num_expired = 0;
5751
42
    int64_t num_prepare = 0;
5752
42
    int64_t num_compacted = 0;
5753
42
    int64_t num_empty_rowset = 0;
5754
42
    size_t total_rowset_key_size = 0;
5755
42
    size_t total_rowset_value_size = 0;
5756
42
    size_t expired_rowset_size = 0;
5757
42
    std::atomic_long num_recycled = 0;
5758
42
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5759
5760
42
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5761
42
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5762
42
    std::string recyc_rs_key0;
5763
42
    std::string recyc_rs_key1;
5764
42
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5765
42
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5766
5767
42
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5768
5769
42
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5770
42
    register_recycle_task(task_name, start_time);
5771
5772
42
    DORIS_CLOUD_DEFER {
5773
42
        unregister_recycle_task(task_name);
5774
42
        int64_t cost =
5775
42
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5776
42
        metrics_context.finish_report();
5777
42
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5778
42
                .tag("instance_id", instance_id_)
5779
42
                .tag("num_scanned", num_scanned)
5780
42
                .tag("num_expired", num_expired)
5781
42
                .tag("num_recycled", num_recycled)
5782
42
                .tag("num_recycled.prepare", num_prepare)
5783
42
                .tag("num_recycled.compacted", num_compacted)
5784
42
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5785
42
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5786
42
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5787
42
                .tag("expired_rowset_meta_size", expired_rowset_size);
5788
42
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5772
7
    DORIS_CLOUD_DEFER {
5773
7
        unregister_recycle_task(task_name);
5774
7
        int64_t cost =
5775
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5776
7
        metrics_context.finish_report();
5777
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5778
7
                .tag("instance_id", instance_id_)
5779
7
                .tag("num_scanned", num_scanned)
5780
7
                .tag("num_expired", num_expired)
5781
7
                .tag("num_recycled", num_recycled)
5782
7
                .tag("num_recycled.prepare", num_prepare)
5783
7
                .tag("num_recycled.compacted", num_compacted)
5784
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5785
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5786
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5787
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5788
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5772
35
    DORIS_CLOUD_DEFER {
5773
35
        unregister_recycle_task(task_name);
5774
35
        int64_t cost =
5775
35
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5776
35
        metrics_context.finish_report();
5777
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5778
35
                .tag("instance_id", instance_id_)
5779
35
                .tag("num_scanned", num_scanned)
5780
35
                .tag("num_expired", num_expired)
5781
35
                .tag("num_recycled", num_recycled)
5782
35
                .tag("num_recycled.prepare", num_prepare)
5783
35
                .tag("num_recycled.compacted", num_compacted)
5784
35
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5785
35
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5786
35
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5787
35
                .tag("expired_rowset_meta_size", expired_rowset_size);
5788
35
    };
5789
5790
42
    std::vector<std::string> rowset_keys;
5791
42
    std::vector<std::string> rowset_keys_to_mark_recycled;
5792
42
    std::vector<std::string> rowset_keys_to_abort_job;
5793
    // rowset_id -> rowset_meta
5794
    // store rowset id and meta for statistics rs size when delete
5795
42
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5796
5797
42
    std::mutex async_recycled_rowset_keys_mutex;
5798
42
    std::vector<std::string> async_recycled_rowset_keys;
5799
42
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5800
42
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5801
42
    worker_pool->start();
5802
42
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5803
42
                                            int64_t partition_id, int64_t tablet_id,
5804
903
                                            const std::string& rowset_id) {
5805
        // Try to delete rowset data in background thread
5806
903
        int ret = worker_pool->submit_with_timeout(
5807
903
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5808
732
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5809
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5810
0
                        return;
5811
0
                    }
5812
732
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5813
732
                        0) {
5814
0
                        return;
5815
0
                    }
5816
732
                    std::vector<std::string> keys;
5817
732
                    {
5818
732
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5819
732
                        async_recycled_rowset_keys.push_back(std::move(key));
5820
732
                        if (async_recycled_rowset_keys.size() > 100) {
5821
7
                            keys.swap(async_recycled_rowset_keys);
5822
7
                        }
5823
732
                    }
5824
732
                    if (keys.empty()) return;
5825
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5826
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5827
0
                                     << instance_id_;
5828
7
                    } else {
5829
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5830
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5831
7
                                           num_recycled, start_time);
5832
7
                    }
5833
7
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5807
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5808
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5809
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5810
0
                        return;
5811
0
                    }
5812
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5813
1
                        0) {
5814
0
                        return;
5815
0
                    }
5816
1
                    std::vector<std::string> keys;
5817
1
                    {
5818
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5819
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5820
1
                        if (async_recycled_rowset_keys.size() > 100) {
5821
0
                            keys.swap(async_recycled_rowset_keys);
5822
0
                        }
5823
1
                    }
5824
1
                    if (keys.empty()) return;
5825
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5826
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5827
0
                                     << instance_id_;
5828
0
                    } else {
5829
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5830
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5831
0
                                           num_recycled, start_time);
5832
0
                    }
5833
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5807
731
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5808
731
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5809
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5810
0
                        return;
5811
0
                    }
5812
731
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5813
731
                        0) {
5814
0
                        return;
5815
0
                    }
5816
731
                    std::vector<std::string> keys;
5817
731
                    {
5818
731
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5819
731
                        async_recycled_rowset_keys.push_back(std::move(key));
5820
731
                        if (async_recycled_rowset_keys.size() > 100) {
5821
7
                            keys.swap(async_recycled_rowset_keys);
5822
7
                        }
5823
731
                    }
5824
731
                    if (keys.empty()) return;
5825
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5826
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5827
0
                                     << instance_id_;
5828
7
                    } else {
5829
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5830
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5831
7
                                           num_recycled, start_time);
5832
7
                    }
5833
7
                },
5834
903
                0);
5835
903
        if (ret == 0) return 0;
5836
        // Submit task failed, delete rowset data in current thread
5837
171
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5838
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5839
0
            return -1;
5840
0
        }
5841
171
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5842
0
            return -1;
5843
0
        }
5844
171
        rowset_keys.push_back(std::move(key));
5845
171
        return 0;
5846
171
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5804
1
                                            const std::string& rowset_id) {
5805
        // Try to delete rowset data in background thread
5806
1
        int ret = worker_pool->submit_with_timeout(
5807
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5808
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5809
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5810
1
                        return;
5811
1
                    }
5812
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5813
1
                        0) {
5814
1
                        return;
5815
1
                    }
5816
1
                    std::vector<std::string> keys;
5817
1
                    {
5818
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5819
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5820
1
                        if (async_recycled_rowset_keys.size() > 100) {
5821
1
                            keys.swap(async_recycled_rowset_keys);
5822
1
                        }
5823
1
                    }
5824
1
                    if (keys.empty()) return;
5825
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5826
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5827
1
                                     << instance_id_;
5828
1
                    } else {
5829
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5830
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5831
1
                                           num_recycled, start_time);
5832
1
                    }
5833
1
                },
5834
1
                0);
5835
1
        if (ret == 0) return 0;
5836
        // Submit task failed, delete rowset data in current thread
5837
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5838
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5839
0
            return -1;
5840
0
        }
5841
0
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5842
0
            return -1;
5843
0
        }
5844
0
        rowset_keys.push_back(std::move(key));
5845
0
        return 0;
5846
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5804
902
                                            const std::string& rowset_id) {
5805
        // Try to delete rowset data in background thread
5806
902
        int ret = worker_pool->submit_with_timeout(
5807
902
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5808
902
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5809
902
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5810
902
                        return;
5811
902
                    }
5812
902
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5813
902
                        0) {
5814
902
                        return;
5815
902
                    }
5816
902
                    std::vector<std::string> keys;
5817
902
                    {
5818
902
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5819
902
                        async_recycled_rowset_keys.push_back(std::move(key));
5820
902
                        if (async_recycled_rowset_keys.size() > 100) {
5821
902
                            keys.swap(async_recycled_rowset_keys);
5822
902
                        }
5823
902
                    }
5824
902
                    if (keys.empty()) return;
5825
902
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5826
902
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5827
902
                                     << instance_id_;
5828
902
                    } else {
5829
902
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5830
902
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5831
902
                                           num_recycled, start_time);
5832
902
                    }
5833
902
                },
5834
902
                0);
5835
902
        if (ret == 0) return 0;
5836
        // Submit task failed, delete rowset data in current thread
5837
171
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5838
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5839
0
            return -1;
5840
0
        }
5841
171
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5842
0
            return -1;
5843
0
        }
5844
171
        rowset_keys.push_back(std::move(key));
5845
171
        return 0;
5846
171
    };
5847
5848
42
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5849
5850
4.28k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5851
4.28k
        ++num_scanned;
5852
4.28k
        total_rowset_key_size += k.size();
5853
4.28k
        total_rowset_value_size += v.size();
5854
4.28k
        RecycleRowsetPB rowset;
5855
4.28k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5856
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5857
0
            return -1;
5858
0
        }
5859
5860
4.28k
        int64_t current_time = ::time(nullptr);
5861
4.28k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5862
5863
4.28k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5864
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5865
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5866
4.28k
        if (current_time < expiration) { // not expired
5867
0
            return 0;
5868
0
        }
5869
4.28k
        ++num_expired;
5870
4.28k
        expired_rowset_size += v.size();
5871
5872
4.28k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5873
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5874
                // in old version, keep this key-value pair and it needs to be checked manually
5875
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5876
0
                return -1;
5877
0
            }
5878
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5879
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5880
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5881
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5882
0
                rowset_keys.emplace_back(k);
5883
0
                return -1;
5884
0
            }
5885
            // decode rowset_id
5886
250
            auto k1 = k;
5887
250
            k1.remove_prefix(1);
5888
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5889
250
            decode_key(&k1, &out);
5890
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5891
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5892
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5893
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5894
250
                      << " task_type=" << metrics_context.operation_type;
5895
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5896
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5897
0
                return -1;
5898
0
            }
5899
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5900
250
            metrics_context.total_recycled_num++;
5901
250
            segment_metrics_context_.total_recycled_data_size +=
5902
250
                    rowset.rowset_meta().total_disk_size();
5903
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5904
250
            return 0;
5905
250
        }
5906
4.03k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5907
5908
        // TODO(plat1ko): check rowset not referenced
5909
4.03k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5910
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5911
0
                LOG_INFO("recycle rowset that has empty resource id");
5912
0
            } else {
5913
                // other situations, keep this key-value pair and it needs to be checked manually
5914
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5915
0
                return -1;
5916
0
            }
5917
0
        }
5918
4.03k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5919
4.03k
                  << " tablet_id=" << rowset_meta->tablet_id()
5920
4.03k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5921
4.03k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5922
4.03k
                  << "] txn_id=" << rowset_meta->txn_id()
5923
4.03k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5924
4.03k
                  << " rowset_meta_size=" << v.size()
5925
4.03k
                  << " creation_time=" << rowset_meta->creation_time()
5926
4.03k
                  << " task_type=" << metrics_context.operation_type;
5927
4.03k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5928
938
            if (config::enable_mark_delete_rowset_before_recycle) {
5929
23
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5930
13
                    rowset_keys_to_mark_recycled.emplace_back(k);
5931
13
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5932
13
                                 "kv "
5933
13
                                 "at next turn, instance_id="
5934
13
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5935
13
                              << " version=[" << rowset_meta->start_version() << '-'
5936
13
                              << rowset_meta->end_version() << "]";
5937
13
                    return 0;
5938
13
                }
5939
23
            }
5940
5941
925
            num_prepare += 1;
5942
925
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5943
925
                rowset_meta->end_version() != 1) {
5944
273
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5945
272
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5946
272
                                 "instance_id="
5947
272
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5948
272
                              << " version=[" << rowset_meta->start_version() << '-'
5949
272
                              << rowset_meta->end_version() << "]";
5950
272
                    rowset_keys_to_abort_job.emplace_back(k);
5951
272
                    return 0;
5952
272
                }
5953
273
            }
5954
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5955
653
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5956
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5957
0
                return -1;
5958
0
            }
5959
3.10k
        } else {
5960
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5961
3.10k
            rowset_keys.emplace_back(k);
5962
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5963
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5964
3.10k
                ++num_empty_rowset;
5965
3.10k
            }
5966
3.10k
        }
5967
3.75k
        return 0;
5968
4.03k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5850
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5851
7
        ++num_scanned;
5852
7
        total_rowset_key_size += k.size();
5853
7
        total_rowset_value_size += v.size();
5854
7
        RecycleRowsetPB rowset;
5855
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5856
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5857
0
            return -1;
5858
0
        }
5859
5860
7
        int64_t current_time = ::time(nullptr);
5861
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5862
5863
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5864
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5865
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5866
7
        if (current_time < expiration) { // not expired
5867
0
            return 0;
5868
0
        }
5869
7
        ++num_expired;
5870
7
        expired_rowset_size += v.size();
5871
5872
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5873
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5874
                // in old version, keep this key-value pair and it needs to be checked manually
5875
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5876
0
                return -1;
5877
0
            }
5878
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5879
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5880
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5881
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5882
0
                rowset_keys.emplace_back(k);
5883
0
                return -1;
5884
0
            }
5885
            // decode rowset_id
5886
0
            auto k1 = k;
5887
0
            k1.remove_prefix(1);
5888
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5889
0
            decode_key(&k1, &out);
5890
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5891
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5892
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5893
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5894
0
                      << " task_type=" << metrics_context.operation_type;
5895
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5896
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5897
0
                return -1;
5898
0
            }
5899
0
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5900
0
            metrics_context.total_recycled_num++;
5901
0
            segment_metrics_context_.total_recycled_data_size +=
5902
0
                    rowset.rowset_meta().total_disk_size();
5903
0
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5904
0
            return 0;
5905
0
        }
5906
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5907
5908
        // TODO(plat1ko): check rowset not referenced
5909
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5910
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5911
0
                LOG_INFO("recycle rowset that has empty resource id");
5912
0
            } else {
5913
                // other situations, keep this key-value pair and it needs to be checked manually
5914
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5915
0
                return -1;
5916
0
            }
5917
0
        }
5918
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5919
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5920
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5921
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5922
7
                  << "] txn_id=" << rowset_meta->txn_id()
5923
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5924
7
                  << " rowset_meta_size=" << v.size()
5925
7
                  << " creation_time=" << rowset_meta->creation_time()
5926
7
                  << " task_type=" << metrics_context.operation_type;
5927
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5928
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5929
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5930
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5931
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5932
4
                                 "kv "
5933
4
                                 "at next turn, instance_id="
5934
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5935
4
                              << " version=[" << rowset_meta->start_version() << '-'
5936
4
                              << rowset_meta->end_version() << "]";
5937
4
                    return 0;
5938
4
                }
5939
6
            }
5940
5941
3
            num_prepare += 1;
5942
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5943
3
                rowset_meta->end_version() != 1) {
5944
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5945
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5946
2
                                 "instance_id="
5947
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5948
2
                              << " version=[" << rowset_meta->start_version() << '-'
5949
2
                              << rowset_meta->end_version() << "]";
5950
2
                    rowset_keys_to_abort_job.emplace_back(k);
5951
2
                    return 0;
5952
2
                }
5953
2
            }
5954
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5955
1
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5956
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5957
0
                return -1;
5958
0
            }
5959
1
        } else {
5960
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5961
0
            rowset_keys.emplace_back(k);
5962
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5963
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5964
0
                ++num_empty_rowset;
5965
0
            }
5966
0
        }
5967
1
        return 0;
5968
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5850
4.28k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5851
4.28k
        ++num_scanned;
5852
4.28k
        total_rowset_key_size += k.size();
5853
4.28k
        total_rowset_value_size += v.size();
5854
4.28k
        RecycleRowsetPB rowset;
5855
4.28k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5856
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5857
0
            return -1;
5858
0
        }
5859
5860
4.28k
        int64_t current_time = ::time(nullptr);
5861
4.28k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5862
5863
4.28k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5864
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5865
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5866
4.28k
        if (current_time < expiration) { // not expired
5867
0
            return 0;
5868
0
        }
5869
4.28k
        ++num_expired;
5870
4.28k
        expired_rowset_size += v.size();
5871
5872
4.28k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5873
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5874
                // in old version, keep this key-value pair and it needs to be checked manually
5875
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5876
0
                return -1;
5877
0
            }
5878
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5879
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5880
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5881
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5882
0
                rowset_keys.emplace_back(k);
5883
0
                return -1;
5884
0
            }
5885
            // decode rowset_id
5886
250
            auto k1 = k;
5887
250
            k1.remove_prefix(1);
5888
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5889
250
            decode_key(&k1, &out);
5890
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5891
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5892
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5893
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5894
250
                      << " task_type=" << metrics_context.operation_type;
5895
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5896
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5897
0
                return -1;
5898
0
            }
5899
250
            metrics_context.total_recycled_data_size += rowset.rowset_meta().total_disk_size();
5900
250
            metrics_context.total_recycled_num++;
5901
250
            segment_metrics_context_.total_recycled_data_size +=
5902
250
                    rowset.rowset_meta().total_disk_size();
5903
250
            segment_metrics_context_.total_recycled_num += rowset.rowset_meta().num_segments();
5904
250
            return 0;
5905
250
        }
5906
4.03k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5907
5908
        // TODO(plat1ko): check rowset not referenced
5909
4.03k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5910
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5911
0
                LOG_INFO("recycle rowset that has empty resource id");
5912
0
            } else {
5913
                // other situations, keep this key-value pair and it needs to be checked manually
5914
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5915
0
                return -1;
5916
0
            }
5917
0
        }
5918
4.03k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5919
4.03k
                  << " tablet_id=" << rowset_meta->tablet_id()
5920
4.03k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5921
4.03k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5922
4.03k
                  << "] txn_id=" << rowset_meta->txn_id()
5923
4.03k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5924
4.03k
                  << " rowset_meta_size=" << v.size()
5925
4.03k
                  << " creation_time=" << rowset_meta->creation_time()
5926
4.03k
                  << " task_type=" << metrics_context.operation_type;
5927
4.03k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5928
931
            if (config::enable_mark_delete_rowset_before_recycle) {
5929
17
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5930
9
                    rowset_keys_to_mark_recycled.emplace_back(k);
5931
9
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5932
9
                                 "kv "
5933
9
                                 "at next turn, instance_id="
5934
9
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5935
9
                              << " version=[" << rowset_meta->start_version() << '-'
5936
9
                              << rowset_meta->end_version() << "]";
5937
9
                    return 0;
5938
9
                }
5939
17
            }
5940
5941
922
            num_prepare += 1;
5942
922
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5943
922
                rowset_meta->end_version() != 1) {
5944
271
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5945
270
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5946
270
                                 "instance_id="
5947
270
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5948
270
                              << " version=[" << rowset_meta->start_version() << '-'
5949
270
                              << rowset_meta->end_version() << "]";
5950
270
                    rowset_keys_to_abort_job.emplace_back(k);
5951
270
                    return 0;
5952
270
                }
5953
271
            }
5954
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5955
652
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5956
652
                                             rowset_meta->rowset_id_v2()) != 0) {
5957
0
                return -1;
5958
0
            }
5959
3.10k
        } else {
5960
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5961
3.10k
            rowset_keys.emplace_back(k);
5962
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5963
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5964
3.10k
                ++num_empty_rowset;
5965
3.10k
            }
5966
3.10k
        }
5967
3.75k
        return 0;
5968
4.03k
    };
5969
5970
48
    auto loop_done = [&]() -> int {
5971
48
        std::vector<std::string> rowset_keys_to_delete;
5972
        // rowset_id -> rowset_meta
5973
        // store rowset id and meta for statistics rs size when delete
5974
48
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5975
48
        std::vector<std::string> mark_keys_to_process;
5976
48
        std::vector<std::string> abort_job_keys_to_process;
5977
48
        rowset_keys_to_delete.swap(rowset_keys);
5978
48
        rowsets_to_delete.swap(rowsets);
5979
48
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5980
48
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5981
48
        if (!mark_keys_to_process.empty()) {
5982
11
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5983
11
                    *worker_pool, std::move(mark_keys_to_process));
5984
11
        }
5985
48
        if (!abort_job_keys_to_process.empty()) {
5986
15
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5987
15
                                               &num_recycled);
5988
15
        }
5989
48
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5990
48
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5991
48
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5992
48
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5993
48
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5994
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5995
0
                return;
5996
0
            }
5997
48
            if (!versioned_delete_bitmap_key_groups.empty() &&
5998
48
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5999
11
                                                         versioned_delete_bitmap_key_groups) != 0) {
6000
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6001
0
                             << instance_id_;
6002
0
                return;
6003
0
            }
6004
48
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6005
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6006
0
                return;
6007
0
            }
6008
48
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6009
48
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5990
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5991
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5992
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5993
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5994
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5995
0
                return;
5996
0
            }
5997
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5998
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5999
0
                                                         versioned_delete_bitmap_key_groups) != 0) {
6000
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6001
0
                             << instance_id_;
6002
0
                return;
6003
0
            }
6004
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6005
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6006
0
                return;
6007
0
            }
6008
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6009
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE_clEv
Line
Count
Source
5990
41
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5991
41
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5992
41
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5993
41
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5994
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5995
0
                return;
5996
0
            }
5997
41
            if (!versioned_delete_bitmap_key_groups.empty() &&
5998
41
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5999
11
                                                         versioned_delete_bitmap_key_groups) != 0) {
6000
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6001
0
                             << instance_id_;
6002
0
                return;
6003
0
            }
6004
41
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6005
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6006
0
                return;
6007
0
            }
6008
41
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6009
41
        });
6010
48
        return 0;
6011
48
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5970
7
    auto loop_done = [&]() -> int {
5971
7
        std::vector<std::string> rowset_keys_to_delete;
5972
        // rowset_id -> rowset_meta
5973
        // store rowset id and meta for statistics rs size when delete
5974
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5975
7
        std::vector<std::string> mark_keys_to_process;
5976
7
        std::vector<std::string> abort_job_keys_to_process;
5977
7
        rowset_keys_to_delete.swap(rowset_keys);
5978
7
        rowsets_to_delete.swap(rowsets);
5979
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5980
7
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5981
7
        if (!mark_keys_to_process.empty()) {
5982
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5983
4
                    *worker_pool, std::move(mark_keys_to_process));
5984
4
        }
5985
7
        if (!abort_job_keys_to_process.empty()) {
5986
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5987
2
                                               &num_recycled);
5988
2
        }
5989
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5990
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5991
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5992
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5993
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5994
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5995
7
                return;
5996
7
            }
5997
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5998
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5999
7
                                                         versioned_delete_bitmap_key_groups) != 0) {
6000
7
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6001
7
                             << instance_id_;
6002
7
                return;
6003
7
            }
6004
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6005
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6006
7
                return;
6007
7
            }
6008
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6009
7
        });
6010
7
        return 0;
6011
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5970
41
    auto loop_done = [&]() -> int {
5971
41
        std::vector<std::string> rowset_keys_to_delete;
5972
        // rowset_id -> rowset_meta
5973
        // store rowset id and meta for statistics rs size when delete
5974
41
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5975
41
        std::vector<std::string> mark_keys_to_process;
5976
41
        std::vector<std::string> abort_job_keys_to_process;
5977
41
        rowset_keys_to_delete.swap(rowset_keys);
5978
41
        rowsets_to_delete.swap(rowsets);
5979
41
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5980
41
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5981
41
        if (!mark_keys_to_process.empty()) {
5982
7
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5983
7
                    *worker_pool, std::move(mark_keys_to_process));
5984
7
        }
5985
41
        if (!abort_job_keys_to_process.empty()) {
5986
13
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5987
13
                                               &num_recycled);
5988
13
        }
5989
41
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5990
41
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5991
41
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5992
41
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5993
41
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5994
41
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5995
41
                return;
5996
41
            }
5997
41
            if (!versioned_delete_bitmap_key_groups.empty() &&
5998
41
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5999
41
                                                         versioned_delete_bitmap_key_groups) != 0) {
6000
41
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
6001
41
                             << instance_id_;
6002
41
                return;
6003
41
            }
6004
41
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
6005
41
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6006
41
                return;
6007
41
            }
6008
41
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
6009
41
        });
6010
41
        return 0;
6011
41
    };
6012
6013
42
    if (config::enable_recycler_stats_metrics) {
6014
0
        scan_and_statistics_rowsets();
6015
0
    }
6016
    // recycle_func and loop_done for scan and recycle
6017
42
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6018
42
                               std::move(loop_done));
6019
6020
42
    worker_pool->stop();
6021
6022
42
    if (!async_recycled_rowset_keys.empty()) {
6023
4
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6024
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6025
0
            return -1;
6026
4
        } else {
6027
4
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6028
4
        }
6029
4
    }
6030
6031
    // Report final metrics after all concurrent tasks completed
6032
42
    segment_metrics_context_.report();
6033
42
    metrics_context.report();
6034
6035
42
    return ret;
6036
42
}
6037
6038
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
6039
0
                                                     int64_t tablet_id, std::string* next_key) {
6040
0
    DCHECK(next_key != nullptr);
6041
0
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
6042
0
        return -1;
6043
0
    }
6044
0
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
6045
0
    return 0;
6046
0
}
6047
6048
13
int InstanceRecycler::recycle_restore_jobs() {
6049
13
    const std::string task_name = "recycle_restore_jobs";
6050
13
    int64_t num_scanned = 0;
6051
13
    int64_t num_expired = 0;
6052
13
    int64_t num_recycled = 0;
6053
13
    int64_t num_aborted = 0;
6054
6055
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6056
6057
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
6058
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
6059
13
    std::string restore_job_key0;
6060
13
    std::string restore_job_key1;
6061
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
6062
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
6063
6064
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
6065
6066
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6067
13
    register_recycle_task(task_name, start_time);
6068
6069
13
    DORIS_CLOUD_DEFER {
6070
13
        unregister_recycle_task(task_name);
6071
13
        int64_t cost =
6072
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6073
13
        metrics_context.finish_report();
6074
6075
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6076
13
                .tag("instance_id", instance_id_)
6077
13
                .tag("num_scanned", num_scanned)
6078
13
                .tag("num_expired", num_expired)
6079
13
                .tag("num_recycled", num_recycled)
6080
13
                .tag("num_aborted", num_aborted);
6081
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
6069
13
    DORIS_CLOUD_DEFER {
6070
13
        unregister_recycle_task(task_name);
6071
13
        int64_t cost =
6072
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6073
13
        metrics_context.finish_report();
6074
6075
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
6076
13
                .tag("instance_id", instance_id_)
6077
13
                .tag("num_scanned", num_scanned)
6078
13
                .tag("num_expired", num_expired)
6079
13
                .tag("num_recycled", num_recycled)
6080
13
                .tag("num_aborted", num_aborted);
6081
13
    };
6082
6083
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6084
6085
13
    std::vector<std::string_view> restore_job_keys;
6086
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6087
41
        ++num_scanned;
6088
41
        RestoreJobCloudPB restore_job_pb;
6089
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6090
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6091
0
            return -1;
6092
0
        }
6093
41
        int64_t expiration =
6094
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6095
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6096
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6097
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6098
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6099
0
                   << " state=" << restore_job_pb.state();
6100
41
        int64_t current_time = ::time(nullptr);
6101
41
        if (current_time < expiration) { // not expired
6102
0
            return 0;
6103
0
        }
6104
41
        ++num_expired;
6105
6106
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6107
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6108
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6109
6110
41
        std::unique_ptr<Transaction> txn;
6111
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6112
41
        if (err != TxnErrorCode::TXN_OK) {
6113
0
            LOG_WARNING("failed to recycle restore job")
6114
0
                    .tag("err", err)
6115
0
                    .tag("tablet id", tablet_id)
6116
0
                    .tag("instance_id", instance_id_)
6117
0
                    .tag("reason", "failed to create txn");
6118
0
            return -1;
6119
0
        }
6120
6121
41
        std::string val;
6122
41
        err = txn->get(k, &val);
6123
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6124
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6125
0
            return 0;
6126
0
        }
6127
41
        if (err != TxnErrorCode::TXN_OK) {
6128
0
            LOG_WARNING("failed to get kv");
6129
0
            return -1;
6130
0
        }
6131
41
        restore_job_pb.Clear();
6132
41
        if (!restore_job_pb.ParseFromString(val)) {
6133
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6134
0
            return -1;
6135
0
        }
6136
6137
        // PREPARED or COMMITTED, change state to DROPPED and return
6138
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6139
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6140
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6141
0
            restore_job_pb.set_need_recycle_data(true);
6142
0
            txn->put(k, restore_job_pb.SerializeAsString());
6143
0
            err = txn->commit();
6144
0
            if (err != TxnErrorCode::TXN_OK) {
6145
0
                LOG_WARNING("failed to commit txn: {}", err);
6146
0
                return -1;
6147
0
            }
6148
0
            num_aborted++;
6149
0
            return 0;
6150
0
        }
6151
6152
        // Change state to RECYCLING
6153
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6154
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6155
21
            txn->put(k, restore_job_pb.SerializeAsString());
6156
21
            err = txn->commit();
6157
21
            if (err != TxnErrorCode::TXN_OK) {
6158
0
                LOG_WARNING("failed to commit txn: {}", err);
6159
0
                return -1;
6160
0
            }
6161
21
            return 0;
6162
21
        }
6163
6164
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6165
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6166
6167
        // Recycle all data associated with the restore job.
6168
        // This includes rowsets, segments, and related resources.
6169
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6170
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6171
0
            LOG_WARNING("failed to recycle tablet")
6172
0
                    .tag("tablet_id", tablet_id)
6173
0
                    .tag("instance_id", instance_id_);
6174
0
            return -1;
6175
0
        }
6176
6177
        // delete all restore job rowset kv
6178
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6179
6180
20
        err = txn->commit();
6181
20
        if (err != TxnErrorCode::TXN_OK) {
6182
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6183
0
                    .tag("err", err)
6184
0
                    .tag("tablet id", tablet_id)
6185
0
                    .tag("instance_id", instance_id_)
6186
0
                    .tag("reason", "failed to commit txn");
6187
0
            return -1;
6188
0
        }
6189
6190
20
        metrics_context.total_recycled_num = ++num_recycled;
6191
20
        metrics_context.report();
6192
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6193
20
        restore_job_keys.push_back(k);
6194
6195
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6196
20
                  << " tablet_id=" << tablet_id;
6197
20
        return 0;
6198
20
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6086
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
6087
41
        ++num_scanned;
6088
41
        RestoreJobCloudPB restore_job_pb;
6089
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
6090
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
6091
0
            return -1;
6092
0
        }
6093
41
        int64_t expiration =
6094
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
6095
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
6096
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
6097
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
6098
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
6099
0
                   << " state=" << restore_job_pb.state();
6100
41
        int64_t current_time = ::time(nullptr);
6101
41
        if (current_time < expiration) { // not expired
6102
0
            return 0;
6103
0
        }
6104
41
        ++num_expired;
6105
6106
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6107
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6108
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6109
6110
41
        std::unique_ptr<Transaction> txn;
6111
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6112
41
        if (err != TxnErrorCode::TXN_OK) {
6113
0
            LOG_WARNING("failed to recycle restore job")
6114
0
                    .tag("err", err)
6115
0
                    .tag("tablet id", tablet_id)
6116
0
                    .tag("instance_id", instance_id_)
6117
0
                    .tag("reason", "failed to create txn");
6118
0
            return -1;
6119
0
        }
6120
6121
41
        std::string val;
6122
41
        err = txn->get(k, &val);
6123
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6124
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6125
0
            return 0;
6126
0
        }
6127
41
        if (err != TxnErrorCode::TXN_OK) {
6128
0
            LOG_WARNING("failed to get kv");
6129
0
            return -1;
6130
0
        }
6131
41
        restore_job_pb.Clear();
6132
41
        if (!restore_job_pb.ParseFromString(val)) {
6133
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6134
0
            return -1;
6135
0
        }
6136
6137
        // PREPARED or COMMITTED, change state to DROPPED and return
6138
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6139
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6140
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6141
0
            restore_job_pb.set_need_recycle_data(true);
6142
0
            txn->put(k, restore_job_pb.SerializeAsString());
6143
0
            err = txn->commit();
6144
0
            if (err != TxnErrorCode::TXN_OK) {
6145
0
                LOG_WARNING("failed to commit txn: {}", err);
6146
0
                return -1;
6147
0
            }
6148
0
            num_aborted++;
6149
0
            return 0;
6150
0
        }
6151
6152
        // Change state to RECYCLING
6153
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6154
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6155
21
            txn->put(k, restore_job_pb.SerializeAsString());
6156
21
            err = txn->commit();
6157
21
            if (err != TxnErrorCode::TXN_OK) {
6158
0
                LOG_WARNING("failed to commit txn: {}", err);
6159
0
                return -1;
6160
0
            }
6161
21
            return 0;
6162
21
        }
6163
6164
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6165
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6166
6167
        // Recycle all data associated with the restore job.
6168
        // This includes rowsets, segments, and related resources.
6169
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6170
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6171
0
            LOG_WARNING("failed to recycle tablet")
6172
0
                    .tag("tablet_id", tablet_id)
6173
0
                    .tag("instance_id", instance_id_);
6174
0
            return -1;
6175
0
        }
6176
6177
        // delete all restore job rowset kv
6178
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6179
6180
20
        err = txn->commit();
6181
20
        if (err != TxnErrorCode::TXN_OK) {
6182
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6183
0
                    .tag("err", err)
6184
0
                    .tag("tablet id", tablet_id)
6185
0
                    .tag("instance_id", instance_id_)
6186
0
                    .tag("reason", "failed to commit txn");
6187
0
            return -1;
6188
0
        }
6189
6190
20
        metrics_context.total_recycled_num = ++num_recycled;
6191
20
        metrics_context.report();
6192
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6193
20
        restore_job_keys.push_back(k);
6194
6195
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6196
20
                  << " tablet_id=" << tablet_id;
6197
20
        return 0;
6198
20
    };
6199
6200
13
    auto loop_done = [&restore_job_keys, this]() -> int {
6201
3
        if (restore_job_keys.empty()) return 0;
6202
1
        DORIS_CLOUD_DEFER {
6203
1
            restore_job_keys.clear();
6204
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6202
1
        DORIS_CLOUD_DEFER {
6203
1
            restore_job_keys.clear();
6204
1
        };
6205
6206
1
        std::unique_ptr<Transaction> txn;
6207
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6208
1
        if (err != TxnErrorCode::TXN_OK) {
6209
0
            LOG_WARNING("failed to recycle restore job")
6210
0
                    .tag("err", err)
6211
0
                    .tag("instance_id", instance_id_)
6212
0
                    .tag("reason", "failed to create txn");
6213
0
            return -1;
6214
0
        }
6215
20
        for (auto& k : restore_job_keys) {
6216
20
            txn->remove(k);
6217
20
        }
6218
1
        err = txn->commit();
6219
1
        if (err != TxnErrorCode::TXN_OK) {
6220
0
            LOG_WARNING("failed to recycle restore job")
6221
0
                    .tag("err", err)
6222
0
                    .tag("instance_id", instance_id_)
6223
0
                    .tag("reason", "failed to commit txn");
6224
0
            return -1;
6225
0
        }
6226
1
        return 0;
6227
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
6200
3
    auto loop_done = [&restore_job_keys, this]() -> int {
6201
3
        if (restore_job_keys.empty()) return 0;
6202
1
        DORIS_CLOUD_DEFER {
6203
1
            restore_job_keys.clear();
6204
1
        };
6205
6206
1
        std::unique_ptr<Transaction> txn;
6207
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6208
1
        if (err != TxnErrorCode::TXN_OK) {
6209
0
            LOG_WARNING("failed to recycle restore job")
6210
0
                    .tag("err", err)
6211
0
                    .tag("instance_id", instance_id_)
6212
0
                    .tag("reason", "failed to create txn");
6213
0
            return -1;
6214
0
        }
6215
20
        for (auto& k : restore_job_keys) {
6216
20
            txn->remove(k);
6217
20
        }
6218
1
        err = txn->commit();
6219
1
        if (err != TxnErrorCode::TXN_OK) {
6220
0
            LOG_WARNING("failed to recycle restore job")
6221
0
                    .tag("err", err)
6222
0
                    .tag("instance_id", instance_id_)
6223
0
                    .tag("reason", "failed to commit txn");
6224
0
            return -1;
6225
0
        }
6226
1
        return 0;
6227
1
    };
6228
6229
13
    if (config::enable_recycler_stats_metrics) {
6230
0
        scan_and_statistics_restore_jobs();
6231
0
    }
6232
6233
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6234
13
                            std::move(loop_done));
6235
13
}
6236
6237
11
int InstanceRecycler::recycle_versioned_rowsets() {
6238
11
    const std::string task_name = "recycle_rowsets";
6239
11
    int64_t num_scanned = 0;
6240
11
    int64_t num_expired = 0;
6241
11
    int64_t num_prepare = 0;
6242
11
    int64_t num_compacted = 0;
6243
11
    int64_t num_empty_rowset = 0;
6244
11
    size_t total_rowset_key_size = 0;
6245
11
    size_t total_rowset_value_size = 0;
6246
11
    size_t expired_rowset_size = 0;
6247
11
    std::atomic_long num_recycled = 0;
6248
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6249
6250
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6251
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6252
11
    std::string recyc_rs_key0;
6253
11
    std::string recyc_rs_key1;
6254
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6255
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6256
6257
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6258
6259
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6260
11
    register_recycle_task(task_name, start_time);
6261
6262
11
    DORIS_CLOUD_DEFER {
6263
11
        unregister_recycle_task(task_name);
6264
11
        int64_t cost =
6265
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6266
11
        metrics_context.finish_report();
6267
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6268
11
                .tag("instance_id", instance_id_)
6269
11
                .tag("num_scanned", num_scanned)
6270
11
                .tag("num_expired", num_expired)
6271
11
                .tag("num_recycled", num_recycled)
6272
11
                .tag("num_recycled.prepare", num_prepare)
6273
11
                .tag("num_recycled.compacted", num_compacted)
6274
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6275
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6276
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6277
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6278
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6262
11
    DORIS_CLOUD_DEFER {
6263
11
        unregister_recycle_task(task_name);
6264
11
        int64_t cost =
6265
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6266
11
        metrics_context.finish_report();
6267
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6268
11
                .tag("instance_id", instance_id_)
6269
11
                .tag("num_scanned", num_scanned)
6270
11
                .tag("num_expired", num_expired)
6271
11
                .tag("num_recycled", num_recycled)
6272
11
                .tag("num_recycled.prepare", num_prepare)
6273
11
                .tag("num_recycled.compacted", num_compacted)
6274
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6275
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6276
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6277
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6278
11
    };
6279
6280
11
    std::vector<std::string> orphan_rowset_keys;
6281
6282
    // Store keys of rowset recycled by background workers
6283
11
    std::mutex async_recycled_rowset_keys_mutex;
6284
11
    std::vector<std::string> async_recycled_rowset_keys;
6285
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6286
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6287
11
    worker_pool->start();
6288
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6289
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6290
        // Try to delete rowset data in background thread
6291
400
        int ret = worker_pool->submit_with_timeout(
6292
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6293
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6294
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6295
400
                        return;
6296
400
                    }
6297
                    // The async recycled rowsets are staled format or has not been used,
6298
                    // so we don't need to check the rowset ref count key.
6299
0
                    std::vector<std::string> keys;
6300
0
                    {
6301
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6302
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6303
0
                        if (async_recycled_rowset_keys.size() > 100) {
6304
0
                            keys.swap(async_recycled_rowset_keys);
6305
0
                        }
6306
0
                    }
6307
0
                    if (keys.empty()) return;
6308
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6309
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6310
0
                                     << instance_id_;
6311
0
                    } else {
6312
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6313
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6314
0
                                           num_recycled, start_time);
6315
0
                    }
6316
0
                },
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_ENUlvE_clEv
Line
Count
Source
6292
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6293
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6294
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6295
400
                        return;
6296
400
                    }
6297
                    // The async recycled rowsets are staled format or has not been used,
6298
                    // so we don't need to check the rowset ref count key.
6299
0
                    std::vector<std::string> keys;
6300
0
                    {
6301
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6302
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6303
0
                        if (async_recycled_rowset_keys.size() > 100) {
6304
0
                            keys.swap(async_recycled_rowset_keys);
6305
0
                        }
6306
0
                    }
6307
0
                    if (keys.empty()) return;
6308
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6309
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6310
0
                                     << instance_id_;
6311
0
                    } else {
6312
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6313
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6314
0
                                           num_recycled, start_time);
6315
0
                    }
6316
0
                },
6317
400
                0);
6318
400
        if (ret == 0) return 0;
6319
        // Submit task failed, delete rowset data in current thread
6320
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6321
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6322
0
            return -1;
6323
0
        }
6324
0
        orphan_rowset_keys.push_back(std::move(key));
6325
0
        return 0;
6326
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_lSA_
Line
Count
Source
6289
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6290
        // Try to delete rowset data in background thread
6291
400
        int ret = worker_pool->submit_with_timeout(
6292
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6293
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6294
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6295
400
                        return;
6296
400
                    }
6297
                    // The async recycled rowsets are staled format or has not been used,
6298
                    // so we don't need to check the rowset ref count key.
6299
400
                    std::vector<std::string> keys;
6300
400
                    {
6301
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6302
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6303
400
                        if (async_recycled_rowset_keys.size() > 100) {
6304
400
                            keys.swap(async_recycled_rowset_keys);
6305
400
                        }
6306
400
                    }
6307
400
                    if (keys.empty()) return;
6308
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6309
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6310
400
                                     << instance_id_;
6311
400
                    } else {
6312
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6313
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6314
400
                                           num_recycled, start_time);
6315
400
                    }
6316
400
                },
6317
400
                0);
6318
400
        if (ret == 0) return 0;
6319
        // Submit task failed, delete rowset data in current thread
6320
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6321
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6322
0
            return -1;
6323
0
        }
6324
0
        orphan_rowset_keys.push_back(std::move(key));
6325
0
        return 0;
6326
0
    };
6327
6328
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6329
6330
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6331
2.01k
        ++num_scanned;
6332
2.01k
        total_rowset_key_size += k.size();
6333
2.01k
        total_rowset_value_size += v.size();
6334
2.01k
        RecycleRowsetPB rowset;
6335
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6336
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6337
0
            return -1;
6338
0
        }
6339
6340
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6341
6342
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6343
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6344
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6345
2.01k
        int64_t current_time = ::time(nullptr);
6346
2.01k
        if (current_time < final_expiration) { // not expired
6347
0
            return 0;
6348
0
        }
6349
2.01k
        ++num_expired;
6350
2.01k
        expired_rowset_size += v.size();
6351
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6352
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6353
                // in old version, keep this key-value pair and it needs to be checked manually
6354
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6355
0
                return -1;
6356
0
            }
6357
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6358
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6359
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6360
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6361
0
                orphan_rowset_keys.emplace_back(k);
6362
0
                return -1;
6363
0
            }
6364
            // decode rowset_id
6365
0
            auto k1 = k;
6366
0
            k1.remove_prefix(1);
6367
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6368
0
            decode_key(&k1, &out);
6369
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6370
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6371
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6372
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6373
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6374
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6375
0
                return -1;
6376
0
            }
6377
0
            return 0;
6378
0
        }
6379
        // TODO(plat1ko): check rowset not referenced
6380
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6381
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6382
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6383
0
                LOG_INFO("recycle rowset that has empty resource id");
6384
0
            } else {
6385
                // other situations, keep this key-value pair and it needs to be checked manually
6386
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6387
0
                return -1;
6388
0
            }
6389
0
        }
6390
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6391
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6392
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6393
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6394
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6395
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6396
2.01k
                  << " rowset_meta_size=" << v.size()
6397
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6398
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6399
            // unable to calculate file path, can only be deleted by rowset id prefix
6400
400
            num_prepare += 1;
6401
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6402
400
                                             rowset_meta->tablet_id(),
6403
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6404
0
                return -1;
6405
0
            }
6406
1.61k
        } else {
6407
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6408
1.61k
            worker_pool->submit(
6409
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6410
                        // The load & compact rowset keys are recycled during recycling operation logs.
6411
1.61k
                        RowsetDeleteTask task;
6412
1.61k
                        task.rowset_meta = rowset_meta;
6413
1.61k
                        task.recycle_rowset_key = k;
6414
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6415
1.59k
                            return;
6416
1.59k
                        }
6417
14
                        num_compacted += is_compacted;
6418
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6419
14
                        if (rowset_meta.num_segments() == 0) {
6420
0
                            ++num_empty_rowset;
6421
0
                        }
6422
14
                    });
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlvE_clEv
Line
Count
Source
6409
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6410
                        // The load & compact rowset keys are recycled during recycling operation logs.
6411
1.61k
                        RowsetDeleteTask task;
6412
1.61k
                        task.rowset_meta = rowset_meta;
6413
1.61k
                        task.recycle_rowset_key = k;
6414
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6415
1.59k
                            return;
6416
1.59k
                        }
6417
14
                        num_compacted += is_compacted;
6418
14
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6419
14
                        if (rowset_meta.num_segments() == 0) {
6420
0
                            ++num_empty_rowset;
6421
0
                        }
6422
14
                    });
6423
1.61k
        }
6424
2.01k
        return 0;
6425
2.01k
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6330
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6331
2.01k
        ++num_scanned;
6332
2.01k
        total_rowset_key_size += k.size();
6333
2.01k
        total_rowset_value_size += v.size();
6334
2.01k
        RecycleRowsetPB rowset;
6335
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6336
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6337
0
            return -1;
6338
0
        }
6339
6340
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6341
6342
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6343
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6344
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6345
2.01k
        int64_t current_time = ::time(nullptr);
6346
2.01k
        if (current_time < final_expiration) { // not expired
6347
0
            return 0;
6348
0
        }
6349
2.01k
        ++num_expired;
6350
2.01k
        expired_rowset_size += v.size();
6351
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6352
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6353
                // in old version, keep this key-value pair and it needs to be checked manually
6354
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6355
0
                return -1;
6356
0
            }
6357
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6358
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6359
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6360
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6361
0
                orphan_rowset_keys.emplace_back(k);
6362
0
                return -1;
6363
0
            }
6364
            // decode rowset_id
6365
0
            auto k1 = k;
6366
0
            k1.remove_prefix(1);
6367
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6368
0
            decode_key(&k1, &out);
6369
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6370
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6371
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6372
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6373
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6374
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6375
0
                return -1;
6376
0
            }
6377
0
            return 0;
6378
0
        }
6379
        // TODO(plat1ko): check rowset not referenced
6380
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6381
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6382
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6383
0
                LOG_INFO("recycle rowset that has empty resource id");
6384
0
            } else {
6385
                // other situations, keep this key-value pair and it needs to be checked manually
6386
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6387
0
                return -1;
6388
0
            }
6389
0
        }
6390
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6391
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6392
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6393
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6394
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6395
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6396
2.01k
                  << " rowset_meta_size=" << v.size()
6397
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6398
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6399
            // unable to calculate file path, can only be deleted by rowset id prefix
6400
400
            num_prepare += 1;
6401
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6402
400
                                             rowset_meta->tablet_id(),
6403
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6404
0
                return -1;
6405
0
            }
6406
1.61k
        } else {
6407
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6408
1.61k
            worker_pool->submit(
6409
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6410
                        // The load & compact rowset keys are recycled during recycling operation logs.
6411
1.61k
                        RowsetDeleteTask task;
6412
1.61k
                        task.rowset_meta = rowset_meta;
6413
1.61k
                        task.recycle_rowset_key = k;
6414
1.61k
                        if (recycle_rowset_meta_and_data(task) != 0) {
6415
1.61k
                            return;
6416
1.61k
                        }
6417
1.61k
                        num_compacted += is_compacted;
6418
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6419
1.61k
                        if (rowset_meta.num_segments() == 0) {
6420
1.61k
                            ++num_empty_rowset;
6421
1.61k
                        }
6422
1.61k
                    });
6423
1.61k
        }
6424
2.01k
        return 0;
6425
2.01k
    };
6426
6427
11
    if (config::enable_recycler_stats_metrics) {
6428
0
        scan_and_statistics_rowsets();
6429
0
    }
6430
6431
11
    auto loop_done = [&]() -> int {
6432
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6433
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6434
0
        }
6435
6
        orphan_rowset_keys.clear();
6436
6
        return 0;
6437
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6431
6
    auto loop_done = [&]() -> int {
6432
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6433
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6434
0
        }
6435
6
        orphan_rowset_keys.clear();
6436
6
        return 0;
6437
6
    };
6438
6439
    // recycle_func and loop_done for scan and recycle
6440
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6441
11
                               std::move(loop_done));
6442
6443
11
    worker_pool->stop();
6444
6445
11
    if (!async_recycled_rowset_keys.empty()) {
6446
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6447
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6448
0
            return -1;
6449
0
        } else {
6450
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6451
0
        }
6452
0
    }
6453
6454
    // Report final metrics after all concurrent tasks completed
6455
11
    segment_metrics_context_.report();
6456
11
    metrics_context.report();
6457
6458
11
    return ret;
6459
11
}
6460
6461
1.61k
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task) {
6462
1.61k
    constexpr int MAX_RETRY = 10;
6463
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6464
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6465
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6466
1.61k
    std::string_view reference_instance_id = instance_id_;
6467
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6468
8
        reference_instance_id = rowset_meta.reference_instance_id();
6469
8
    }
6470
6471
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6472
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6473
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6474
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6475
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6476
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6477
1.61k
        std::unique_ptr<Transaction> txn;
6478
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6479
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6480
0
            LOG_WARNING("failed to create txn").tag("err", err);
6481
0
            return -1;
6482
0
        }
6483
6484
1.61k
        std::string rowset_ref_count_key =
6485
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6486
1.61k
        int64_t ref_count = 0;
6487
1.61k
        {
6488
1.61k
            std::string value;
6489
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6490
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6491
                // This is the old version rowset, we could recycle it directly.
6492
1.60k
                ref_count = 1;
6493
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6494
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6495
0
                return -1;
6496
10
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6497
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6498
0
                return -1;
6499
0
            }
6500
1.61k
        }
6501
6502
1.61k
        if (ref_count == 1) {
6503
            // It would not be added since it is recycling.
6504
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6505
1.60k
                LOG_WARNING("failed to delete rowset data");
6506
1.60k
                return -1;
6507
1.60k
            }
6508
6509
            // Reset the transaction to avoid timeout.
6510
10
            err = txn_kv_->create_txn(&txn);
6511
10
            if (err != TxnErrorCode::TXN_OK) {
6512
0
                LOG_WARNING("failed to create txn").tag("err", err);
6513
0
                return -1;
6514
0
            }
6515
10
            txn->remove(rowset_ref_count_key);
6516
10
            LOG_INFO("delete rowset data ref count key")
6517
10
                    .tag("txn_id", rowset_meta.txn_id())
6518
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6519
6520
10
            std::string dbm_start_key =
6521
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6522
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6523
10
                    {reference_instance_id, tablet_id, rowset_id,
6524
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6525
10
            txn->remove(dbm_start_key, dbm_end_key);
6526
10
            LOG_INFO("remove delete bitmap kv")
6527
10
                    .tag("begin", hex(dbm_start_key))
6528
10
                    .tag("end", hex(dbm_end_key));
6529
6530
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6531
10
                    {reference_instance_id, tablet_id, rowset_id});
6532
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6533
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6534
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6535
10
            LOG_INFO("remove versioned delete bitmap kv")
6536
10
                    .tag("begin", hex(versioned_dbm_start_key))
6537
10
                    .tag("end", hex(versioned_dbm_end_key));
6538
10
        } else {
6539
            // Decrease the rowset ref count.
6540
            //
6541
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6542
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6543
2
            txn->atomic_add(rowset_ref_count_key, -1);
6544
2
            LOG_INFO("decrease rowset data ref count")
6545
2
                    .tag("txn_id", rowset_meta.txn_id())
6546
2
                    .tag("ref_count", ref_count - 1)
6547
2
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6548
2
        }
6549
6550
12
        if (!task.versioned_rowset_key.empty()) {
6551
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6552
0
                                                          task.versionstamp);
6553
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6554
0
        }
6555
6556
12
        if (!task.non_versioned_rowset_key.empty()) {
6557
0
            txn->remove(task.non_versioned_rowset_key);
6558
0
            LOG_INFO("remove non versioned rowset key")
6559
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6560
0
        }
6561
6562
        // empty when recycle ref rowsets for deleted instance
6563
13
        if (!task.recycle_rowset_key.empty()) {
6564
13
            txn->remove(task.recycle_rowset_key);
6565
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6566
13
        }
6567
6568
12
        err = txn->commit();
6569
12
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6570
            // The rowset ref count key has been changed, we need to retry.
6571
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6572
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6573
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6574
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6575
0
            continue;
6576
12
        } else if (err != TxnErrorCode::TXN_OK) {
6577
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6578
0
            return -1;
6579
0
        }
6580
12
        LOG_INFO("recycle rowset meta and data success");
6581
12
        return 0;
6582
12
    }
6583
1
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6584
1
            .tag("tablet_id", tablet_id)
6585
1
            .tag("rowset_id", rowset_id)
6586
1
            .tag("retry", MAX_RETRY);
6587
1
    return -1;
6588
1.61k
}
6589
6590
37
int InstanceRecycler::recycle_tmp_rowsets() {
6591
37
    const std::string task_name = "recycle_tmp_rowsets";
6592
37
    int64_t num_scanned = 0;
6593
37
    int64_t num_expired = 0;
6594
37
    std::atomic_long num_recycled = 0;
6595
37
    size_t expired_rowset_size = 0;
6596
37
    size_t total_rowset_key_size = 0;
6597
37
    size_t total_rowset_value_size = 0;
6598
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6599
6600
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6601
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6602
37
    std::string tmp_rs_key0;
6603
37
    std::string tmp_rs_key1;
6604
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6605
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6606
6607
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6608
6609
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6610
37
    register_recycle_task(task_name, start_time);
6611
6612
37
    DORIS_CLOUD_DEFER {
6613
37
        unregister_recycle_task(task_name);
6614
37
        int64_t cost =
6615
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6616
37
        metrics_context.finish_report();
6617
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6618
37
                .tag("instance_id", instance_id_)
6619
37
                .tag("num_scanned", num_scanned)
6620
37
                .tag("num_expired", num_expired)
6621
37
                .tag("num_recycled", num_recycled)
6622
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6623
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6624
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6625
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6612
12
    DORIS_CLOUD_DEFER {
6613
12
        unregister_recycle_task(task_name);
6614
12
        int64_t cost =
6615
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6616
12
        metrics_context.finish_report();
6617
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6618
12
                .tag("instance_id", instance_id_)
6619
12
                .tag("num_scanned", num_scanned)
6620
12
                .tag("num_expired", num_expired)
6621
12
                .tag("num_recycled", num_recycled)
6622
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6623
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6624
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6625
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6612
25
    DORIS_CLOUD_DEFER {
6613
25
        unregister_recycle_task(task_name);
6614
25
        int64_t cost =
6615
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6616
25
        metrics_context.finish_report();
6617
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6618
25
                .tag("instance_id", instance_id_)
6619
25
                .tag("num_scanned", num_scanned)
6620
25
                .tag("num_expired", num_expired)
6621
25
                .tag("num_recycled", num_recycled)
6622
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6623
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6624
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6625
25
    };
6626
6627
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6628
37
    std::vector<std::string> tmp_rowset_keys;
6629
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6630
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6631
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6632
6633
    // rowset_id -> rowset_meta
6634
    // store tmp_rowset id and meta for statistics rs size when delete
6635
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6636
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6637
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6638
37
    worker_pool->start();
6639
6640
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6641
6642
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6643
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6644
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6645
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6646
53.2k
                                    std::string_view k, std::string_view v) -> int {
6647
53.2k
        ++num_scanned;
6648
53.2k
        total_rowset_key_size += k.size();
6649
53.2k
        total_rowset_value_size += v.size();
6650
53.2k
        doris::RowsetMetaCloudPB rowset;
6651
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6652
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6653
0
            return -1;
6654
0
        }
6655
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6656
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6657
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6658
0
                   << " txn_expiration=" << rowset.txn_expiration()
6659
0
                   << " rowset_creation_time=" << rowset.creation_time();
6660
53.2k
        int64_t current_time = ::time(nullptr);
6661
53.2k
        if (current_time < expiration) { // not expired
6662
0
            return 0;
6663
0
        }
6664
53.2k
        ++num_expired;
6665
53.2k
        expired_rowset_size += v.size();
6666
53.2k
        if (!rowset.has_resource_id()) {
6667
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6668
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6669
0
                return -1;
6670
0
            }
6671
            // might be a delete pred rowset
6672
0
            tmp_rowset_keys.emplace_back(k);
6673
0
            return 0;
6674
0
        }
6675
6676
        // TODO(plat1ko): check rowset not referenced
6677
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6678
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6679
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6680
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6681
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6682
53.2k
                  << " num_expired=" << num_expired
6683
53.2k
                  << " task_type=" << metrics_context.operation_type;
6684
6685
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6686
16
            if (need_mark_rowset_as_recycled(rowset)) {
6687
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6688
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6689
9
                             "at next turn, instance_id="
6690
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6691
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6692
9
                return 0;
6693
9
            }
6694
16
        }
6695
6696
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6697
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6698
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6699
261
                             "instance_id="
6700
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6701
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6702
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6703
261
                return 0;
6704
261
            }
6705
265
        }
6706
6707
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6708
        // Remove the rowset ref count key directly since it has not been used.
6709
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6710
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6711
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6712
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6713
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6714
6715
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6716
53.0k
        return 0;
6717
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6646
16
                                    std::string_view k, std::string_view v) -> int {
6647
16
        ++num_scanned;
6648
16
        total_rowset_key_size += k.size();
6649
16
        total_rowset_value_size += v.size();
6650
16
        doris::RowsetMetaCloudPB rowset;
6651
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6652
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6653
0
            return -1;
6654
0
        }
6655
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6656
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6657
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6658
0
                   << " txn_expiration=" << rowset.txn_expiration()
6659
0
                   << " rowset_creation_time=" << rowset.creation_time();
6660
16
        int64_t current_time = ::time(nullptr);
6661
16
        if (current_time < expiration) { // not expired
6662
0
            return 0;
6663
0
        }
6664
16
        ++num_expired;
6665
16
        expired_rowset_size += v.size();
6666
16
        if (!rowset.has_resource_id()) {
6667
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6668
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6669
0
                return -1;
6670
0
            }
6671
            // might be a delete pred rowset
6672
0
            tmp_rowset_keys.emplace_back(k);
6673
0
            return 0;
6674
0
        }
6675
6676
        // TODO(plat1ko): check rowset not referenced
6677
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6678
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6679
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6680
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6681
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6682
16
                  << " num_expired=" << num_expired
6683
16
                  << " task_type=" << metrics_context.operation_type;
6684
6685
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6686
16
            if (need_mark_rowset_as_recycled(rowset)) {
6687
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6688
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6689
9
                             "at next turn, instance_id="
6690
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6691
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6692
9
                return 0;
6693
9
            }
6694
16
        }
6695
6696
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6697
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6698
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6699
3
                             "instance_id="
6700
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6701
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6702
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6703
3
                return 0;
6704
3
            }
6705
7
        }
6706
6707
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6708
        // Remove the rowset ref count key directly since it has not been used.
6709
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6710
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6711
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6712
4
                  << "key=" << hex(rowset_ref_count_key);
6713
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6714
6715
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6716
4
        return 0;
6717
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6646
53.2k
                                    std::string_view k, std::string_view v) -> int {
6647
53.2k
        ++num_scanned;
6648
53.2k
        total_rowset_key_size += k.size();
6649
53.2k
        total_rowset_value_size += v.size();
6650
53.2k
        doris::RowsetMetaCloudPB rowset;
6651
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6652
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6653
0
            return -1;
6654
0
        }
6655
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6656
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6657
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6658
0
                   << " txn_expiration=" << rowset.txn_expiration()
6659
0
                   << " rowset_creation_time=" << rowset.creation_time();
6660
53.2k
        int64_t current_time = ::time(nullptr);
6661
53.2k
        if (current_time < expiration) { // not expired
6662
0
            return 0;
6663
0
        }
6664
53.2k
        ++num_expired;
6665
53.2k
        expired_rowset_size += v.size();
6666
53.2k
        if (!rowset.has_resource_id()) {
6667
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6668
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6669
0
                return -1;
6670
0
            }
6671
            // might be a delete pred rowset
6672
0
            tmp_rowset_keys.emplace_back(k);
6673
0
            return 0;
6674
0
        }
6675
6676
        // TODO(plat1ko): check rowset not referenced
6677
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6678
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6679
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6680
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6681
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6682
53.2k
                  << " num_expired=" << num_expired
6683
53.2k
                  << " task_type=" << metrics_context.operation_type;
6684
6685
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6686
0
            if (need_mark_rowset_as_recycled(rowset)) {
6687
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6688
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6689
0
                             "at next turn, instance_id="
6690
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6691
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6692
0
                return 0;
6693
0
            }
6694
0
        }
6695
6696
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6697
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6698
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6699
258
                             "instance_id="
6700
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6701
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6702
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6703
258
                return 0;
6704
258
            }
6705
258
        }
6706
6707
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6708
        // Remove the rowset ref count key directly since it has not been used.
6709
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6710
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6711
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6712
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6713
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6714
6715
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6716
53.0k
        return 0;
6717
53.2k
    };
6718
6719
37
    auto loop_done = [&]() -> int {
6720
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6721
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6722
24
        std::vector<std::string> mark_keys_to_process;
6723
24
        std::vector<std::string> abort_keys_to_process;
6724
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6725
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6726
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6727
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6728
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6729
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6730
24
        if (!mark_keys_to_process.empty()) {
6731
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6732
7
                    *worker_pool, std::move(mark_keys_to_process));
6733
7
        }
6734
24
        if (!abort_keys_to_process.empty()) {
6735
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6736
5
                                           &num_recycled, &metrics_context);
6737
5
        }
6738
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6739
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6740
24
                             tmp_rowset_ref_count_keys_to_delete =
6741
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6742
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6743
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6744
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6745
24
                                   metrics_context) != 0) {
6746
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6747
2
                return;
6748
2
            }
6749
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6750
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6751
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6752
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6753
0
                                 << rs.ShortDebugString();
6754
0
                    return;
6755
0
                }
6756
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6757
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6758
0
                                 << rs.ShortDebugString();
6759
0
                    return;
6760
0
                }
6761
51.0k
            }
6762
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6763
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6764
0
                return;
6765
0
            }
6766
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6767
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6768
0
                return;
6769
0
            }
6770
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6771
22
            return;
6772
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6743
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6744
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6745
12
                                   metrics_context) != 0) {
6746
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6747
0
                return;
6748
0
            }
6749
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6750
4
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6751
4
                                                       rs.rowset_id_v2()) != 0) {
6752
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6753
0
                                 << rs.ShortDebugString();
6754
0
                    return;
6755
0
                }
6756
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6757
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6758
0
                                 << rs.ShortDebugString();
6759
0
                    return;
6760
0
                }
6761
4
            }
6762
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6763
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6764
0
                return;
6765
0
            }
6766
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6767
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6768
0
                return;
6769
0
            }
6770
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6771
12
            return;
6772
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE_clEv
Line
Count
Source
6743
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6744
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6745
12
                                   metrics_context) != 0) {
6746
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6747
2
                return;
6748
2
            }
6749
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6750
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6751
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6752
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6753
0
                                 << rs.ShortDebugString();
6754
0
                    return;
6755
0
                }
6756
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6757
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6758
0
                                 << rs.ShortDebugString();
6759
0
                    return;
6760
0
                }
6761
51.0k
            }
6762
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6763
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6764
0
                return;
6765
0
            }
6766
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6767
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6768
0
                return;
6769
0
            }
6770
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6771
10
            return;
6772
10
        });
6773
24
        return 0;
6774
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6719
12
    auto loop_done = [&]() -> int {
6720
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6721
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6722
12
        std::vector<std::string> mark_keys_to_process;
6723
12
        std::vector<std::string> abort_keys_to_process;
6724
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6725
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6726
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6727
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6728
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6729
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6730
12
        if (!mark_keys_to_process.empty()) {
6731
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6732
7
                    *worker_pool, std::move(mark_keys_to_process));
6733
7
        }
6734
12
        if (!abort_keys_to_process.empty()) {
6735
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6736
3
                                           &num_recycled, &metrics_context);
6737
3
        }
6738
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6739
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6740
12
                             tmp_rowset_ref_count_keys_to_delete =
6741
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6742
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6743
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6744
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6745
12
                                   metrics_context) != 0) {
6746
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6747
12
                return;
6748
12
            }
6749
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6750
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6751
12
                                                       rs.rowset_id_v2()) != 0) {
6752
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6753
12
                                 << rs.ShortDebugString();
6754
12
                    return;
6755
12
                }
6756
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6757
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6758
12
                                 << rs.ShortDebugString();
6759
12
                    return;
6760
12
                }
6761
12
            }
6762
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6763
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6764
12
                return;
6765
12
            }
6766
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6767
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6768
12
                return;
6769
12
            }
6770
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6771
12
            return;
6772
12
        });
6773
12
        return 0;
6774
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6719
12
    auto loop_done = [&]() -> int {
6720
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6721
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6722
12
        std::vector<std::string> mark_keys_to_process;
6723
12
        std::vector<std::string> abort_keys_to_process;
6724
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6725
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6726
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6727
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6728
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6729
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6730
12
        if (!mark_keys_to_process.empty()) {
6731
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6732
0
                    *worker_pool, std::move(mark_keys_to_process));
6733
0
        }
6734
12
        if (!abort_keys_to_process.empty()) {
6735
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6736
2
                                           &num_recycled, &metrics_context);
6737
2
        }
6738
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6739
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6740
12
                             tmp_rowset_ref_count_keys_to_delete =
6741
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6742
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6743
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6744
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6745
12
                                   metrics_context) != 0) {
6746
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6747
12
                return;
6748
12
            }
6749
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6750
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6751
12
                                                       rs.rowset_id_v2()) != 0) {
6752
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6753
12
                                 << rs.ShortDebugString();
6754
12
                    return;
6755
12
                }
6756
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6757
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6758
12
                                 << rs.ShortDebugString();
6759
12
                    return;
6760
12
                }
6761
12
            }
6762
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6763
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6764
12
                return;
6765
12
            }
6766
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6767
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6768
12
                return;
6769
12
            }
6770
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6771
12
            return;
6772
12
        });
6773
12
        return 0;
6774
12
    };
6775
6776
37
    if (config::enable_recycler_stats_metrics) {
6777
0
        scan_and_statistics_tmp_rowsets();
6778
0
    }
6779
    // recycle_func and loop_done for scan and recycle
6780
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6781
37
                               std::move(loop_done));
6782
6783
37
    worker_pool->stop();
6784
6785
    // Report final metrics after all concurrent tasks completed
6786
37
    segment_metrics_context_.report();
6787
37
    metrics_context.report();
6788
6789
37
    return ret;
6790
37
}
6791
6792
int InstanceRecycler::scan_and_recycle(
6793
        std::string begin, std::string_view end,
6794
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6795
329
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6796
329
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6797
329
    int ret = 0;
6798
329
    int64_t cnt = 0;
6799
329
    int get_range_retried = 0;
6800
329
    std::string err;
6801
329
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6802
329
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6803
329
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6804
329
                  << " ret=" << ret << " err=" << err;
6805
329
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6801
39
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6802
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6803
39
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6804
39
                  << " ret=" << ret << " err=" << err;
6805
39
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6801
290
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6802
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6803
290
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6804
290
                  << " ret=" << ret << " err=" << err;
6805
290
    };
6806
6807
329
    std::unique_ptr<RangeGetIterator> it;
6808
539
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6809
361
        if (get_range_retried > 1000) {
6810
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6811
0
            ret = -3;
6812
0
            return ret;
6813
0
        }
6814
361
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6815
361
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6816
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6817
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6818
0
                         << " get_range_retried=" << get_range_retried;
6819
0
            ++get_range_retried;
6820
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6821
0
            continue; // try again
6822
0
        }
6823
361
        if (!it->has_next()) {
6824
151
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6825
151
            break; // scan finished
6826
151
        }
6827
210
        bool begin_updated = false;
6828
210
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6829
210
                  << ") iterator->size()=" << it->size();
6830
138k
        while (it->has_next()) {
6831
138k
            ++cnt;
6832
            // recycle corresponding resources
6833
138k
            auto [k, v] = it->next();
6834
138k
            if (!it->has_next()) {
6835
210
                begin = k;
6836
210
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6837
210
            }
6838
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6839
138k
            if (recycle_func(k, v) != 0) {
6840
4.00k
                err = "recycle_func error";
6841
4.00k
                ret = -1;
6842
4.00k
            }
6843
138k
            if (next_begin_getter) {
6844
0
                std::string next_begin;
6845
0
                if (next_begin_getter(&next_begin)) {
6846
0
                    if (next_begin > k) {
6847
0
                        begin = std::move(next_begin);
6848
0
                        begin_updated = true;
6849
0
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6850
0
                                   << " after key=" << hex(k);
6851
0
                        break;
6852
0
                    }
6853
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6854
0
                            .tag("next_begin", hex(next_begin))
6855
0
                            .tag("current_key", hex(k));
6856
0
                }
6857
0
            }
6858
138k
        }
6859
210
        if (!begin_updated) {
6860
210
            begin.push_back('\x00'); // Update to next smallest key for iteration
6861
210
        } else {
6862
0
            it.reset();
6863
0
        }
6864
6865
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6866
        // if we want to continue scanning, the recycle_func should not return non-zero
6867
210
        if (loop_done && loop_done() != 0) {
6868
8
            err = "loop_done error";
6869
8
            ret = -1;
6870
8
        }
6871
210
    }
6872
329
    return ret;
6873
329
}
6874
6875
19
int InstanceRecycler::abort_timeout_txn() {
6876
19
    const std::string task_name = "abort_timeout_txn";
6877
19
    int64_t num_scanned = 0;
6878
19
    int64_t num_timeout = 0;
6879
19
    int64_t num_abort = 0;
6880
19
    int64_t num_advance = 0;
6881
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6882
6883
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6884
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6885
19
    std::string begin_txn_running_key;
6886
19
    std::string end_txn_running_key;
6887
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6888
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6889
6890
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6891
6892
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6893
19
    register_recycle_task(task_name, start_time);
6894
6895
19
    DORIS_CLOUD_DEFER {
6896
19
        unregister_recycle_task(task_name);
6897
19
        int64_t cost =
6898
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6899
19
        metrics_context.finish_report();
6900
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6901
19
                .tag("instance_id", instance_id_)
6902
19
                .tag("num_scanned", num_scanned)
6903
19
                .tag("num_timeout", num_timeout)
6904
19
                .tag("num_abort", num_abort)
6905
19
                .tag("num_advance", num_advance);
6906
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6895
3
    DORIS_CLOUD_DEFER {
6896
3
        unregister_recycle_task(task_name);
6897
3
        int64_t cost =
6898
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6899
3
        metrics_context.finish_report();
6900
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6901
3
                .tag("instance_id", instance_id_)
6902
3
                .tag("num_scanned", num_scanned)
6903
3
                .tag("num_timeout", num_timeout)
6904
3
                .tag("num_abort", num_abort)
6905
3
                .tag("num_advance", num_advance);
6906
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6895
16
    DORIS_CLOUD_DEFER {
6896
16
        unregister_recycle_task(task_name);
6897
16
        int64_t cost =
6898
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6899
16
        metrics_context.finish_report();
6900
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6901
16
                .tag("instance_id", instance_id_)
6902
16
                .tag("num_scanned", num_scanned)
6903
16
                .tag("num_timeout", num_timeout)
6904
16
                .tag("num_abort", num_abort)
6905
16
                .tag("num_advance", num_advance);
6906
16
    };
6907
6908
19
    int64_t current_time =
6909
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6910
6911
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6912
19
                                  &current_time, &metrics_context,
6913
19
                                  this](std::string_view k, std::string_view v) -> int {
6914
9
        ++num_scanned;
6915
6916
9
        std::unique_ptr<Transaction> txn;
6917
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6918
9
        if (err != TxnErrorCode::TXN_OK) {
6919
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6920
0
            return -1;
6921
0
        }
6922
9
        std::string_view k1 = k;
6923
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6924
9
        k1.remove_prefix(1); // Remove key space
6925
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6926
9
        if (decode_key(&k1, &out) != 0) {
6927
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6928
0
            return -1;
6929
0
        }
6930
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6931
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6932
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6933
        // Update txn_info
6934
9
        std::string txn_inf_key, txn_inf_val;
6935
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6936
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6937
9
        if (err != TxnErrorCode::TXN_OK) {
6938
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6939
0
            return -1;
6940
0
        }
6941
9
        TxnInfoPB txn_info;
6942
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6943
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6944
0
            return -1;
6945
0
        }
6946
6947
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6948
3
            txn.reset();
6949
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6950
3
            std::shared_ptr<TxnLazyCommitTask> task =
6951
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6952
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6953
3
            if (ret.first != MetaServiceCode::OK) {
6954
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6955
0
                             << "msg=" << ret.second;
6956
0
                return -1;
6957
0
            }
6958
3
            ++num_advance;
6959
3
            return 0;
6960
6
        } else {
6961
6
            TxnRunningPB txn_running_pb;
6962
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6963
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6964
0
                return -1;
6965
0
            }
6966
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6967
4
                return 0;
6968
4
            }
6969
2
            ++num_timeout;
6970
6971
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6972
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6973
2
            txn_info.set_finish_time(current_time);
6974
2
            txn_info.set_reason("timeout");
6975
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6976
2
            txn_inf_val.clear();
6977
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6978
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6979
0
                return -1;
6980
0
            }
6981
2
            txn->put(txn_inf_key, txn_inf_val);
6982
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6983
            // Put recycle txn key
6984
2
            std::string recyc_txn_key, recyc_txn_val;
6985
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6986
2
            RecycleTxnPB recycle_txn_pb;
6987
2
            recycle_txn_pb.set_creation_time(current_time);
6988
2
            recycle_txn_pb.set_label(txn_info.label());
6989
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6990
0
                LOG_WARNING("failed to serialize txn recycle info")
6991
0
                        .tag("key", hex(k))
6992
0
                        .tag("db_id", db_id)
6993
0
                        .tag("txn_id", txn_id);
6994
0
                return -1;
6995
0
            }
6996
2
            txn->put(recyc_txn_key, recyc_txn_val);
6997
            // Remove txn running key
6998
2
            txn->remove(k);
6999
2
            err = txn->commit();
7000
2
            if (err != TxnErrorCode::TXN_OK) {
7001
0
                LOG_WARNING("failed to commit txn err={}", err)
7002
0
                        .tag("key", hex(k))
7003
0
                        .tag("db_id", db_id)
7004
0
                        .tag("txn_id", txn_id);
7005
0
                return -1;
7006
0
            }
7007
2
            metrics_context.total_recycled_num = ++num_abort;
7008
2
            metrics_context.report();
7009
2
        }
7010
7011
2
        return 0;
7012
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6913
3
                                  this](std::string_view k, std::string_view v) -> int {
6914
3
        ++num_scanned;
6915
6916
3
        std::unique_ptr<Transaction> txn;
6917
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6918
3
        if (err != TxnErrorCode::TXN_OK) {
6919
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6920
0
            return -1;
6921
0
        }
6922
3
        std::string_view k1 = k;
6923
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6924
3
        k1.remove_prefix(1); // Remove key space
6925
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6926
3
        if (decode_key(&k1, &out) != 0) {
6927
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6928
0
            return -1;
6929
0
        }
6930
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6931
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6932
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6933
        // Update txn_info
6934
3
        std::string txn_inf_key, txn_inf_val;
6935
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6936
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6937
3
        if (err != TxnErrorCode::TXN_OK) {
6938
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6939
0
            return -1;
6940
0
        }
6941
3
        TxnInfoPB txn_info;
6942
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6943
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6944
0
            return -1;
6945
0
        }
6946
6947
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6948
3
            txn.reset();
6949
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6950
3
            std::shared_ptr<TxnLazyCommitTask> task =
6951
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6952
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6953
3
            if (ret.first != MetaServiceCode::OK) {
6954
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6955
0
                             << "msg=" << ret.second;
6956
0
                return -1;
6957
0
            }
6958
3
            ++num_advance;
6959
3
            return 0;
6960
3
        } else {
6961
0
            TxnRunningPB txn_running_pb;
6962
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6963
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6964
0
                return -1;
6965
0
            }
6966
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6967
0
                return 0;
6968
0
            }
6969
0
            ++num_timeout;
6970
6971
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6972
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6973
0
            txn_info.set_finish_time(current_time);
6974
0
            txn_info.set_reason("timeout");
6975
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6976
0
            txn_inf_val.clear();
6977
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6978
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6979
0
                return -1;
6980
0
            }
6981
0
            txn->put(txn_inf_key, txn_inf_val);
6982
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6983
            // Put recycle txn key
6984
0
            std::string recyc_txn_key, recyc_txn_val;
6985
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6986
0
            RecycleTxnPB recycle_txn_pb;
6987
0
            recycle_txn_pb.set_creation_time(current_time);
6988
0
            recycle_txn_pb.set_label(txn_info.label());
6989
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6990
0
                LOG_WARNING("failed to serialize txn recycle info")
6991
0
                        .tag("key", hex(k))
6992
0
                        .tag("db_id", db_id)
6993
0
                        .tag("txn_id", txn_id);
6994
0
                return -1;
6995
0
            }
6996
0
            txn->put(recyc_txn_key, recyc_txn_val);
6997
            // Remove txn running key
6998
0
            txn->remove(k);
6999
0
            err = txn->commit();
7000
0
            if (err != TxnErrorCode::TXN_OK) {
7001
0
                LOG_WARNING("failed to commit txn err={}", err)
7002
0
                        .tag("key", hex(k))
7003
0
                        .tag("db_id", db_id)
7004
0
                        .tag("txn_id", txn_id);
7005
0
                return -1;
7006
0
            }
7007
0
            metrics_context.total_recycled_num = ++num_abort;
7008
0
            metrics_context.report();
7009
0
        }
7010
7011
0
        return 0;
7012
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6913
6
                                  this](std::string_view k, std::string_view v) -> int {
6914
6
        ++num_scanned;
6915
6916
6
        std::unique_ptr<Transaction> txn;
6917
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6918
6
        if (err != TxnErrorCode::TXN_OK) {
6919
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6920
0
            return -1;
6921
0
        }
6922
6
        std::string_view k1 = k;
6923
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6924
6
        k1.remove_prefix(1); // Remove key space
6925
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6926
6
        if (decode_key(&k1, &out) != 0) {
6927
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6928
0
            return -1;
6929
0
        }
6930
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6931
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6932
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6933
        // Update txn_info
6934
6
        std::string txn_inf_key, txn_inf_val;
6935
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6936
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6937
6
        if (err != TxnErrorCode::TXN_OK) {
6938
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6939
0
            return -1;
6940
0
        }
6941
6
        TxnInfoPB txn_info;
6942
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6943
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6944
0
            return -1;
6945
0
        }
6946
6947
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6948
0
            txn.reset();
6949
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6950
0
            std::shared_ptr<TxnLazyCommitTask> task =
6951
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6952
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6953
0
            if (ret.first != MetaServiceCode::OK) {
6954
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6955
0
                             << "msg=" << ret.second;
6956
0
                return -1;
6957
0
            }
6958
0
            ++num_advance;
6959
0
            return 0;
6960
6
        } else {
6961
6
            TxnRunningPB txn_running_pb;
6962
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6963
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6964
0
                return -1;
6965
0
            }
6966
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6967
4
                return 0;
6968
4
            }
6969
2
            ++num_timeout;
6970
6971
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6972
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6973
2
            txn_info.set_finish_time(current_time);
6974
2
            txn_info.set_reason("timeout");
6975
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6976
2
            txn_inf_val.clear();
6977
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6978
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6979
0
                return -1;
6980
0
            }
6981
2
            txn->put(txn_inf_key, txn_inf_val);
6982
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6983
            // Put recycle txn key
6984
2
            std::string recyc_txn_key, recyc_txn_val;
6985
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6986
2
            RecycleTxnPB recycle_txn_pb;
6987
2
            recycle_txn_pb.set_creation_time(current_time);
6988
2
            recycle_txn_pb.set_label(txn_info.label());
6989
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6990
0
                LOG_WARNING("failed to serialize txn recycle info")
6991
0
                        .tag("key", hex(k))
6992
0
                        .tag("db_id", db_id)
6993
0
                        .tag("txn_id", txn_id);
6994
0
                return -1;
6995
0
            }
6996
2
            txn->put(recyc_txn_key, recyc_txn_val);
6997
            // Remove txn running key
6998
2
            txn->remove(k);
6999
2
            err = txn->commit();
7000
2
            if (err != TxnErrorCode::TXN_OK) {
7001
0
                LOG_WARNING("failed to commit txn err={}", err)
7002
0
                        .tag("key", hex(k))
7003
0
                        .tag("db_id", db_id)
7004
0
                        .tag("txn_id", txn_id);
7005
0
                return -1;
7006
0
            }
7007
2
            metrics_context.total_recycled_num = ++num_abort;
7008
2
            metrics_context.report();
7009
2
        }
7010
7011
2
        return 0;
7012
6
    };
7013
7014
19
    if (config::enable_recycler_stats_metrics) {
7015
0
        scan_and_statistics_abort_timeout_txn();
7016
0
    }
7017
    // recycle_func and loop_done for scan and recycle
7018
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
7019
19
                            std::move(handle_txn_running_kv));
7020
19
}
7021
7022
22
int InstanceRecycler::recycle_expired_txn_label() {
7023
22
    const std::string task_name = "recycle_expired_txn_label";
7024
22
    int64_t num_scanned = 0;
7025
22
    int64_t num_expired = 0;
7026
22
    std::atomic_long num_recycled = 0;
7027
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7028
22
    int ret = 0;
7029
7030
22
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
7031
22
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
7032
22
    std::string begin_recycle_txn_key;
7033
22
    std::string end_recycle_txn_key;
7034
22
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
7035
22
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
7036
22
    std::unordered_map<std::string, std::vector<std::string>> recycle_txn_keys_by_label;
7037
7038
22
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
7039
7040
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7041
22
    register_recycle_task(task_name, start_time);
7042
22
    DORIS_CLOUD_DEFER {
7043
22
        unregister_recycle_task(task_name);
7044
22
        int64_t cost =
7045
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7046
22
        metrics_context.finish_report();
7047
22
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7048
22
                .tag("instance_id", instance_id_)
7049
22
                .tag("num_scanned", num_scanned)
7050
22
                .tag("num_expired", num_expired)
7051
22
                .tag("num_recycled", num_recycled);
7052
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
7042
1
    DORIS_CLOUD_DEFER {
7043
1
        unregister_recycle_task(task_name);
7044
1
        int64_t cost =
7045
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7046
1
        metrics_context.finish_report();
7047
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7048
1
                .tag("instance_id", instance_id_)
7049
1
                .tag("num_scanned", num_scanned)
7050
1
                .tag("num_expired", num_expired)
7051
1
                .tag("num_recycled", num_recycled);
7052
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
7042
21
    DORIS_CLOUD_DEFER {
7043
21
        unregister_recycle_task(task_name);
7044
21
        int64_t cost =
7045
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7046
21
        metrics_context.finish_report();
7047
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
7048
21
                .tag("instance_id", instance_id_)
7049
21
                .tag("num_scanned", num_scanned)
7050
21
                .tag("num_expired", num_expired)
7051
21
                .tag("num_recycled", num_recycled);
7052
21
    };
7053
7054
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7055
7056
22
    SyncExecutor<int> concurrent_delete_executor(
7057
22
            _thread_pool_group.s3_producer_pool,
7058
22
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
7059
38.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7059
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
7059
38.0k
            [](const int& ret) { return ret != 0; });
7060
7061
22
    int64_t current_time_ms =
7062
22
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7063
7064
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7065
50.0k
        ++num_scanned;
7066
50.0k
        RecycleTxnPB recycle_txn_pb;
7067
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7068
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7069
0
            return -1;
7070
0
        }
7071
50.0k
        if ((config::force_immediate_recycle) ||
7072
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7073
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7074
50.0k
             current_time_ms)) {
7075
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7076
38.0k
            num_expired++;
7077
7078
38.0k
            std::string_view k1 = k;
7079
38.0k
            k1.remove_prefix(1); // Remove key space
7080
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7081
38.0k
            if (decode_key(&k1, &out) != 0) {
7082
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7083
0
                return -1;
7084
0
            }
7085
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7086
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7087
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7088
38.0k
        }
7089
50.0k
        return 0;
7090
50.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7064
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7065
1
        ++num_scanned;
7066
1
        RecycleTxnPB recycle_txn_pb;
7067
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7068
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7069
0
            return -1;
7070
0
        }
7071
1
        if ((config::force_immediate_recycle) ||
7072
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7073
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7074
1
             current_time_ms)) {
7075
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7076
1
            num_expired++;
7077
7078
1
            std::string_view k1 = k;
7079
1
            k1.remove_prefix(1); // Remove key space
7080
1
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7081
1
            if (decode_key(&k1, &out) != 0) {
7082
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7083
0
                return -1;
7084
0
            }
7085
1
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7086
1
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7087
1
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7088
1
        }
7089
1
        return 0;
7090
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7064
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
7065
50.0k
        ++num_scanned;
7066
50.0k
        RecycleTxnPB recycle_txn_pb;
7067
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
7068
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
7069
0
            return -1;
7070
0
        }
7071
50.0k
        if ((config::force_immediate_recycle) ||
7072
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
7073
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
7074
50.0k
             current_time_ms)) {
7075
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
7076
38.0k
            num_expired++;
7077
7078
38.0k
            std::string_view k1 = k;
7079
38.0k
            k1.remove_prefix(1); // Remove key space
7080
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7081
38.0k
            if (decode_key(&k1, &out) != 0) {
7082
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7083
0
                return -1;
7084
0
            }
7085
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7086
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7087
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7088
38.0k
        }
7089
50.0k
        return 0;
7090
50.0k
    };
7091
7092
    // int 0 for success, 1 for conflict, -1 for error
7093
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7094
38.0k
        std::string_view k1 = k;
7095
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7096
38.0k
        k1.remove_prefix(1); // Remove key space
7097
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7098
38.0k
        int ret = decode_key(&k1, &out);
7099
38.0k
        if (ret != 0) {
7100
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7101
0
            return -1;
7102
0
        }
7103
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7104
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7105
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7106
38.0k
        std::unique_ptr<Transaction> txn;
7107
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7108
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7109
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7110
0
            return -1;
7111
0
        }
7112
        // Remove txn index kv
7113
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7114
38.0k
        txn->remove(index_key);
7115
        // Remove txn info kv
7116
38.0k
        std::string info_key, info_val;
7117
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7118
38.0k
        err = txn->get(info_key, &info_val);
7119
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7120
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7121
0
            return -1;
7122
0
        }
7123
38.0k
        TxnInfoPB txn_info;
7124
38.0k
        if (!txn_info.ParseFromString(info_val)) {
7125
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7126
0
            return -1;
7127
0
        }
7128
38.0k
        txn->remove(info_key);
7129
        // Remove sub txn index kvs
7130
38.0k
        std::vector<std::string> sub_txn_index_keys;
7131
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7132
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7133
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7134
38.0k
        }
7135
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7136
38.0k
            txn->remove(sub_txn_index_key);
7137
38.0k
        }
7138
        // Update txn label
7139
38.0k
        std::string label_key, label_val;
7140
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7141
38.0k
        err = txn->get(label_key, &label_val);
7142
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7143
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7144
0
                         << " err=" << err;
7145
0
            return -1;
7146
0
        }
7147
38.0k
        TxnLabelPB txn_label;
7148
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7149
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7150
0
            return -1;
7151
0
        }
7152
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7153
38.0k
        if (it != txn_label.txn_ids().end()) {
7154
38.0k
            txn_label.mutable_txn_ids()->erase(it);
7155
38.0k
        }
7156
38.0k
        if (txn_label.txn_ids().empty()) {
7157
38.0k
            txn->remove(label_key);
7158
38.0k
            TEST_SYNC_POINT_CALLBACK(
7159
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7160
38.0k
        } else {
7161
11
            if (!txn_label.SerializeToString(&label_val)) {
7162
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7163
0
                return -1;
7164
0
            }
7165
11
            TEST_SYNC_POINT_CALLBACK(
7166
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7167
11
            txn->atomic_set_ver_value(label_key, label_val);
7168
11
            TEST_SYNC_POINT_CALLBACK(
7169
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7170
11
        }
7171
        // Remove recycle txn kv
7172
38.0k
        txn->remove(k);
7173
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7174
38.0k
        err = txn->commit();
7175
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7176
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
7177
4
                TEST_SYNC_POINT_CALLBACK(
7178
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7179
                // log the txn_id and label
7180
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7181
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7182
4
                             << " txn_label=" << txn_info.label();
7183
4
                return 1;
7184
4
            }
7185
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7186
0
            return -1;
7187
4
        }
7188
38.0k
        ++num_recycled;
7189
7190
38.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7191
38.0k
        return 0;
7192
38.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7093
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7094
1
        std::string_view k1 = k;
7095
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7096
1
        k1.remove_prefix(1); // Remove key space
7097
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7098
1
        int ret = decode_key(&k1, &out);
7099
1
        if (ret != 0) {
7100
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7101
0
            return -1;
7102
0
        }
7103
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7104
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7105
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7106
1
        std::unique_ptr<Transaction> txn;
7107
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7108
1
        if (err != TxnErrorCode::TXN_OK) {
7109
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7110
0
            return -1;
7111
0
        }
7112
        // Remove txn index kv
7113
1
        auto index_key = txn_index_key({instance_id_, txn_id});
7114
1
        txn->remove(index_key);
7115
        // Remove txn info kv
7116
1
        std::string info_key, info_val;
7117
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7118
1
        err = txn->get(info_key, &info_val);
7119
1
        if (err != TxnErrorCode::TXN_OK) {
7120
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7121
0
            return -1;
7122
0
        }
7123
1
        TxnInfoPB txn_info;
7124
1
        if (!txn_info.ParseFromString(info_val)) {
7125
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7126
0
            return -1;
7127
0
        }
7128
1
        txn->remove(info_key);
7129
        // Remove sub txn index kvs
7130
1
        std::vector<std::string> sub_txn_index_keys;
7131
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7132
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7133
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
7134
0
        }
7135
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7136
0
            txn->remove(sub_txn_index_key);
7137
0
        }
7138
        // Update txn label
7139
1
        std::string label_key, label_val;
7140
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7141
1
        err = txn->get(label_key, &label_val);
7142
1
        if (err != TxnErrorCode::TXN_OK) {
7143
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7144
0
                         << " err=" << err;
7145
0
            return -1;
7146
0
        }
7147
1
        TxnLabelPB txn_label;
7148
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7149
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7150
0
            return -1;
7151
0
        }
7152
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7153
1
        if (it != txn_label.txn_ids().end()) {
7154
1
            txn_label.mutable_txn_ids()->erase(it);
7155
1
        }
7156
1
        if (txn_label.txn_ids().empty()) {
7157
1
            txn->remove(label_key);
7158
1
            TEST_SYNC_POINT_CALLBACK(
7159
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7160
1
        } else {
7161
0
            if (!txn_label.SerializeToString(&label_val)) {
7162
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7163
0
                return -1;
7164
0
            }
7165
0
            TEST_SYNC_POINT_CALLBACK(
7166
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7167
0
            txn->atomic_set_ver_value(label_key, label_val);
7168
0
            TEST_SYNC_POINT_CALLBACK(
7169
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7170
0
        }
7171
        // Remove recycle txn kv
7172
1
        txn->remove(k);
7173
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7174
1
        err = txn->commit();
7175
1
        if (err != TxnErrorCode::TXN_OK) {
7176
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
7177
0
                TEST_SYNC_POINT_CALLBACK(
7178
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7179
                // log the txn_id and label
7180
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7181
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7182
0
                             << " txn_label=" << txn_info.label();
7183
0
                return 1;
7184
0
            }
7185
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7186
0
            return -1;
7187
0
        }
7188
1
        ++num_recycled;
7189
7190
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7191
1
        return 0;
7192
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7093
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7094
38.0k
        std::string_view k1 = k;
7095
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7096
38.0k
        k1.remove_prefix(1); // Remove key space
7097
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7098
38.0k
        int ret = decode_key(&k1, &out);
7099
38.0k
        if (ret != 0) {
7100
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7101
0
            return -1;
7102
0
        }
7103
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7104
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7105
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7106
38.0k
        std::unique_ptr<Transaction> txn;
7107
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7108
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7109
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7110
0
            return -1;
7111
0
        }
7112
        // Remove txn index kv
7113
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7114
38.0k
        txn->remove(index_key);
7115
        // Remove txn info kv
7116
38.0k
        std::string info_key, info_val;
7117
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7118
38.0k
        err = txn->get(info_key, &info_val);
7119
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7120
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7121
0
            return -1;
7122
0
        }
7123
38.0k
        TxnInfoPB txn_info;
7124
38.0k
        if (!txn_info.ParseFromString(info_val)) {
7125
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7126
0
            return -1;
7127
0
        }
7128
38.0k
        txn->remove(info_key);
7129
        // Remove sub txn index kvs
7130
38.0k
        std::vector<std::string> sub_txn_index_keys;
7131
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7132
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7133
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7134
38.0k
        }
7135
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7136
38.0k
            txn->remove(sub_txn_index_key);
7137
38.0k
        }
7138
        // Update txn label
7139
38.0k
        std::string label_key, label_val;
7140
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7141
38.0k
        err = txn->get(label_key, &label_val);
7142
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7143
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7144
0
                         << " err=" << err;
7145
0
            return -1;
7146
0
        }
7147
38.0k
        TxnLabelPB txn_label;
7148
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7149
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7150
0
            return -1;
7151
0
        }
7152
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7153
38.0k
        if (it != txn_label.txn_ids().end()) {
7154
38.0k
            txn_label.mutable_txn_ids()->erase(it);
7155
38.0k
        }
7156
38.0k
        if (txn_label.txn_ids().empty()) {
7157
38.0k
            txn->remove(label_key);
7158
38.0k
            TEST_SYNC_POINT_CALLBACK(
7159
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7160
38.0k
        } else {
7161
11
            if (!txn_label.SerializeToString(&label_val)) {
7162
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7163
0
                return -1;
7164
0
            }
7165
11
            TEST_SYNC_POINT_CALLBACK(
7166
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7167
11
            txn->atomic_set_ver_value(label_key, label_val);
7168
11
            TEST_SYNC_POINT_CALLBACK(
7169
11
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7170
11
        }
7171
        // Remove recycle txn kv
7172
38.0k
        txn->remove(k);
7173
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7174
38.0k
        err = txn->commit();
7175
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7176
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
7177
4
                TEST_SYNC_POINT_CALLBACK(
7178
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7179
                // log the txn_id and label
7180
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7181
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7182
4
                             << " txn_label=" << txn_info.label();
7183
4
                return 1;
7184
4
            }
7185
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7186
0
            return -1;
7187
4
        }
7188
38.0k
        ++num_recycled;
7189
7190
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7191
38.0k
        return 0;
7192
38.0k
    };
7193
7194
22
    auto loop_done = [&]() -> int {
7195
15
        DORIS_CLOUD_DEFER {
7196
15
            recycle_txn_keys_by_label.clear();
7197
15
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7195
1
        DORIS_CLOUD_DEFER {
7196
1
            recycle_txn_keys_by_label.clear();
7197
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7195
14
        DORIS_CLOUD_DEFER {
7196
14
            recycle_txn_keys_by_label.clear();
7197
14
        };
7198
15
        TEST_SYNC_POINT_CALLBACK(
7199
15
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7200
15
                &recycle_txn_keys_by_label);
7201
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7202
38.0k
            int ret = delete_recycle_txn_kv(k);
7203
38.0k
            TEST_SYNC_POINT_CALLBACK(
7204
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7205
38.0k
                    &ret);
7206
38.0k
            if (ret == 1) {
7207
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7208
4
                for (int i = 1; i <= max_retry; ++i) {
7209
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7210
3
                    ret = delete_recycle_txn_kv(k);
7211
3
                    TEST_SYNC_POINT_CALLBACK(
7212
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7213
3
                            "error",
7214
3
                            &ret);
7215
3
                    if (ret != 1) {
7216
1
                        break;
7217
1
                    }
7218
                    // random sleep 0-100 ms to retry
7219
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7220
2
                }
7221
2
            }
7222
38.0k
            return ret;
7223
38.0k
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
7201
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7202
1
            int ret = delete_recycle_txn_kv(k);
7203
1
            TEST_SYNC_POINT_CALLBACK(
7204
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7205
1
                    &ret);
7206
1
            if (ret == 1) {
7207
0
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7208
0
                for (int i = 1; i <= max_retry; ++i) {
7209
0
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7210
0
                    ret = delete_recycle_txn_kv(k);
7211
0
                    TEST_SYNC_POINT_CALLBACK(
7212
0
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7213
0
                            "error",
7214
0
                            &ret);
7215
0
                    if (ret != 1) {
7216
0
                        break;
7217
0
                    }
7218
                    // random sleep 0-100 ms to retry
7219
0
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7220
0
                }
7221
0
            }
7222
1
            return ret;
7223
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
7201
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7202
38.0k
            int ret = delete_recycle_txn_kv(k);
7203
38.0k
            TEST_SYNC_POINT_CALLBACK(
7204
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7205
38.0k
                    &ret);
7206
38.0k
            if (ret == 1) {
7207
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7208
4
                for (int i = 1; i <= max_retry; ++i) {
7209
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7210
3
                    ret = delete_recycle_txn_kv(k);
7211
3
                    TEST_SYNC_POINT_CALLBACK(
7212
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7213
3
                            "error",
7214
3
                            &ret);
7215
3
                    if (ret != 1) {
7216
1
                        break;
7217
1
                    }
7218
                    // random sleep 0-100 ms to retry
7219
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7220
2
                }
7221
2
            }
7222
38.0k
            return ret;
7223
38.0k
        };
7224
7225
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7226
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7227
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7228
0
                           << " txn_count=" << txn_keys.size();
7229
38.0k
                for (const auto& k : txn_keys) {
7230
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7231
38.0k
                    if (ret != 0) {
7232
2
                        LOG_WARNING("failed to delete recycle txn kv")
7233
2
                                .tag("instance id", instance_id_)
7234
2
                                .tag("key", hex(k))
7235
2
                                .tag("label_key", hex(label_key));
7236
2
                        return -1;
7237
2
                    }
7238
38.0k
                }
7239
38.0k
                return 0;
7240
38.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7226
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7227
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7228
0
                           << " txn_count=" << txn_keys.size();
7229
1
                for (const auto& k : txn_keys) {
7230
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7231
1
                    if (ret != 0) {
7232
0
                        LOG_WARNING("failed to delete recycle txn kv")
7233
0
                                .tag("instance id", instance_id_)
7234
0
                                .tag("key", hex(k))
7235
0
                                .tag("label_key", hex(label_key));
7236
0
                        return -1;
7237
0
                    }
7238
1
                }
7239
1
                return 0;
7240
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7226
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7227
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7228
0
                           << " txn_count=" << txn_keys.size();
7229
38.0k
                for (const auto& k : txn_keys) {
7230
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7231
38.0k
                    if (ret != 0) {
7232
2
                        LOG_WARNING("failed to delete recycle txn kv")
7233
2
                                .tag("instance id", instance_id_)
7234
2
                                .tag("key", hex(k))
7235
2
                                .tag("label_key", hex(label_key));
7236
2
                        return -1;
7237
2
                    }
7238
38.0k
                }
7239
38.0k
                return 0;
7240
38.0k
            });
7241
38.0k
        }
7242
15
        bool finished = true;
7243
15
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7244
38.0k
        for (int r : rets) {
7245
38.0k
            if (r != 0) {
7246
2
                ret = -1;
7247
2
            }
7248
38.0k
        }
7249
7250
15
        ret = finished ? ret : -1;
7251
7252
        // Update metrics after all concurrent tasks completed
7253
15
        metrics_context.total_recycled_num = num_recycled.load();
7254
15
        metrics_context.report();
7255
7256
15
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7257
7258
15
        if (ret != 0) {
7259
6
            LOG_WARNING("recycle txn kv ret!=0")
7260
6
                    .tag("finished", finished)
7261
6
                    .tag("ret", ret)
7262
6
                    .tag("instance_id", instance_id_);
7263
6
            return ret;
7264
6
        }
7265
9
        return ret;
7266
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7194
1
    auto loop_done = [&]() -> int {
7195
1
        DORIS_CLOUD_DEFER {
7196
1
            recycle_txn_keys_by_label.clear();
7197
1
        };
7198
1
        TEST_SYNC_POINT_CALLBACK(
7199
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7200
1
                &recycle_txn_keys_by_label);
7201
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7202
1
            int ret = delete_recycle_txn_kv(k);
7203
1
            TEST_SYNC_POINT_CALLBACK(
7204
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7205
1
                    &ret);
7206
1
            if (ret == 1) {
7207
1
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7208
1
                for (int i = 1; i <= max_retry; ++i) {
7209
1
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7210
1
                    ret = delete_recycle_txn_kv(k);
7211
1
                    TEST_SYNC_POINT_CALLBACK(
7212
1
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7213
1
                            "error",
7214
1
                            &ret);
7215
1
                    if (ret != 1) {
7216
1
                        break;
7217
1
                    }
7218
                    // random sleep 0-100 ms to retry
7219
1
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7220
1
                }
7221
1
            }
7222
1
            return ret;
7223
1
        };
7224
7225
1
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7226
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7227
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7228
1
                           << " txn_count=" << txn_keys.size();
7229
1
                for (const auto& k : txn_keys) {
7230
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7231
1
                    if (ret != 0) {
7232
1
                        LOG_WARNING("failed to delete recycle txn kv")
7233
1
                                .tag("instance id", instance_id_)
7234
1
                                .tag("key", hex(k))
7235
1
                                .tag("label_key", hex(label_key));
7236
1
                        return -1;
7237
1
                    }
7238
1
                }
7239
1
                return 0;
7240
1
            });
7241
1
        }
7242
1
        bool finished = true;
7243
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7244
1
        for (int r : rets) {
7245
1
            if (r != 0) {
7246
0
                ret = -1;
7247
0
            }
7248
1
        }
7249
7250
1
        ret = finished ? ret : -1;
7251
7252
        // Update metrics after all concurrent tasks completed
7253
1
        metrics_context.total_recycled_num = num_recycled.load();
7254
1
        metrics_context.report();
7255
7256
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7257
7258
1
        if (ret != 0) {
7259
0
            LOG_WARNING("recycle txn kv ret!=0")
7260
0
                    .tag("finished", finished)
7261
0
                    .tag("ret", ret)
7262
0
                    .tag("instance_id", instance_id_);
7263
0
            return ret;
7264
0
        }
7265
1
        return ret;
7266
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7194
14
    auto loop_done = [&]() -> int {
7195
14
        DORIS_CLOUD_DEFER {
7196
14
            recycle_txn_keys_by_label.clear();
7197
14
        };
7198
14
        TEST_SYNC_POINT_CALLBACK(
7199
14
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7200
14
                &recycle_txn_keys_by_label);
7201
14
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7202
14
            int ret = delete_recycle_txn_kv(k);
7203
14
            TEST_SYNC_POINT_CALLBACK(
7204
14
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7205
14
                    &ret);
7206
14
            if (ret == 1) {
7207
14
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7208
14
                for (int i = 1; i <= max_retry; ++i) {
7209
14
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7210
14
                    ret = delete_recycle_txn_kv(k);
7211
14
                    TEST_SYNC_POINT_CALLBACK(
7212
14
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7213
14
                            "error",
7214
14
                            &ret);
7215
14
                    if (ret != 1) {
7216
14
                        break;
7217
14
                    }
7218
                    // random sleep 0-100 ms to retry
7219
14
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7220
14
                }
7221
14
            }
7222
14
            return ret;
7223
14
        };
7224
7225
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7226
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7227
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7228
38.0k
                           << " txn_count=" << txn_keys.size();
7229
38.0k
                for (const auto& k : txn_keys) {
7230
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7231
38.0k
                    if (ret != 0) {
7232
38.0k
                        LOG_WARNING("failed to delete recycle txn kv")
7233
38.0k
                                .tag("instance id", instance_id_)
7234
38.0k
                                .tag("key", hex(k))
7235
38.0k
                                .tag("label_key", hex(label_key));
7236
38.0k
                        return -1;
7237
38.0k
                    }
7238
38.0k
                }
7239
38.0k
                return 0;
7240
38.0k
            });
7241
38.0k
        }
7242
14
        bool finished = true;
7243
14
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7244
38.0k
        for (int r : rets) {
7245
38.0k
            if (r != 0) {
7246
2
                ret = -1;
7247
2
            }
7248
38.0k
        }
7249
7250
14
        ret = finished ? ret : -1;
7251
7252
        // Update metrics after all concurrent tasks completed
7253
14
        metrics_context.total_recycled_num = num_recycled.load();
7254
14
        metrics_context.report();
7255
7256
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7257
7258
14
        if (ret != 0) {
7259
6
            LOG_WARNING("recycle txn kv ret!=0")
7260
6
                    .tag("finished", finished)
7261
6
                    .tag("ret", ret)
7262
6
                    .tag("instance_id", instance_id_);
7263
6
            return ret;
7264
6
        }
7265
8
        return ret;
7266
14
    };
7267
7268
22
    if (config::enable_recycler_stats_metrics) {
7269
0
        scan_and_statistics_expired_txn_label();
7270
0
    }
7271
    // recycle_func and loop_done for scan and recycle
7272
22
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7273
22
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7274
22
}
7275
7276
struct CopyJobIdTuple {
7277
    std::string instance_id;
7278
    std::string stage_id;
7279
    long table_id;
7280
    std::string copy_id;
7281
    std::string stage_path;
7282
};
7283
struct BatchObjStoreAccessor {
7284
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7285
                          TxnKv* txn_kv)
7286
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7287
3
    ~BatchObjStoreAccessor() {
7288
3
        if (!paths_.empty()) {
7289
3
            consume();
7290
3
        }
7291
3
    }
7292
7293
    /**
7294
    * To implicitely do batch work and submit the batch delete task to s3
7295
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7296
    *
7297
    * @param copy_job The protubuf struct consists of the copy job files.
7298
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7299
    *            it would last until we finish the delete task, here we need pass one string value
7300
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7301
    */
7302
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7303
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7304
5
        auto& file_keys = copy_file_keys_[key];
7305
5
        file_keys.log_trace =
7306
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7307
5
                            instance_id, stage_id, table_id, copy_id, path);
7308
5
        std::string_view log_trace = file_keys.log_trace;
7309
2.03k
        for (const auto& file : copy_job.object_files()) {
7310
2.03k
            auto relative_path = file.relative_path();
7311
2.03k
            paths_.push_back(relative_path);
7312
2.03k
            file_keys.keys.push_back(copy_file_key(
7313
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7314
2.03k
            LOG_INFO(log_trace)
7315
2.03k
                    .tag("relative_path", relative_path)
7316
2.03k
                    .tag("batch_count", batch_count_);
7317
2.03k
        }
7318
5
        LOG_INFO(log_trace)
7319
5
                .tag("objects_num", copy_job.object_files().size())
7320
5
                .tag("batch_count", batch_count_);
7321
        // TODO(AlexYue): If the size is 1001, it would be one delete with 1000 objects and one delete request with only one object(**ATTN**: DOESN'T
7322
        // recommend using delete objects when objects num is less than 10)
7323
5
        if (paths_.size() < 1000) {
7324
3
            return;
7325
3
        }
7326
2
        consume();
7327
2
    }
7328
7329
private:
7330
5
    void consume() {
7331
5
        DORIS_CLOUD_DEFER {
7332
5
            paths_.clear();
7333
5
            copy_file_keys_.clear();
7334
5
            batch_count_++;
7335
7336
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7337
5
                        batch_count_);
7338
5
        };
7339
7340
5
        StopWatch sw;
7341
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7342
5
        if (0 != accessor_->delete_files(paths_)) {
7343
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7344
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7345
2
            return;
7346
2
        }
7347
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7348
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7349
        // delete fdb's keys
7350
3
        for (auto& file_keys : copy_file_keys_) {
7351
3
            auto& [log_trace, keys] = file_keys.second;
7352
3
            std::unique_ptr<Transaction> txn;
7353
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7354
0
                LOG(WARNING) << "failed to create txn";
7355
0
                continue;
7356
0
            }
7357
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7358
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7359
            // limited, should not cause the txn commit failed.
7360
1.02k
            for (const auto& key : keys) {
7361
1.02k
                txn->remove(key);
7362
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7363
1.02k
            }
7364
3
            txn->remove(file_keys.first);
7365
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7366
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7367
0
                continue;
7368
0
            }
7369
3
        }
7370
3
    }
7371
    std::shared_ptr<StorageVaultAccessor> accessor_;
7372
    // the path of the s3 files to be deleted
7373
    std::vector<std::string> paths_;
7374
    struct CopyFiles {
7375
        std::string log_trace;
7376
        std::vector<std::string> keys;
7377
    };
7378
    // pair<std::string, std::vector<std::string>>
7379
    // first: instance_id_ stage_id table_id query_id
7380
    // second: keys to be deleted
7381
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7382
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7383
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7384
    // which can together uniquely identifies different tasks for tracing log
7385
    uint64_t& batch_count_;
7386
    TxnKv* txn_kv_;
7387
};
7388
7389
13
int InstanceRecycler::recycle_copy_jobs() {
7390
13
    int64_t num_scanned = 0;
7391
13
    int64_t num_finished = 0;
7392
13
    int64_t num_expired = 0;
7393
13
    int64_t num_recycled = 0;
7394
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7395
13
    uint64_t batch_count = 0;
7396
13
    const std::string task_name = "recycle_copy_jobs";
7397
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7398
7399
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7400
7401
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7402
13
    register_recycle_task(task_name, start_time);
7403
7404
13
    DORIS_CLOUD_DEFER {
7405
13
        unregister_recycle_task(task_name);
7406
13
        int64_t cost =
7407
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7408
13
        metrics_context.finish_report();
7409
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7410
13
                .tag("instance_id", instance_id_)
7411
13
                .tag("num_scanned", num_scanned)
7412
13
                .tag("num_finished", num_finished)
7413
13
                .tag("num_expired", num_expired)
7414
13
                .tag("num_recycled", num_recycled);
7415
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7404
13
    DORIS_CLOUD_DEFER {
7405
13
        unregister_recycle_task(task_name);
7406
13
        int64_t cost =
7407
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7408
13
        metrics_context.finish_report();
7409
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7410
13
                .tag("instance_id", instance_id_)
7411
13
                .tag("num_scanned", num_scanned)
7412
13
                .tag("num_finished", num_finished)
7413
13
                .tag("num_expired", num_expired)
7414
13
                .tag("num_recycled", num_recycled);
7415
13
    };
7416
7417
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7418
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7419
13
    std::string key0;
7420
13
    std::string key1;
7421
13
    copy_job_key(key_info0, &key0);
7422
13
    copy_job_key(key_info1, &key1);
7423
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7424
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7425
13
                         &batch_count, &stage_accessor_map, &task_name, &metrics_context,
7426
16
                         this](std::string_view k, std::string_view v) -> int {
7427
16
        ++num_scanned;
7428
16
        CopyJobPB copy_job;
7429
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7430
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7431
0
            return -1;
7432
0
        }
7433
7434
        // decode copy job key
7435
16
        auto k1 = k;
7436
16
        k1.remove_prefix(1);
7437
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7438
16
        decode_key(&k1, &out);
7439
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7440
        // -> CopyJobPB
7441
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7442
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7443
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7444
7445
16
        bool check_storage = true;
7446
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7447
12
            ++num_finished;
7448
7449
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7450
7
                auto it = stage_accessor_map.find(stage_id);
7451
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7452
7
                std::string_view path;
7453
7
                if (it != stage_accessor_map.end()) {
7454
2
                    accessor = it->second;
7455
5
                } else {
7456
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7457
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7458
5
                                                      &inner_accessor);
7459
5
                    if (ret < 0) { // error
7460
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7461
0
                        return -1;
7462
5
                    } else if (ret == 0) {
7463
3
                        path = inner_accessor->uri();
7464
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7465
3
                                inner_accessor, batch_count, txn_kv_.get());
7466
3
                        stage_accessor_map.emplace(stage_id, accessor);
7467
3
                    } else { // stage not found, skip check storage
7468
2
                        check_storage = false;
7469
2
                    }
7470
5
                }
7471
7
                if (check_storage) {
7472
                    // TODO delete objects with key and etag is not supported
7473
5
                    accessor->add(std::move(copy_job), std::string(k),
7474
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7475
5
                    return 0;
7476
5
                }
7477
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7478
5
                int64_t current_time =
7479
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7480
5
                if (copy_job.finish_time_ms() > 0) {
7481
2
                    if (!config::force_immediate_recycle &&
7482
2
                        current_time < copy_job.finish_time_ms() +
7483
2
                                               config::copy_job_max_retention_second * 1000) {
7484
1
                        return 0;
7485
1
                    }
7486
3
                } else {
7487
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7488
3
                    if (!config::force_immediate_recycle &&
7489
3
                        current_time < copy_job.start_time_ms() +
7490
3
                                               config::copy_job_max_retention_second * 1000) {
7491
1
                        return 0;
7492
1
                    }
7493
3
                }
7494
5
            }
7495
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7496
4
            int64_t current_time =
7497
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7498
            // if copy job is timeout: delete all copy file kvs and copy job kv
7499
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7500
2
                return 0;
7501
2
            }
7502
2
            ++num_expired;
7503
2
        }
7504
7505
        // delete all copy files
7506
7
        std::vector<std::string> copy_file_keys;
7507
70
        for (auto& file : copy_job.object_files()) {
7508
70
            copy_file_keys.push_back(copy_file_key(
7509
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7510
70
        }
7511
7
        std::unique_ptr<Transaction> txn;
7512
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7513
0
            LOG(WARNING) << "failed to create txn";
7514
0
            return -1;
7515
0
        }
7516
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7517
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7518
        // limited, should not cause the txn commit failed.
7519
70
        for (const auto& key : copy_file_keys) {
7520
70
            txn->remove(key);
7521
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7522
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7523
70
                      << ", query_id=" << copy_id;
7524
70
        }
7525
7
        txn->remove(k);
7526
7
        TxnErrorCode err = txn->commit();
7527
7
        if (err != TxnErrorCode::TXN_OK) {
7528
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7529
0
            return -1;
7530
0
        }
7531
7532
7
        metrics_context.total_recycled_num = ++num_recycled;
7533
7
        metrics_context.report();
7534
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7535
7
        return 0;
7536
7
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7426
16
                         this](std::string_view k, std::string_view v) -> int {
7427
16
        ++num_scanned;
7428
16
        CopyJobPB copy_job;
7429
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7430
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7431
0
            return -1;
7432
0
        }
7433
7434
        // decode copy job key
7435
16
        auto k1 = k;
7436
16
        k1.remove_prefix(1);
7437
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7438
16
        decode_key(&k1, &out);
7439
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7440
        // -> CopyJobPB
7441
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7442
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7443
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7444
7445
16
        bool check_storage = true;
7446
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7447
12
            ++num_finished;
7448
7449
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7450
7
                auto it = stage_accessor_map.find(stage_id);
7451
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7452
7
                std::string_view path;
7453
7
                if (it != stage_accessor_map.end()) {
7454
2
                    accessor = it->second;
7455
5
                } else {
7456
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7457
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7458
5
                                                      &inner_accessor);
7459
5
                    if (ret < 0) { // error
7460
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7461
0
                        return -1;
7462
5
                    } else if (ret == 0) {
7463
3
                        path = inner_accessor->uri();
7464
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7465
3
                                inner_accessor, batch_count, txn_kv_.get());
7466
3
                        stage_accessor_map.emplace(stage_id, accessor);
7467
3
                    } else { // stage not found, skip check storage
7468
2
                        check_storage = false;
7469
2
                    }
7470
5
                }
7471
7
                if (check_storage) {
7472
                    // TODO delete objects with key and etag is not supported
7473
5
                    accessor->add(std::move(copy_job), std::string(k),
7474
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7475
5
                    return 0;
7476
5
                }
7477
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7478
5
                int64_t current_time =
7479
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7480
5
                if (copy_job.finish_time_ms() > 0) {
7481
2
                    if (!config::force_immediate_recycle &&
7482
2
                        current_time < copy_job.finish_time_ms() +
7483
2
                                               config::copy_job_max_retention_second * 1000) {
7484
1
                        return 0;
7485
1
                    }
7486
3
                } else {
7487
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7488
3
                    if (!config::force_immediate_recycle &&
7489
3
                        current_time < copy_job.start_time_ms() +
7490
3
                                               config::copy_job_max_retention_second * 1000) {
7491
1
                        return 0;
7492
1
                    }
7493
3
                }
7494
5
            }
7495
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7496
4
            int64_t current_time =
7497
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7498
            // if copy job is timeout: delete all copy file kvs and copy job kv
7499
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7500
2
                return 0;
7501
2
            }
7502
2
            ++num_expired;
7503
2
        }
7504
7505
        // delete all copy files
7506
7
        std::vector<std::string> copy_file_keys;
7507
70
        for (auto& file : copy_job.object_files()) {
7508
70
            copy_file_keys.push_back(copy_file_key(
7509
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7510
70
        }
7511
7
        std::unique_ptr<Transaction> txn;
7512
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7513
0
            LOG(WARNING) << "failed to create txn";
7514
0
            return -1;
7515
0
        }
7516
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7517
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7518
        // limited, should not cause the txn commit failed.
7519
70
        for (const auto& key : copy_file_keys) {
7520
70
            txn->remove(key);
7521
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7522
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7523
70
                      << ", query_id=" << copy_id;
7524
70
        }
7525
7
        txn->remove(k);
7526
7
        TxnErrorCode err = txn->commit();
7527
7
        if (err != TxnErrorCode::TXN_OK) {
7528
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7529
0
            return -1;
7530
0
        }
7531
7532
7
        metrics_context.total_recycled_num = ++num_recycled;
7533
7
        metrics_context.report();
7534
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7535
7
        return 0;
7536
7
    };
7537
7538
13
    if (config::enable_recycler_stats_metrics) {
7539
0
        scan_and_statistics_copy_jobs();
7540
0
    }
7541
    // recycle_func and loop_done for scan and recycle
7542
13
    return scan_and_recycle(key0, key1, std::move(recycle_func));
7543
13
}
7544
7545
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7546
                                             const StagePB::StageType& stage_type,
7547
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7548
5
#ifdef UNIT_TEST
7549
    // In unit test, external use the same accessor as the internal stage
7550
5
    auto it = accessor_map_.find(stage_id);
7551
5
    if (it != accessor_map_.end()) {
7552
3
        *accessor = it->second;
7553
3
    } else {
7554
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7555
2
        return 1;
7556
2
    }
7557
#else
7558
    // init s3 accessor and add to accessor map
7559
    auto stage_it =
7560
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7561
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7562
7563
    if (stage_it == instance_info_.stages().end()) {
7564
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7565
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7566
        return 1;
7567
    }
7568
7569
    const auto& object_store_info = stage_it->obj_info();
7570
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7571
7572
    S3Conf s3_conf;
7573
    if (stage_type == StagePB::EXTERNAL) {
7574
        if (stage_access_type == StagePB::AKSK) {
7575
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7576
            if (!conf) {
7577
                return -1;
7578
            }
7579
7580
            s3_conf = std::move(*conf);
7581
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7582
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7583
            if (!conf) {
7584
                return -1;
7585
            }
7586
7587
            s3_conf = std::move(*conf);
7588
            if (instance_info_.ram_user().has_encryption_info()) {
7589
                AkSkPair plain_ak_sk_pair;
7590
                int ret = decrypt_ak_sk_helper(
7591
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7592
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7593
                if (ret != 0) {
7594
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7595
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7596
                    return -1;
7597
                }
7598
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7599
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7600
            } else {
7601
                s3_conf.ak = instance_info_.ram_user().ak();
7602
                s3_conf.sk = instance_info_.ram_user().sk();
7603
            }
7604
        } else {
7605
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7606
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7607
            return -1;
7608
        }
7609
    } else if (stage_type == StagePB::INTERNAL) {
7610
        int idx = stoi(object_store_info.id());
7611
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7612
            LOG(WARNING) << "invalid idx: " << idx;
7613
            return -1;
7614
        }
7615
7616
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7617
        auto conf = S3Conf::from_obj_store_info(old_obj);
7618
        if (!conf) {
7619
            return -1;
7620
        }
7621
7622
        s3_conf = std::move(*conf);
7623
        s3_conf.prefix = object_store_info.prefix();
7624
    } else {
7625
        LOG(WARNING) << "unknown stage type " << stage_type;
7626
        return -1;
7627
    }
7628
7629
    std::shared_ptr<S3Accessor> s3_accessor;
7630
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7631
    if (ret != 0) {
7632
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7633
        return -1;
7634
    }
7635
7636
    *accessor = std::move(s3_accessor);
7637
#endif
7638
3
    return 0;
7639
5
}
7640
7641
11
int InstanceRecycler::recycle_stage() {
7642
11
    int64_t num_scanned = 0;
7643
11
    int64_t num_recycled = 0;
7644
11
    const std::string task_name = "recycle_stage";
7645
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7646
7647
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7648
7649
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7650
11
    register_recycle_task(task_name, start_time);
7651
7652
11
    DORIS_CLOUD_DEFER {
7653
11
        unregister_recycle_task(task_name);
7654
11
        int64_t cost =
7655
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7656
11
        metrics_context.finish_report();
7657
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7658
11
                .tag("instance_id", instance_id_)
7659
11
                .tag("num_scanned", num_scanned)
7660
11
                .tag("num_recycled", num_recycled);
7661
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7652
11
    DORIS_CLOUD_DEFER {
7653
11
        unregister_recycle_task(task_name);
7654
11
        int64_t cost =
7655
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7656
11
        metrics_context.finish_report();
7657
        LOG_WARNING("recycle stage, cost={}s", cost)
7658
11
                .tag("instance_id", instance_id_)
7659
11
                .tag("num_scanned", num_scanned)
7660
11
                .tag("num_recycled", num_recycled);
7661
11
    };
7662
7663
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7664
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7665
11
    std::string key0 = recycle_stage_key(key_info0);
7666
11
    std::string key1 = recycle_stage_key(key_info1);
7667
7668
11
    std::vector<std::string_view> stage_keys;
7669
11
    auto recycle_func = [&start_time, &num_scanned, &num_recycled, &stage_keys, &metrics_context,
7670
11
                         this](std::string_view k, std::string_view v) -> int {
7671
1
        ++num_scanned;
7672
1
        RecycleStagePB recycle_stage;
7673
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7674
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7675
0
            return -1;
7676
0
        }
7677
7678
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7679
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7680
0
            LOG(WARNING) << "invalid idx: " << idx;
7681
0
            return -1;
7682
0
        }
7683
7684
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7685
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7686
1
                [&] {
7687
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7688
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7689
1
                    if (!s3_conf) {
7690
1
                        return -1;
7691
1
                    }
7692
7693
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7694
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7695
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7696
1
                    if (ret != 0) {
7697
1
                        return -1;
7698
1
                    }
7699
7700
1
                    accessor = std::move(s3_accessor);
7701
1
                    return 0;
7702
1
                }(),
7703
1
                "recycle_stage:get_accessor", &accessor);
7704
7705
1
        if (ret != 0) {
7706
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7707
0
            return ret;
7708
0
        }
7709
7710
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7711
1
                .tag("instance_id", instance_id_)
7712
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7713
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7714
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7715
1
                .tag("obj_info_id", idx)
7716
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7717
1
        ret = accessor->delete_all();
7718
1
        if (ret != 0) {
7719
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7720
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7721
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7722
0
                         << ", ret=" << ret;
7723
0
            return -1;
7724
0
        }
7725
1
        metrics_context.total_recycled_num = ++num_recycled;
7726
1
        metrics_context.report();
7727
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7728
1
        stage_keys.push_back(k);
7729
1
        return 0;
7730
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7670
1
                         this](std::string_view k, std::string_view v) -> int {
7671
1
        ++num_scanned;
7672
1
        RecycleStagePB recycle_stage;
7673
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7674
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7675
0
            return -1;
7676
0
        }
7677
7678
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7679
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7680
0
            LOG(WARNING) << "invalid idx: " << idx;
7681
0
            return -1;
7682
0
        }
7683
7684
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7685
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7686
1
                [&] {
7687
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7688
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7689
1
                    if (!s3_conf) {
7690
1
                        return -1;
7691
1
                    }
7692
7693
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7694
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7695
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7696
1
                    if (ret != 0) {
7697
1
                        return -1;
7698
1
                    }
7699
7700
1
                    accessor = std::move(s3_accessor);
7701
1
                    return 0;
7702
1
                }(),
7703
1
                "recycle_stage:get_accessor", &accessor);
7704
7705
1
        if (ret != 0) {
7706
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7707
0
            return ret;
7708
0
        }
7709
7710
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7711
1
                .tag("instance_id", instance_id_)
7712
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7713
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7714
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7715
1
                .tag("obj_info_id", idx)
7716
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7717
1
        ret = accessor->delete_all();
7718
1
        if (ret != 0) {
7719
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7720
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7721
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7722
0
                         << ", ret=" << ret;
7723
0
            return -1;
7724
0
        }
7725
1
        metrics_context.total_recycled_num = ++num_recycled;
7726
1
        metrics_context.report();
7727
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7728
1
        stage_keys.push_back(k);
7729
1
        return 0;
7730
1
    };
7731
7732
11
    auto loop_done = [&stage_keys, this]() -> int {
7733
1
        if (stage_keys.empty()) return 0;
7734
1
        DORIS_CLOUD_DEFER {
7735
1
            stage_keys.clear();
7736
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7734
1
        DORIS_CLOUD_DEFER {
7735
1
            stage_keys.clear();
7736
1
        };
7737
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7738
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7739
0
            return -1;
7740
0
        }
7741
1
        return 0;
7742
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7732
1
    auto loop_done = [&stage_keys, this]() -> int {
7733
1
        if (stage_keys.empty()) return 0;
7734
1
        DORIS_CLOUD_DEFER {
7735
1
            stage_keys.clear();
7736
1
        };
7737
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7738
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7739
0
            return -1;
7740
0
        }
7741
1
        return 0;
7742
1
    };
7743
11
    if (config::enable_recycler_stats_metrics) {
7744
0
        scan_and_statistics_stage();
7745
0
    }
7746
    // recycle_func and loop_done for scan and recycle
7747
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7748
11
}
7749
7750
10
int InstanceRecycler::recycle_expired_stage_objects() {
7751
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7752
7753
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7754
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7755
7756
10
    DORIS_CLOUD_DEFER {
7757
10
        int64_t cost =
7758
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7759
10
        metrics_context.finish_report();
7760
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7761
10
                .tag("instance_id", instance_id_);
7762
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7756
10
    DORIS_CLOUD_DEFER {
7757
10
        int64_t cost =
7758
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7759
10
        metrics_context.finish_report();
7760
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7761
10
                .tag("instance_id", instance_id_);
7762
10
    };
7763
7764
10
    int ret = 0;
7765
7766
10
    if (config::enable_recycler_stats_metrics) {
7767
0
        scan_and_statistics_expired_stage_objects();
7768
0
    }
7769
7770
10
    for (const auto& stage : instance_info_.stages()) {
7771
0
        std::stringstream ss;
7772
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7773
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7774
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7775
0
           << ", prefix=" << stage.obj_info().prefix();
7776
7777
0
        if (stopped()) {
7778
0
            break;
7779
0
        }
7780
0
        if (stage.type() == StagePB::EXTERNAL) {
7781
0
            continue;
7782
0
        }
7783
0
        int idx = stoi(stage.obj_info().id());
7784
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7785
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7786
0
            continue;
7787
0
        }
7788
7789
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7790
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7791
0
        if (!s3_conf) {
7792
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7793
0
            continue;
7794
0
        }
7795
7796
0
        s3_conf->prefix = stage.obj_info().prefix();
7797
0
        std::shared_ptr<S3Accessor> accessor;
7798
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7799
0
        if (ret1 != 0) {
7800
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7801
0
            ret = -1;
7802
0
            continue;
7803
0
        }
7804
7805
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7806
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7807
0
            ret = -1;
7808
0
            continue;
7809
0
        }
7810
7811
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7812
0
        int64_t expiration_time =
7813
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7814
0
                config::internal_stage_objects_expire_time_second;
7815
0
        if (config::force_immediate_recycle) {
7816
0
            expiration_time = INT64_MAX;
7817
0
        }
7818
0
        ret1 = accessor->delete_all(expiration_time);
7819
0
        if (ret1 != 0) {
7820
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7821
0
                         << ss.str();
7822
0
            ret = -1;
7823
0
            continue;
7824
0
        }
7825
0
        metrics_context.total_recycled_num++;
7826
0
        metrics_context.report();
7827
0
    }
7828
10
    return ret;
7829
10
}
7830
7831
228
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7832
228
    std::lock_guard lock(recycle_tasks_mutex);
7833
228
    running_recycle_tasks[task_name] = start_time;
7834
228
}
7835
7836
228
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7837
228
    std::lock_guard lock(recycle_tasks_mutex);
7838
228
    DCHECK(running_recycle_tasks[task_name] > 0);
7839
228
    running_recycle_tasks.erase(task_name);
7840
228
}
7841
7842
21
bool InstanceRecycler::check_recycle_tasks() {
7843
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7844
21
    {
7845
21
        std::lock_guard lock(recycle_tasks_mutex);
7846
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7847
21
    }
7848
7849
21
    bool found = false;
7850
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7851
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7852
20
        int64_t cost = now - start_time;
7853
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7854
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7855
20
                    .tag("instance_id", instance_id_)
7856
20
                    .tag("task", task_name);
7857
20
            found = true;
7858
20
        }
7859
20
    }
7860
7861
21
    return found;
7862
21
}
7863
7864
// Scan and statistics indexes that need to be recycled
7865
1
int InstanceRecycler::scan_and_statistics_indexes() {
7866
1
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_indexes");
7867
1
    RecyclerMetricsContext stream_metrics_context(instance_id_, "recycle_stream");
7868
7869
1
    RecycleIndexKeyInfo index_key_info0 {instance_id_, 0};
7870
1
    RecycleIndexKeyInfo index_key_info1 {instance_id_, INT64_MAX};
7871
1
    std::string index_key0;
7872
1
    std::string index_key1;
7873
1
    recycle_index_key(index_key_info0, &index_key0);
7874
1
    recycle_index_key(index_key_info1, &index_key1);
7875
1
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7876
7877
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7878
1
        RecycleIndexPB index_pb;
7879
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7880
0
            return 0;
7881
0
        }
7882
1
        int64_t current_time = ::time(nullptr);
7883
1
        if (current_time <
7884
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7885
0
            return 0;
7886
0
        }
7887
        // decode index_id
7888
1
        auto k1 = k;
7889
1
        k1.remove_prefix(1);
7890
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7891
1
        decode_key(&k1, &out);
7892
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7893
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7894
1
        std::unique_ptr<Transaction> txn;
7895
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7896
1
        if (err != TxnErrorCode::TXN_OK) {
7897
0
            return 0;
7898
0
        }
7899
1
        std::string val;
7900
1
        err = txn->get(k, &val);
7901
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7902
0
            return 0;
7903
0
        }
7904
1
        if (err != TxnErrorCode::TXN_OK) {
7905
0
            return 0;
7906
0
        }
7907
1
        index_pb.Clear();
7908
1
        if (!index_pb.ParseFromString(val)) {
7909
0
            return 0;
7910
0
        }
7911
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7912
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7913
0
                LOG_WARNING("table stream recycle index is missing binding")
7914
0
                        .tag("instance_id", instance_id_)
7915
0
                        .tag("stream_id", index_id);
7916
0
                return 0;
7917
0
            }
7918
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7919
2
                std::string end = prefix;
7920
2
                end.push_back('\xff');
7921
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7922
6
                                                              std::string_view value) {
7923
6
                    stream_metrics_context.total_need_recycle_num++;
7924
6
                    stream_metrics_context.total_need_recycle_data_size +=
7925
6
                            key.size() + value.size();
7926
6
                    return 0;
7927
6
                };
Unexecuted instantiation: recycler.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
recycler_test.cpp:_ZZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_ENKUlS6_S6_E_clES6_S6_
Line
Count
Source
7922
6
                                                              std::string_view value) {
7923
6
                    stream_metrics_context.total_need_recycle_num++;
7924
6
                    stream_metrics_context.total_need_recycle_data_size +=
7925
6
                            key.size() + value.size();
7926
6
                    return 0;
7927
6
                };
7928
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7929
2
            };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_ENKUlNSt7__cxx1112basic_stringIcS5_SaIcEEEE_clESA_
Line
Count
Source
7918
2
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7919
2
                std::string end = prefix;
7920
2
                end.push_back('\xff');
7921
2
                auto count_offset = [&stream_metrics_context](std::string_view key,
7922
2
                                                              std::string_view value) {
7923
2
                    stream_metrics_context.total_need_recycle_num++;
7924
2
                    stream_metrics_context.total_need_recycle_data_size +=
7925
2
                            key.size() + value.size();
7926
2
                    return 0;
7927
2
                };
7928
2
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7929
2
            };
7930
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7931
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7932
1
                    index_id);
7933
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7934
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7935
1
                    index_id);
7936
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7937
1
                scan_offset_prefix(versioned_prefix) != 0) {
7938
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7939
0
                        .tag("instance_id", instance_id_)
7940
0
                        .tag("stream_id", index_id);
7941
0
            }
7942
1
            return 0;
7943
1
        }
7944
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7945
0
            return 0;
7946
0
        }
7947
0
        metrics_context.total_need_recycle_num++;
7948
0
        return 0;
7949
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_indexesEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7877
1
    auto handle_index_kv = [&, this](std::string_view k, std::string_view v) -> int {
7878
1
        RecycleIndexPB index_pb;
7879
1
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
7880
0
            return 0;
7881
0
        }
7882
1
        int64_t current_time = ::time(nullptr);
7883
1
        if (current_time <
7884
1
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
7885
0
            return 0;
7886
0
        }
7887
        // decode index_id
7888
1
        auto k1 = k;
7889
1
        k1.remove_prefix(1);
7890
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7891
1
        decode_key(&k1, &out);
7892
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
7893
1
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
7894
1
        std::unique_ptr<Transaction> txn;
7895
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7896
1
        if (err != TxnErrorCode::TXN_OK) {
7897
0
            return 0;
7898
0
        }
7899
1
        std::string val;
7900
1
        err = txn->get(k, &val);
7901
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7902
0
            return 0;
7903
0
        }
7904
1
        if (err != TxnErrorCode::TXN_OK) {
7905
0
            return 0;
7906
0
        }
7907
1
        index_pb.Clear();
7908
1
        if (!index_pb.ParseFromString(val)) {
7909
0
            return 0;
7910
0
        }
7911
1
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
7912
1
            if (!index_pb.has_db_id() || !index_pb.has_stream_db_id()) {
7913
0
                LOG_WARNING("table stream recycle index is missing binding")
7914
0
                        .tag("instance_id", instance_id_)
7915
0
                        .tag("stream_id", index_id);
7916
0
                return 0;
7917
0
            }
7918
1
            auto scan_offset_prefix = [this, &stream_metrics_context](std::string prefix) {
7919
1
                std::string end = prefix;
7920
1
                end.push_back('\xff');
7921
1
                auto count_offset = [&stream_metrics_context](std::string_view key,
7922
1
                                                              std::string_view value) {
7923
1
                    stream_metrics_context.total_need_recycle_num++;
7924
1
                    stream_metrics_context.total_need_recycle_data_size +=
7925
1
                            key.size() + value.size();
7926
1
                    return 0;
7927
1
                };
7928
1
                return scan_and_recycle(std::move(prefix), end, std::move(count_offset));
7929
1
            };
7930
1
            const std::string latest_prefix = table_stream_offset_key_prefix(
7931
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7932
1
                    index_id);
7933
1
            const std::string versioned_prefix = versioned::table_stream_offset_key_prefix(
7934
1
                    instance_id_, index_pb.db_id(), index_pb.table_id(), index_pb.stream_db_id(),
7935
1
                    index_id);
7936
1
            if (scan_offset_prefix(latest_prefix) != 0 ||
7937
1
                scan_offset_prefix(versioned_prefix) != 0) {
7938
0
                LOG_WARNING("failed to scan table stream offsets for recycle statistics")
7939
0
                        .tag("instance_id", instance_id_)
7940
0
                        .tag("stream_id", index_id);
7941
0
            }
7942
1
            return 0;
7943
1
        }
7944
0
        if (scan_tablets_and_statistics(index_pb.table_id(), index_id, metrics_context) != 0) {
7945
0
            return 0;
7946
0
        }
7947
0
        metrics_context.total_need_recycle_num++;
7948
0
        return 0;
7949
0
    };
7950
7951
1
    int ret = scan_and_recycle(index_key0, index_key1, std::move(handle_index_kv));
7952
1
    metrics_context.report(true);
7953
1
    stream_metrics_context.report(true);
7954
1
    segment_metrics_context_.report(true);
7955
1
    tablet_metrics_context_.report(true);
7956
1
    return ret;
7957
1
}
7958
7959
// Scan and statistics partitions that need to be recycled
7960
0
int InstanceRecycler::scan_and_statistics_partitions() {
7961
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_partitions");
7962
7963
0
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
7964
0
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
7965
0
    std::string part_key0;
7966
0
    std::string part_key1;
7967
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
7968
7969
0
    recycle_partition_key(part_key_info0, &part_key0);
7970
0
    recycle_partition_key(part_key_info1, &part_key1);
7971
0
    auto handle_partition_kv = [&, this](std::string_view k, std::string_view v) -> int {
7972
0
        RecyclePartitionPB part_pb;
7973
0
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
7974
0
            return 0;
7975
0
        }
7976
0
        int64_t current_time = ::time(nullptr);
7977
0
        if (current_time <
7978
0
            calculate_partition_expired_time(instance_id_, part_pb, &earlest_ts)) { // not expired
7979
0
            return 0;
7980
0
        }
7981
        // decode partition_id
7982
0
        auto k1 = k;
7983
0
        k1.remove_prefix(1);
7984
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7985
0
        decode_key(&k1, &out);
7986
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
7987
0
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
7988
        // Change state to RECYCLING
7989
0
        std::unique_ptr<Transaction> txn;
7990
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7991
0
        if (err != TxnErrorCode::TXN_OK) {
7992
0
            return 0;
7993
0
        }
7994
0
        std::string val;
7995
0
        err = txn->get(k, &val);
7996
0
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7997
0
            return 0;
7998
0
        }
7999
0
        if (err != TxnErrorCode::TXN_OK) {
8000
0
            return 0;
8001
0
        }
8002
0
        part_pb.Clear();
8003
0
        if (!part_pb.ParseFromString(val)) {
8004
0
            return 0;
8005
0
        }
8006
        // Partitions with PREPARED state MUST have no data
8007
0
        bool is_empty_tablet = part_pb.state() == RecyclePartitionPB::PREPARED;
8008
0
        int ret = 0;
8009
0
        for (int64_t index_id : part_pb.index_id()) {
8010
0
            if (scan_tablets_and_statistics(part_pb.table_id(), index_id, metrics_context,
8011
0
                                            partition_id, is_empty_tablet) != 0) {
8012
0
                ret = 0;
8013
0
            }
8014
0
        }
8015
0
        metrics_context.total_need_recycle_num++;
8016
0
        return ret;
8017
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30scan_and_statistics_partitionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30scan_and_statistics_partitionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
8018
8019
0
    int ret = scan_and_recycle(part_key0, part_key1, std::move(handle_partition_kv));
8020
0
    metrics_context.report(true);
8021
0
    segment_metrics_context_.report(true);
8022
0
    tablet_metrics_context_.report(true);
8023
0
    return ret;
8024
0
}
8025
8026
// Scan and statistics rowsets that need to be recycled
8027
0
int InstanceRecycler::scan_and_statistics_rowsets() {
8028
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_rowsets");
8029
0
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
8030
0
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
8031
0
    std::string recyc_rs_key0;
8032
0
    std::string recyc_rs_key1;
8033
0
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
8034
0
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
8035
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8036
8037
0
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
8038
0
        RecycleRowsetPB rowset;
8039
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8040
0
            return 0;
8041
0
        }
8042
0
        auto* rowset_meta = rowset.mutable_rowset_meta();
8043
0
        int64_t current_time = ::time(nullptr);
8044
0
        if (current_time <
8045
0
            calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts)) { // not expired
8046
0
            return 0;
8047
0
        }
8048
8049
0
        if (!rowset.has_type()) {
8050
0
            if (!rowset.has_resource_id()) [[unlikely]] {
8051
0
                return 0;
8052
0
            }
8053
0
            if (rowset.resource_id().empty()) [[unlikely]] {
8054
0
                return 0;
8055
0
            }
8056
0
            metrics_context.total_need_recycle_num++;
8057
0
            metrics_context.total_need_recycle_data_size += rowset.rowset_meta().total_disk_size();
8058
0
            segment_metrics_context_.total_need_recycle_num += rowset.rowset_meta().num_segments();
8059
0
            segment_metrics_context_.total_need_recycle_data_size +=
8060
0
                    rowset.rowset_meta().total_disk_size();
8061
0
            return 0;
8062
0
        }
8063
8064
0
        if (config::enable_mark_delete_rowset_before_recycle &&
8065
0
            rowset.type() == RecycleRowsetPB::PREPARE &&
8066
0
            (!rowset_meta->has_is_recycled() || !rowset_meta->is_recycled())) {
8067
0
            return 0;
8068
0
        }
8069
8070
0
        if (!rowset_meta->has_resource_id()) [[unlikely]] {
8071
0
            if (rowset.type() == RecycleRowsetPB::PREPARE || rowset_meta->num_segments() != 0) {
8072
0
                return 0;
8073
0
            }
8074
0
        }
8075
0
        metrics_context.total_need_recycle_num++;
8076
0
        metrics_context.total_need_recycle_data_size += rowset_meta->total_disk_size();
8077
0
        segment_metrics_context_.total_need_recycle_num += rowset_meta->num_segments();
8078
0
        segment_metrics_context_.total_need_recycle_data_size += rowset_meta->total_disk_size();
8079
0
        return 0;
8080
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler27scan_and_statistics_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
8081
0
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv));
8082
0
    metrics_context.report(true);
8083
0
    segment_metrics_context_.report(true);
8084
0
    return ret;
8085
0
}
8086
8087
// Scan and statistics tmp_rowsets that need to be recycled
8088
0
int InstanceRecycler::scan_and_statistics_tmp_rowsets() {
8089
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_tmp_rowsets");
8090
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
8091
0
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
8092
0
    std::string tmp_rs_key0;
8093
0
    std::string tmp_rs_key1;
8094
0
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
8095
0
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
8096
8097
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8098
8099
0
    auto handle_tmp_rowsets_kv = [&, this](std::string_view k, std::string_view v) -> int {
8100
0
        doris::RowsetMetaCloudPB rowset;
8101
0
        if (!rowset.ParseFromArray(v.data(), v.size())) {
8102
0
            return 0;
8103
0
        }
8104
0
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
8105
0
        int64_t current_time = ::time(nullptr);
8106
0
        if (current_time < expiration) {
8107
0
            return 0;
8108
0
        }
8109
8110
0
        DCHECK_GT(rowset.txn_id(), 0)
8111
0
                << "txn_id=" << rowset.txn_id() << " rowset=" << rowset.ShortDebugString();
8112
8113
0
        if (!rowset.has_is_recycled() || !rowset.is_recycled()) {
8114
0
            return 0;
8115
0
        }
8116
8117
0
        if (!rowset.has_resource_id()) {
8118
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
8119
0
                return 0;
8120
0
            }
8121
0
            return 0;
8122
0
        }
8123
8124
0
        metrics_context.total_need_recycle_num++;
8125
0
        metrics_context.total_need_recycle_data_size += rowset.total_disk_size();
8126
0
        segment_metrics_context_.total_need_recycle_data_size += rowset.total_disk_size();
8127
0
        segment_metrics_context_.total_need_recycle_num += rowset.num_segments();
8128
0
        return 0;
8129
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler31scan_and_statistics_tmp_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler31scan_and_statistics_tmp_rowsetsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
8130
0
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_tmp_rowsets_kv));
8131
0
    metrics_context.report(true);
8132
0
    segment_metrics_context_.report(true);
8133
0
    return ret;
8134
0
}
8135
8136
// Scan and statistics abort_timeout_txn that need to be recycled
8137
0
int InstanceRecycler::scan_and_statistics_abort_timeout_txn() {
8138
0
    RecyclerMetricsContext metrics_context(instance_id_, "abort_timeout_txn");
8139
8140
0
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
8141
0
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8142
0
    std::string begin_txn_running_key;
8143
0
    std::string end_txn_running_key;
8144
0
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
8145
0
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
8146
8147
0
    int64_t current_time =
8148
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8149
8150
0
    auto handle_abort_timeout_txn_kv = [&metrics_context, &current_time, this](
8151
0
                                               std::string_view k, std::string_view v) -> int {
8152
0
        std::unique_ptr<Transaction> txn;
8153
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8154
0
        if (err != TxnErrorCode::TXN_OK) {
8155
0
            return 0;
8156
0
        }
8157
0
        std::string_view k1 = k;
8158
0
        k1.remove_prefix(1);
8159
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8160
0
        if (decode_key(&k1, &out) != 0) {
8161
0
            return 0;
8162
0
        }
8163
0
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
8164
0
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
8165
        // Update txn_info
8166
0
        std::string txn_inf_key, txn_inf_val;
8167
0
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
8168
0
        err = txn->get(txn_inf_key, &txn_inf_val);
8169
0
        if (err != TxnErrorCode::TXN_OK) {
8170
0
            return 0;
8171
0
        }
8172
0
        TxnInfoPB txn_info;
8173
0
        if (!txn_info.ParseFromString(txn_inf_val)) {
8174
0
            return 0;
8175
0
        }
8176
8177
0
        if (TxnStatusPB::TXN_STATUS_COMMITTED != txn_info.status()) {
8178
0
            TxnRunningPB txn_running_pb;
8179
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
8180
0
                return 0;
8181
0
            }
8182
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
8183
0
                return 0;
8184
0
            }
8185
0
            metrics_context.total_need_recycle_num++;
8186
0
        }
8187
0
        return 0;
8188
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_abort_timeout_txnEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_abort_timeout_txnEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
8189
8190
0
    int ret = scan_and_recycle(begin_txn_running_key, end_txn_running_key,
8191
0
                               std::move(handle_abort_timeout_txn_kv));
8192
0
    metrics_context.report(true);
8193
0
    return ret;
8194
0
}
8195
8196
// Scan and statistics expired_txn_label that need to be recycled
8197
0
int InstanceRecycler::scan_and_statistics_expired_txn_label() {
8198
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_txn_label");
8199
8200
0
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
8201
0
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
8202
0
    std::string begin_recycle_txn_key;
8203
0
    std::string end_recycle_txn_key;
8204
0
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
8205
0
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
8206
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8207
0
    int64_t current_time_ms =
8208
0
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8209
8210
    // for calculate the total num or bytes of recyled objects
8211
0
    auto handle_expired_txn_label_kv = [&, this](std::string_view k, std::string_view v) -> int {
8212
0
        RecycleTxnPB recycle_txn_pb;
8213
0
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
8214
0
            return 0;
8215
0
        }
8216
0
        if ((config::force_immediate_recycle) ||
8217
0
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
8218
0
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
8219
0
             current_time_ms)) {
8220
0
            metrics_context.total_need_recycle_num++;
8221
0
        }
8222
0
        return 0;
8223
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_expired_txn_labelEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler37scan_and_statistics_expired_txn_labelEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
8224
8225
0
    int ret = scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
8226
0
                               std::move(handle_expired_txn_label_kv));
8227
0
    metrics_context.report(true);
8228
0
    return ret;
8229
0
}
8230
8231
// Scan and statistics copy_jobs that need to be recycled
8232
0
int InstanceRecycler::scan_and_statistics_copy_jobs() {
8233
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_copy_jobs");
8234
0
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
8235
0
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
8236
0
    std::string key0;
8237
0
    std::string key1;
8238
0
    copy_job_key(key_info0, &key0);
8239
0
    copy_job_key(key_info1, &key1);
8240
8241
    // for calculate the total num or bytes of recyled objects
8242
0
    auto scan_and_statistics = [&metrics_context](std::string_view k, std::string_view v) -> int {
8243
0
        CopyJobPB copy_job;
8244
0
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
8245
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
8246
0
            return 0;
8247
0
        }
8248
8249
0
        if (copy_job.job_status() == CopyJobPB::FINISH) {
8250
0
            if (copy_job.stage_type() == StagePB::EXTERNAL) {
8251
0
                int64_t current_time =
8252
0
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8253
0
                if (copy_job.finish_time_ms() > 0) {
8254
0
                    if (!config::force_immediate_recycle &&
8255
0
                        current_time < copy_job.finish_time_ms() +
8256
0
                                               config::copy_job_max_retention_second * 1000) {
8257
0
                        return 0;
8258
0
                    }
8259
0
                } else {
8260
0
                    if (!config::force_immediate_recycle &&
8261
0
                        current_time < copy_job.start_time_ms() +
8262
0
                                               config::copy_job_max_retention_second * 1000) {
8263
0
                        return 0;
8264
0
                    }
8265
0
                }
8266
0
            }
8267
0
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
8268
0
            int64_t current_time =
8269
0
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
8270
0
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
8271
0
                return 0;
8272
0
            }
8273
0
        }
8274
0
        metrics_context.total_need_recycle_num++;
8275
0
        return 0;
8276
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29scan_and_statistics_copy_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29scan_and_statistics_copy_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
8277
8278
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8279
0
    metrics_context.report(true);
8280
0
    return ret;
8281
0
}
8282
8283
// Scan and statistics stage that need to be recycled
8284
0
int InstanceRecycler::scan_and_statistics_stage() {
8285
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stage");
8286
0
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
8287
0
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
8288
0
    std::string key0 = recycle_stage_key(key_info0);
8289
0
    std::string key1 = recycle_stage_key(key_info1);
8290
8291
    // for calculate the total num or bytes of recyled objects
8292
0
    auto scan_and_statistics = [&metrics_context, this](std::string_view k,
8293
0
                                                        std::string_view v) -> int {
8294
0
        RecycleStagePB recycle_stage;
8295
0
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
8296
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
8297
0
            return 0;
8298
0
        }
8299
8300
0
        int idx = stoi(recycle_stage.stage().obj_info().id());
8301
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
8302
0
            LOG(WARNING) << "invalid idx: " << idx;
8303
0
            return 0;
8304
0
        }
8305
8306
0
        std::shared_ptr<StorageVaultAccessor> accessor;
8307
0
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
8308
0
                [&] {
8309
0
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
8310
0
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8311
0
                    if (!s3_conf) {
8312
0
                        return 0;
8313
0
                    }
8314
8315
0
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
8316
0
                    std::shared_ptr<S3Accessor> s3_accessor;
8317
0
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
8318
0
                    if (ret != 0) {
8319
0
                        return 0;
8320
0
                    }
8321
8322
0
                    accessor = std::move(s3_accessor);
8323
0
                    return 0;
8324
0
                }(),
8325
0
                "recycle_stage:get_accessor", &accessor);
8326
8327
0
        if (ret != 0) {
8328
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
8329
0
            return 0;
8330
0
        }
8331
8332
0
        metrics_context.total_need_recycle_num++;
8333
0
        return 0;
8334
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25scan_and_statistics_stageEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25scan_and_statistics_stageEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
8335
8336
0
    int ret = scan_and_recycle(key0, key1, std::move(scan_and_statistics));
8337
0
    metrics_context.report(true);
8338
0
    return ret;
8339
0
}
8340
8341
// Scan and statistics expired_stage_objects that need to be recycled
8342
0
int InstanceRecycler::scan_and_statistics_expired_stage_objects() {
8343
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
8344
8345
    // for calculate the total num or bytes of recyled objects
8346
0
    auto scan_and_statistics = [&metrics_context, this]() {
8347
0
        for (const auto& stage : instance_info_.stages()) {
8348
0
            if (stopped()) {
8349
0
                break;
8350
0
            }
8351
0
            if (stage.type() == StagePB::EXTERNAL) {
8352
0
                continue;
8353
0
            }
8354
0
            int idx = stoi(stage.obj_info().id());
8355
0
            if (idx > instance_info_.obj_info().size() || idx < 1) {
8356
0
                continue;
8357
0
            }
8358
0
            const auto& old_obj = instance_info_.obj_info()[idx - 1];
8359
0
            auto s3_conf = S3Conf::from_obj_store_info(old_obj);
8360
0
            if (!s3_conf) {
8361
0
                continue;
8362
0
            }
8363
0
            s3_conf->prefix = stage.obj_info().prefix();
8364
0
            std::shared_ptr<S3Accessor> accessor;
8365
0
            int ret1 = S3Accessor::create(*s3_conf, &accessor);
8366
0
            if (ret1 != 0) {
8367
0
                continue;
8368
0
            }
8369
0
            if (s3_conf->prefix.find("/stage/") == std::string::npos) {
8370
0
                continue;
8371
0
            }
8372
0
            metrics_context.total_need_recycle_num++;
8373
0
        }
8374
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler41scan_and_statistics_expired_stage_objectsEvENK3$_0clEv
8375
8376
0
    scan_and_statistics();
8377
0
    metrics_context.report(true);
8378
0
    return 0;
8379
0
}
8380
8381
// Scan and statistics versions that need to be recycled
8382
0
int InstanceRecycler::scan_and_statistics_versions() {
8383
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
8384
0
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
8385
0
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
8386
8387
0
    int64_t last_scanned_table_id = 0;
8388
0
    bool is_recycled = false; // Is last scanned kv recycled
8389
    // for calculate the total num or bytes of recyled objects
8390
0
    auto scan_and_statistics = [&metrics_context, &last_scanned_table_id, &is_recycled, this](
8391
0
                                       std::string_view k, std::string_view) {
8392
0
        auto k1 = k;
8393
0
        k1.remove_prefix(1);
8394
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
8395
0
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
8396
0
        decode_key(&k1, &out);
8397
0
        DCHECK_EQ(out.size(), 6) << k;
8398
0
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
8399
0
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
8400
0
            metrics_context.total_need_recycle_num +=
8401
0
                    is_recycled; // Version kv of this table has been recycled
8402
0
            return 0;
8403
0
        }
8404
0
        last_scanned_table_id = table_id;
8405
0
        is_recycled = false;
8406
0
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
8407
0
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
8408
0
        std::unique_ptr<Transaction> txn;
8409
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8410
0
        if (err != TxnErrorCode::TXN_OK) {
8411
0
            return 0;
8412
0
        }
8413
0
        std::unique_ptr<RangeGetIterator> iter;
8414
0
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
8415
0
        if (err != TxnErrorCode::TXN_OK) {
8416
0
            return 0;
8417
0
        }
8418
0
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
8419
0
            return 0;
8420
0
        }
8421
0
        metrics_context.total_need_recycle_num++;
8422
0
        is_recycled = true;
8423
0
        return 0;
8424
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler28scan_and_statistics_versionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler28scan_and_statistics_versionsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
8425
8426
0
    int ret = scan_and_recycle(version_key_begin, version_key_end, std::move(scan_and_statistics));
8427
0
    metrics_context.report(true);
8428
0
    return ret;
8429
0
}
8430
8431
// Scan and statistics restore jobs that need to be recycled
8432
0
int InstanceRecycler::scan_and_statistics_restore_jobs() {
8433
0
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_restore_jobs");
8434
0
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
8435
0
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
8436
0
    std::string restore_job_key0;
8437
0
    std::string restore_job_key1;
8438
0
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
8439
0
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
8440
8441
0
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
8442
8443
    // for calculate the total num or bytes of recyled objects
8444
0
    auto scan_and_statistics = [&](std::string_view k, std::string_view v) -> int {
8445
0
        RestoreJobCloudPB restore_job_pb;
8446
0
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
8447
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
8448
0
            return 0;
8449
0
        }
8450
0
        int64_t expiration =
8451
0
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
8452
0
        int64_t current_time = ::time(nullptr);
8453
0
        if (current_time < expiration) { // not expired
8454
0
            return 0;
8455
0
        }
8456
0
        metrics_context.total_need_recycle_num++;
8457
0
        if (restore_job_pb.need_recycle_data()) {
8458
0
            scan_tablet_and_statistics(restore_job_pb.tablet_id(), metrics_context);
8459
0
        }
8460
0
        return 0;
8461
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler32scan_and_statistics_restore_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler32scan_and_statistics_restore_jobsEvENK3$_0clESt17basic_string_viewIcSt11char_traitsIcEES6_
8462
8463
0
    int ret = scan_and_recycle(restore_job_key0, restore_job_key1, std::move(scan_and_statistics));
8464
0
    metrics_context.report(true);
8465
0
    return ret;
8466
0
}
8467
8468
3
void InstanceRecycler::scan_and_statistics_operation_logs() {
8469
3
    if (!should_recycle_versioned_keys()) {
8470
0
        return;
8471
0
    }
8472
8473
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_operation_logs");
8474
8475
3
    OperationLogRecycleChecker recycle_checker(instance_id_, txn_kv_.get(), instance_info_);
8476
3
    if (recycle_checker.init() != 0) {
8477
0
        return;
8478
0
    }
8479
8480
3
    std::string log_key_prefix = versioned::log_key(instance_id_);
8481
3
    std::string begin_key = encode_versioned_key(log_key_prefix, Versionstamp::min());
8482
3
    std::string end_key = encode_versioned_key(log_key_prefix, Versionstamp::max());
8483
8484
3
    std::unique_ptr<BlobIterator> iter = blob_get_range(txn_kv_, begin_key, end_key);
8485
8
    for (; iter->valid(); iter->next()) {
8486
5
        OperationLogPB operation_log;
8487
5
        if (!iter->parse_value(&operation_log)) {
8488
0
            continue;
8489
0
        }
8490
8491
5
        std::string_view key = iter->key();
8492
5
        Versionstamp log_versionstamp;
8493
5
        if (!decode_versioned_key(&key, &log_versionstamp)) {
8494
0
            continue;
8495
0
        }
8496
8497
5
        OperationLogReferenceInfo ref_info;
8498
5
        if (recycle_checker.can_recycle(log_versionstamp, operation_log.min_timestamp(),
8499
5
                                        &ref_info)) {
8500
4
            metrics_context.total_need_recycle_num++;
8501
4
            metrics_context.total_need_recycle_data_size += operation_log.ByteSizeLong();
8502
4
        }
8503
5
    }
8504
8505
3
    metrics_context.report(true);
8506
3
}
8507
8508
int InstanceRecycler::classify_rowset_task_by_ref_count(
8509
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
8510
60
    constexpr int MAX_RETRY = 10;
8511
60
    const auto& rowset_meta = task.rowset_meta;
8512
60
    int64_t tablet_id = rowset_meta.tablet_id();
8513
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
8514
60
    std::string_view reference_instance_id = instance_id_;
8515
60
    if (rowset_meta.has_reference_instance_id()) {
8516
5
        reference_instance_id = rowset_meta.reference_instance_id();
8517
5
    }
8518
8519
61
    for (int i = 0; i < MAX_RETRY; ++i) {
8520
61
        std::unique_ptr<Transaction> txn;
8521
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8522
61
        if (err != TxnErrorCode::TXN_OK) {
8523
0
            LOG_WARNING("failed to create txn when classifying rowset task")
8524
0
                    .tag("instance_id", instance_id_)
8525
0
                    .tag("tablet_id", tablet_id)
8526
0
                    .tag("rowset_id", rowset_id)
8527
0
                    .tag("err", err);
8528
0
            return -1;
8529
0
        }
8530
8531
61
        std::string rowset_ref_count_key =
8532
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
8533
61
        task.rowset_ref_count_key = rowset_ref_count_key;
8534
8535
61
        int64_t ref_count = 0;
8536
61
        {
8537
61
            std::string value;
8538
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
8539
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
8540
0
                ref_count = 1;
8541
61
            } else if (err != TxnErrorCode::TXN_OK) {
8542
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
8543
0
                        .tag("instance_id", instance_id_)
8544
0
                        .tag("tablet_id", tablet_id)
8545
0
                        .tag("rowset_id", rowset_id)
8546
0
                        .tag("err", err);
8547
0
                return -1;
8548
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
8549
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
8550
0
                        .tag("instance_id", instance_id_)
8551
0
                        .tag("tablet_id", tablet_id)
8552
0
                        .tag("rowset_id", rowset_id)
8553
0
                        .tag("value", hex(value));
8554
0
                return -1;
8555
0
            }
8556
61
        }
8557
8558
61
        if (ref_count > 1) {
8559
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
8560
12
            txn->atomic_add(rowset_ref_count_key, -1);
8561
12
            LOG_INFO("decrease rowset data ref count in classification phase")
8562
12
                    .tag("instance_id", instance_id_)
8563
12
                    .tag("tablet_id", tablet_id)
8564
12
                    .tag("rowset_id", rowset_id)
8565
12
                    .tag("ref_count", ref_count - 1)
8566
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
8567
8568
12
            if (!task.recycle_rowset_key.empty()) {
8569
0
                txn->remove(task.recycle_rowset_key);
8570
0
                LOG_INFO("remove recycle rowset key in classification phase")
8571
0
                        .tag("key", hex(task.recycle_rowset_key));
8572
0
            }
8573
12
            if (!task.non_versioned_rowset_key.empty()) {
8574
12
                txn->remove(task.non_versioned_rowset_key);
8575
12
                LOG_INFO("remove non versioned rowset key in classification phase")
8576
12
                        .tag("key", hex(task.non_versioned_rowset_key));
8577
12
            }
8578
8579
12
            err = txn->commit();
8580
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
8581
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
8582
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
8583
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
8584
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
8585
1
                continue;
8586
11
            } else if (err != TxnErrorCode::TXN_OK) {
8587
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
8588
0
                        .tag("instance_id", instance_id_)
8589
0
                        .tag("tablet_id", tablet_id)
8590
0
                        .tag("rowset_id", rowset_id)
8591
0
                        .tag("err", err);
8592
0
                return -1;
8593
0
            }
8594
11
            return 1; // handled, not added to batch delete
8595
49
        } else {
8596
            // ref_count == 1: Add to batch delete plan without modifying any KV.
8597
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
8598
49
            LOG_INFO("add rowset to batch delete plan")
8599
49
                    .tag("instance_id", instance_id_)
8600
49
                    .tag("tablet_id", tablet_id)
8601
49
                    .tag("rowset_id", rowset_id)
8602
49
                    .tag("resource_id", rowset_meta.resource_id())
8603
49
                    .tag("ref_count", ref_count);
8604
8605
49
            batch_delete_tasks.push_back(std::move(task));
8606
49
            return 0; // added to batch delete
8607
49
        }
8608
61
    }
8609
8610
0
    LOG_WARNING("failed to classify rowset task after retry")
8611
0
            .tag("instance_id", instance_id_)
8612
0
            .tag("tablet_id", tablet_id)
8613
0
            .tag("rowset_id", rowset_id)
8614
0
            .tag("retry", MAX_RETRY);
8615
0
    return -1;
8616
60
}
8617
8618
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
8619
10
    int ret = 0;
8620
49
    for (const auto& task : tasks) {
8621
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
8622
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
8623
8624
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
8625
        // so we don't need to call it again here.
8626
8627
        // Remove all metadata keys in one transaction
8628
49
        std::unique_ptr<Transaction> txn;
8629
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
8630
49
        if (err != TxnErrorCode::TXN_OK) {
8631
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
8632
0
                    .tag("instance_id", instance_id_)
8633
0
                    .tag("tablet_id", tablet_id)
8634
0
                    .tag("rowset_id", rowset_id)
8635
0
                    .tag("err", err);
8636
0
            ret = -1;
8637
0
            continue;
8638
0
        }
8639
8640
49
        std::string_view reference_instance_id = instance_id_;
8641
49
        if (task.rowset_meta.has_reference_instance_id()) {
8642
0
            reference_instance_id = task.rowset_meta.reference_instance_id();
8643
0
        }
8644
8645
49
        txn->remove(task.rowset_ref_count_key);
8646
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
8647
49
                .tag("instance_id", instance_id_)
8648
49
                .tag("tablet_id", tablet_id)
8649
49
                .tag("rowset_id", rowset_id)
8650
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
8651
8652
49
        std::string dbm_start_key =
8653
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
8654
49
        std::string dbm_end_key = meta_delete_bitmap_key(
8655
49
                {reference_instance_id, tablet_id, rowset_id, std::numeric_limits<int64_t>::max(),
8656
49
                 std::numeric_limits<int64_t>::max()});
8657
49
        txn->remove(dbm_start_key, dbm_end_key);
8658
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
8659
49
                .tag("instance_id", instance_id_)
8660
49
                .tag("tablet_id", tablet_id)
8661
49
                .tag("rowset_id", rowset_id)
8662
49
                .tag("begin", hex(dbm_start_key))
8663
49
                .tag("end", hex(dbm_end_key));
8664
8665
49
        std::string versioned_dbm_start_key =
8666
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
8667
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
8668
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
8669
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
8670
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
8671
49
                .tag("instance_id", instance_id_)
8672
49
                .tag("tablet_id", tablet_id)
8673
49
                .tag("rowset_id", rowset_id)
8674
49
                .tag("begin", hex(versioned_dbm_start_key))
8675
49
                .tag("end", hex(versioned_dbm_end_key));
8676
8677
        // Remove versioned meta rowset key
8678
49
        if (!task.versioned_rowset_key.empty()) {
8679
49
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
8680
49
                                                          task.versionstamp);
8681
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
8682
49
                    .tag("instance_id", instance_id_)
8683
49
                    .tag("tablet_id", tablet_id)
8684
49
                    .tag("rowset_id", rowset_id)
8685
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
8686
49
        }
8687
8688
49
        if (!task.non_versioned_rowset_key.empty()) {
8689
49
            txn->remove(task.non_versioned_rowset_key);
8690
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
8691
49
                    .tag("instance_id", instance_id_)
8692
49
                    .tag("tablet_id", tablet_id)
8693
49
                    .tag("rowset_id", rowset_id)
8694
49
                    .tag("key", hex(task.non_versioned_rowset_key));
8695
49
        }
8696
8697
        // Remove recycle_rowset_key last to ensure retry safety:
8698
        // if cleanup fails, this key remains and triggers next round retry.
8699
49
        if (!task.recycle_rowset_key.empty()) {
8700
0
            txn->remove(task.recycle_rowset_key);
8701
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
8702
0
                    .tag("instance_id", instance_id_)
8703
0
                    .tag("tablet_id", tablet_id)
8704
0
                    .tag("rowset_id", rowset_id)
8705
0
                    .tag("key", hex(task.recycle_rowset_key));
8706
0
        }
8707
8708
49
        err = txn->commit();
8709
49
        if (err != TxnErrorCode::TXN_OK) {
8710
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8711
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8712
0
                    .tag("instance_id", instance_id_)
8713
0
                    .tag("tablet_id", tablet_id)
8714
0
                    .tag("rowset_id", rowset_id)
8715
0
                    .tag("err", err);
8716
0
            ret = -1;
8717
0
            continue;
8718
0
        }
8719
8720
49
        LOG_INFO("cleanup rowset metadata success")
8721
49
                .tag("instance_id", instance_id_)
8722
49
                .tag("tablet_id", tablet_id)
8723
49
                .tag("rowset_id", rowset_id);
8724
49
    }
8725
10
    return ret;
8726
10
}
8727
8728
} // namespace doris::cloud