Coverage Report

Created: 2026-09-20 15:42

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
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
868k
    const auto& locations = rowset.packed_slice_locations();
106
868k
    auto it = locations.find(path);
107
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
868k
           !it->second.packed_file_path().empty();
109
868k
}
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
868k
bool is_packed_slice_path(const doris::RowsetMetaCloudPB& rowset, const std::string& path) {
105
868k
    const auto& locations = rowset.packed_slice_locations();
106
868k
    auto it = locations.find(path);
107
868k
    return it != locations.end() && it->second.has_packed_file_path() &&
108
868k
           !it->second.packed_file_path().empty();
109
868k
}
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
376
                   std::unique_ptr<RangeGetIterator>& it) {
150
376
    std::unique_ptr<Transaction> txn;
151
376
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
376
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
376
    switch (txn->get(begin, end, &it, true)) {
156
377
    case TxnErrorCode::TXN_OK:
157
377
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
376
    };
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
337
                   std::unique_ptr<RangeGetIterator>& it) {
150
337
    std::unique_ptr<Transaction> txn;
151
337
    TxnErrorCode err = txn_kv->create_txn(&txn);
152
337
    if (err != TxnErrorCode::TXN_OK) {
153
0
        return -1;
154
0
    }
155
337
    switch (txn->get(begin, end, &it, true)) {
156
338
    case TxnErrorCode::TXN_OK:
157
338
        return 0;
158
0
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
159
0
        return 1;
160
0
    default:
161
0
        return -1;
162
337
    };
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
694
    while (!stopped()) {
331
689
        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
685
        } else {
354
685
            LOG(WARNING) << "Skip recycler since enable_recycler is false";
355
685
        }
356
689
        {
357
689
            std::unique_lock lock(mtx_);
358
689
            notifier_.wait_for(lock, std::chrono::seconds(config::recycle_interval_seconds),
359
1.37k
                               [&]() { return stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler25instance_scanner_callbackEvENK3$_1clEv
Line
Count
Source
359
1.37k
                               [&]() { return stopped(); });
360
689
        }
361
689
    }
362
5
}
363
364
9
void Recycler::recycle_callback() {
365
40
    while (!stopped()) {
366
39
        InstanceInfoPB instance;
367
39
        {
368
39
            std::unique_lock lock(mtx_);
369
39
            pending_instance_cond_.wait(
370
53
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud8Recycler16recycle_callbackEvENK3$_0clEv
Line
Count
Source
370
53
                    lock, [&]() { return !pending_instance_queue_.empty() || stopped(); });
371
39
            if (stopped()) {
372
8
                return;
373
8
            }
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
183
            : 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
504
            LOG(WARNING) << "failed to get schema, err=" << err;
613
504
            return static_cast<int>(err);
614
504
        }
615
5.03k
        doris::TabletSchemaCloudPB schema;
616
5.03k
        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.03k
        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.03k
        insert(index_id, schema_version, res);
634
5.03k
        return 0;
635
5.03k
    }
636
637
    // Empty `ids` means this schema has no inverted index
638
5.03k
    void insert(int64_t index_id, int32_t schema_version, const InvertedIndexInfo& index_info) {
639
5.03k
        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.03k
    }
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
183
        : txn_kv_(std::move(txn_kv)),
674
183
          instance_id_(instance.instance_id()),
675
183
          instance_info_(instance),
676
183
          inverted_index_id_cache_(std::make_unique<InvertedIndexIdCache>(instance_id_, txn_kv_)),
677
183
          _thread_pool_group(std::move(thread_pool_group)),
678
183
          txn_lazy_committer_(std::move(txn_lazy_committer)),
679
183
          delete_bitmap_lock_white_list_(std::make_shared<DeleteBitmapLockWhiteList>()),
680
183
          resource_mgr_(std::make_shared<ResourceManager>(txn_kv_)),
681
183
          tablet_metrics_context_(instance_id_),
682
183
          segment_metrics_context_(instance_id_) {
683
183
    delete_bitmap_lock_white_list_->init();
684
183
    resource_mgr_->init();
685
686
183
    snapshot_manager_ = create_snapshot_manager(txn_kv_);
687
688
    // Since the recycler's resource manager could not be notified when instance info changes,
689
    // we need to refresh the instance info here to ensure the resource manager has the latest info.
690
183
    txn_lazy_committer_->resource_manager()->refresh_instance(instance_id_, instance);
691
183
};
692
693
183
InstanceRecycler::~InstanceRecycler() = default;
694
695
152
int InstanceRecycler::init_obj_store_accessors() {
696
152
    for (const auto& obj_info : instance_info_.obj_info()) {
697
104
#ifdef UNIT_TEST
698
104
        auto accessor = std::make_shared<MockAccessor>();
699
#else
700
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
701
        if (!s3_conf) {
702
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
703
            return -1;
704
        }
705
706
        std::shared_ptr<S3Accessor> accessor;
707
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
708
        if (ret != 0) {
709
            LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
710
                         << " resource_id=" << obj_info.id();
711
            return ret;
712
        }
713
#endif
714
104
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
715
104
    }
716
717
152
    return 0;
718
152
}
719
720
152
int InstanceRecycler::init_storage_vault_accessors() {
721
152
    if (instance_info_.resource_ids().empty()) {
722
145
        return 0;
723
145
    }
724
725
7
    FullRangeGetOptions opts(txn_kv_);
726
7
    opts.prefetch = true;
727
7
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
728
7
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
729
730
25
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
731
18
        auto [k, v] = *kv;
732
18
        StorageVaultPB vault;
733
18
        if (!vault.ParseFromArray(v.data(), v.size())) {
734
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
735
0
            return -1;
736
0
        }
737
18
        std::string recycler_storage_vault_white_list = accumulate(
738
18
                config::recycler_storage_vault_white_list.begin(),
739
18
                config::recycler_storage_vault_white_list.end(), std::string(),
740
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
740
24
                [](std::string a, std::string b) { return a + (a.empty() ? "" : ",") + b; });
741
18
        LOG_INFO("config::recycler_storage_vault_white_list")
742
18
                .tag("", recycler_storage_vault_white_list);
743
18
        if (!config::recycler_storage_vault_white_list.empty()) {
744
8
            if (auto it = std::find(config::recycler_storage_vault_white_list.begin(),
745
8
                                    config::recycler_storage_vault_white_list.end(), vault.name());
746
8
                it == config::recycler_storage_vault_white_list.end()) {
747
2
                LOG_WARNING(
748
2
                        "failed to init accessor for vault because this vault is not in "
749
2
                        "config::recycler_storage_vault_white_list. ")
750
2
                        .tag(" vault name:", vault.name())
751
2
                        .tag(" config::recycler_storage_vault_white_list:",
752
2
                             recycler_storage_vault_white_list);
753
2
                continue;
754
2
            }
755
8
        }
756
18
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
757
16
                                 &accessor_map_, &vault);
758
16
        if (vault.has_hdfs_info()) {
759
9
#ifdef ENABLE_HDFS_STORAGE_VAULT
760
9
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
761
9
            int ret = accessor->init();
762
9
            if (ret != 0) {
763
4
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
764
4
                             << " resource_id=" << vault.id() << " name=" << vault.name()
765
4
                             << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
766
4
                continue;
767
4
            }
768
9
            LOG(INFO) << "succeed to init hdfs accessor. instance_id=" << instance_id_
769
5
                      << " resource_id=" << vault.id() << " name=" << vault.name()
770
5
                      << " hdfs_vault=" << vault.hdfs_info().ShortDebugString();
771
5
            accessor_map_.emplace(vault.id(), std::move(accessor));
772
#else
773
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
774
                       << "but HDFS storage vaults were detected";
775
#endif
776
7
        } else if (vault.has_obj_info()) {
777
            // TODO: Propagate object storage session tokens to Recycler in a follow-up PR.
778
7
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
779
7
            if (!s3_conf) {
780
1
                LOG(WARNING) << "failed to init object accessor, invalid conf, instance_id="
781
1
                             << instance_id_ << " s3_vault=" << vault.obj_info().ShortDebugString();
782
1
                continue;
783
1
            }
784
785
6
            std::shared_ptr<S3Accessor> accessor;
786
6
            int ret = S3Accessor::create(*s3_conf, &accessor);
787
6
            if (ret != 0) {
788
0
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
789
0
                             << " resource_id=" << vault.id() << " name=" << vault.name()
790
0
                             << " ret=" << ret
791
0
                             << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
792
0
                continue;
793
0
            }
794
6
            LOG(INFO) << "succeed to init s3 accessor. instance_id=" << instance_id_
795
6
                      << " resource_id=" << vault.id() << " name=" << vault.name() << " ret=" << ret
796
6
                      << " s3_vault=" << encryt_sk(vault.obj_info().ShortDebugString());
797
6
            accessor_map_.emplace(vault.id(), std::move(accessor));
798
6
        }
799
16
    }
800
801
7
    if (!it->is_valid()) {
802
0
        LOG_WARNING("failed to get storage vault kv");
803
0
        return -1;
804
0
    }
805
806
7
    if (accessor_map_.empty()) {
807
1
        LOG(WARNING) << "no accessors for instance=" << instance_id_;
808
1
        return -2;
809
1
    }
810
6
    LOG_INFO("finish init instance recycler number_accessors={} instance=", accessor_map_.size(),
811
6
             instance_id_);
812
813
6
    return 0;
814
7
}
815
816
153
int InstanceRecycler::init() {
817
153
    if (instance_info_.status() == InstanceInfoPB::DELETED &&
818
153
        (instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING ||
819
4
         instance_info_.recycle_state() == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED)) {
820
1
        return 0;
821
1
    }
822
823
152
    int ret = init_obj_store_accessors();
824
152
    if (ret != 0) {
825
0
        return ret;
826
0
    }
827
828
152
    return init_storage_vault_accessors();
829
152
}
830
831
template <typename... Func>
832
120
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
120
    return [funcs...]() {
834
120
        return [](std::initializer_list<int> ret_vals) {
835
120
            int i = 0;
836
140
            for (int ret : ret_vals) {
837
140
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
140
            }
841
120
            return i;
842
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
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
20
            for (int ret : ret_vals) {
837
20
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
20
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESC_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
20
            for (int ret : ret_vals) {
837
20
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
20
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
recycler_test.cpp:_ZZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEvENKUlSt16initializer_listIiEE_clESB_
Line
Count
Source
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
0
                    i = ret;
839
0
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
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
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
recycler_test.cpp:_ZZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_ENKUlvE_clEv
Line
Count
Source
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
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
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_3EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_4ZNS2_10do_recycleEvE3$_5EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_6EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_7EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_8EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE3$_9ZNS2_10do_recycleEvE4$_10EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_11EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_12EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_13EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_14EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
recycler_test.cpp:_ZN5doris5cloud12task_wrapperIJZNS0_16InstanceRecycler10do_recycleEvE4$_15EEESt8functionIFivEEDpT_
Line
Count
Source
832
10
auto task_wrapper(Func... funcs) -> std::function<int()> {
833
10
    return [funcs...]() {
834
10
        return [](std::initializer_list<int> ret_vals) {
835
10
            int i = 0;
836
10
            for (int ret : ret_vals) {
837
10
                if (ret != 0) {
838
10
                    i = ret;
839
10
                }
840
10
            }
841
10
            return i;
842
10
        }({funcs()...});
843
10
    };
844
10
}
845
846
11
int InstanceRecycler::do_recycle() {
847
11
    const auto start_time = steady_clock::now();
848
11
    DORIS_CLOUD_DEFER {
849
11
        g_bvar_recycler_instance_current_round_elapsed_ms.put(
850
11
                {instance_id_},
851
11
                duration_cast<milliseconds>(steady_clock::now() - start_time).count());
852
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_0clEv
Line
Count
Source
848
11
    DORIS_CLOUD_DEFER {
849
11
        g_bvar_recycler_instance_current_round_elapsed_ms.put(
850
11
                {instance_id_},
851
11
                duration_cast<milliseconds>(steady_clock::now() - start_time).count());
852
11
    };
853
854
11
    TEST_SYNC_POINT("InstanceRecycler.do_recycle");
855
11
    if (instance_info_.status() == InstanceInfoPB::DELETED) {
856
1
        int res = recycle_cluster_snapshots();
857
1
        if (res != 0) {
858
0
            return -1;
859
0
        }
860
1
        return recycle_deleted_instance();
861
10
    } else if (instance_info_.status() == InstanceInfoPB::NORMAL) {
862
10
        SyncExecutor<int> sync_executor(_thread_pool_group.group_recycle_function_pool,
863
10
                                        fmt::format("instance id {}", instance_id_),
864
120
                                        [](int r) { return r != 0; });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_1clEi
Line
Count
Source
864
120
                                        [](int r) { return r != 0; });
865
10
        sync_executor
866
10
                .add(task_wrapper(
867
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_2clEv
Line
Count
Source
867
10
                        [this]() { return InstanceRecycler::recycle_cluster_snapshots(); }))
868
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
868
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_operation_logs(); }))
869
10
                .add(task_wrapper( // dropped table and dropped partition need to be recycled in series
870
                                   // becase they may both recycle the same set of tablets
871
                        // recycle dropped table or idexes(mv, rollup)
872
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_4clEv
Line
Count
Source
872
10
                        [this]() -> int { return InstanceRecycler::recycle_indexes(); },
873
                        // recycle dropped partitions
874
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_5clEv
Line
Count
Source
874
10
                        [this]() -> int { return InstanceRecycler::recycle_partitions(); }))
875
10
                .add(task_wrapper(
876
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_6clEv
Line
Count
Source
876
10
                        [this]() -> int { return InstanceRecycler::recycle_tmp_rowsets(); }))
877
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
877
10
                .add(task_wrapper([this]() -> int { return InstanceRecycler::recycle_rowsets(); }))
878
10
                .add(task_wrapper(
879
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_8clEv
Line
Count
Source
879
10
                        [this]() -> int { return InstanceRecycler::recycle_packed_files(); }))
880
10
                .add(task_wrapper(
881
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK3$_9clEv
Line
Count
Source
881
10
                        [this]() { return InstanceRecycler::abort_timeout_txn(); },
882
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_10clEv
Line
Count
Source
882
10
                        [this]() { return InstanceRecycler::recycle_expired_txn_label(); }))
883
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
883
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_copy_jobs(); }))
884
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
884
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_stage(); }))
885
10
                .add(task_wrapper(
886
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler10do_recycleEvENK4$_13clEv
Line
Count
Source
886
10
                        [this]() { return InstanceRecycler::recycle_expired_stage_objects(); }))
887
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
887
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_versions(); }))
888
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
888
10
                .add(task_wrapper([this]() { return InstanceRecycler::recycle_restore_jobs(); }));
889
10
        bool finished = true;
890
10
        std::vector<int> rets = sync_executor.when_all(&finished);
891
120
        for (int ret : rets) {
892
120
            if (ret != 0) {
893
0
                return ret;
894
0
            }
895
120
        }
896
10
        return finished ? 0 : -1;
897
10
    } else {
898
0
        LOG(WARNING) << "invalid instance status: " << instance_info_.status()
899
0
                     << " instance_id=" << instance_id_;
900
0
        return -1;
901
0
    }
902
11
}
903
904
/**
905
* 1. delete all remote data
906
* 2. delete all kv
907
* 3. remove instance kv depend on config::retain_deleted_instance_tombstone
908
*/
909
13
int InstanceRecycler::recycle_deleted_instance() {
910
13
    LOG_WARNING("begin to recycle deleted instance").tag("instance_id", instance_id_);
911
912
13
    int ret = 0;
913
13
    auto start_time = steady_clock::now();
914
13
    const auto recycle_state = instance_info_.recycle_state();
915
916
13
    if (config::retain_deleted_instance_tombstone &&
917
13
        recycle_state == InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
918
4
        return 0;
919
4
    }
920
921
9
    DORIS_CLOUD_DEFER {
922
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
923
9
        if (ret != 0) {
924
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
925
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
926
0
                         << "s, instance_id=" << instance_id_;
927
9
        } else if (recycle_state ==
928
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
929
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
930
0
                      << "s, instance_id=" << instance_id_;
931
9
        } else {
932
9
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
933
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
934
9
                      << "s, instance_id=" << instance_id_;
935
9
        }
936
9
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_deleted_instanceEvENK3$_0clEv
Line
Count
Source
921
9
    DORIS_CLOUD_DEFER {
922
9
        auto cost = duration<float>(steady_clock::now() - start_time).count();
923
9
        if (ret != 0) {
924
0
            LOG(WARNING) << "failed to recycle deleted instance, recycle_state="
925
0
                         << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
926
0
                         << "s, instance_id=" << instance_id_;
927
9
        } else if (recycle_state ==
928
9
                   InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
929
0
            LOG(INFO) << "successfully removed recycled instance key, cost=" << cost
930
0
                      << "s, instance_id=" << instance_id_;
931
9
        } else {
932
            LOG(INFO) << "finished recycle deleted instance step, recycle_state="
933
9
                      << InstanceRecycleState_Name(recycle_state) << ", cost=" << cost
934
9
                      << "s, instance_id=" << instance_id_;
935
9
        }
936
9
    };
937
938
9
    switch (recycle_state) {
939
6
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING:
940
6
        ret = recycle_deleted_instance_data();
941
6
        break;
942
3
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING:
943
3
        ret = recycle_deleted_instance_metadata();
944
3
        break;
945
0
    case InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED:
946
0
        ret = remove_instance_key();
947
0
        break;
948
0
    default:
949
0
        LOG_WARNING("invalid instance recycle state")
950
0
                .tag("instance_id", instance_id_)
951
0
                .tag("recycle_state", instance_info_.recycle_state());
952
0
        ret = -1;
953
0
        break;
954
9
    }
955
956
9
    return ret;
957
9
}
958
959
6
int InstanceRecycler::recycle_deleted_instance_data() {
960
6
    int ret = 0;
961
962
    // Step 1: Recycle tmp rowsets (contains ref count but txn is not committed)
963
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
964
6
        int res = recycle_tmp_rowsets();
965
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
966
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
967
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
968
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
969
            // and cannot be recycled.
970
0
            res = recycle_tmp_rowsets();
971
0
        }
972
6
        return res;
973
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_deleted_instance_dataEvENK3$_0clEv
Line
Count
Source
963
6
    auto recycle_tmp_rowsets_with_mark_delete_enabled = [&]() -> int {
964
6
        int res = recycle_tmp_rowsets();
965
6
        if (res == 0 && config::enable_mark_delete_rowset_before_recycle) {
966
            // If mark_delete_rowset_before_recycle is enabled, we will mark delete rowsets before recycling them,
967
            // so we need to recycle tmp rowsets again to make sure all rowsets in recycle space are marked for
968
            // deletion, otherwise we may meet some corner cases that some rowsets are not marked for deletion
969
            // and cannot be recycled.
970
0
            res = recycle_tmp_rowsets();
971
0
        }
972
6
        return res;
973
6
    };
974
975
6
    if (recycle_tmp_rowsets_with_mark_delete_enabled() != 0) {
976
0
        LOG_WARNING("failed to recycle tmp rowsets").tag("instance_id", instance_id_);
977
0
        return -1;
978
0
    }
979
980
    // Step 2: Recycle versioned rowsets in recycle space (already marked for deletion)
981
6
    if (recycle_versioned_rowsets() != 0) {
982
0
        LOG_WARNING("failed to recycle versioned rowsets").tag("instance_id", instance_id_);
983
0
        return -1;
984
0
    }
985
986
    // Step 3: Recycle operation logs (can recycle logs not referenced by snapshots)
987
6
    if (recycle_operation_logs() != 0) {
988
0
        LOG_WARNING("failed to recycle operation logs").tag("instance_id", instance_id_);
989
0
        return -1;
990
0
    }
991
992
    // Step 4: Check if there are still cluster snapshots
993
6
    bool has_snapshots = false;
994
6
    if (has_cluster_snapshots(&has_snapshots) != 0) {
995
0
        LOG(WARNING) << "check instance cluster snapshots failed, instance_id=" << instance_id_;
996
0
        return -1;
997
6
    } else if (has_snapshots) {
998
1
        LOG(INFO) << "instance has cluster snapshots, skip recycling, instance_id=" << instance_id_;
999
1
        return 0;
1000
1
    }
1001
1002
5
    bool snapshot_enabled = instance_info().has_snapshot_switch_status() &&
1003
5
                            instance_info().snapshot_switch_status() !=
1004
1
                                    SnapshotSwitchStatus::SNAPSHOT_SWITCH_DISABLED;
1005
5
    if (snapshot_enabled) {
1006
1
        bool has_unrecycled_rowsets = false;
1007
1
        if (recycle_ref_rowsets(&has_unrecycled_rowsets) != 0) {
1008
0
            LOG_WARNING("failed to recycle ref rowsets").tag("instance_id", instance_id_);
1009
0
            return -1;
1010
1
        } else if (has_unrecycled_rowsets) {
1011
0
            LOG_INFO("instance has referenced rowsets, skip recycling")
1012
0
                    .tag("instance_id", instance_id_);
1013
0
            return ret;
1014
0
        }
1015
4
    } else { // delete all remote data if snapshot is disabled
1016
4
        for (auto& [_, accessor] : accessor_map_) {
1017
4
            if (stopped()) {
1018
0
                return ret;
1019
0
            }
1020
1021
4
            LOG(INFO) << "begin to delete all objects in " << accessor->uri();
1022
4
            int del_ret = accessor->delete_all();
1023
4
            if (del_ret == 0) {
1024
4
                LOG(INFO) << "successfully delete all objects in " << accessor->uri();
1025
4
            } else if (del_ret != 1) { // no need to log, because S3Accessor has logged this error
1026
                // If `del_ret == 1`, it can be considered that the object data has been recycled by cloud platform,
1027
                // so the recycling has been successful.
1028
0
                ret = -1;
1029
0
            }
1030
4
        }
1031
1032
4
        if (ret != 0) {
1033
0
            LOG(WARNING) << "failed to delete all data of deleted instance=" << instance_id_;
1034
0
            return ret;
1035
0
        }
1036
4
    }
1037
1038
5
    if (update_instance_recycle_state(
1039
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING,
1040
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) != 0) {
1041
0
        return -1;
1042
0
    }
1043
1044
5
    return 0;
1045
5
}
1046
1047
7
int InstanceRecycler::recycle_deleted_instance_metadata() {
1048
    // Check successor instance, if exists, skip deleting kv because successor instance may still need the data in kv
1049
7
    if (instance_info_.has_successor_instance_id() &&
1050
7
        !instance_info_.successor_instance_id().empty()) {
1051
4
        std::string key = instance_key(instance_info_.successor_instance_id());
1052
4
        std::unique_ptr<Transaction> txn;
1053
4
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1054
4
        if (err != TxnErrorCode::TXN_OK) {
1055
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_
1056
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1057
0
                         << " err=" << err;
1058
0
            return -1;
1059
0
        }
1060
1061
4
        InstanceInfoPB successor_instance;
1062
4
        std::string value;
1063
4
        err = txn->get(key, &value);
1064
4
        if (err == TxnErrorCode::TXN_OK) {
1065
3
            InstanceInfoPB successor_instance;
1066
3
            if (!successor_instance.ParseFromString(value)) {
1067
0
                LOG(WARNING) << "failed to parse successor instance, instance_id=" << instance_id_
1068
0
                             << " successor_instance_id=" << instance_info_.successor_instance_id();
1069
0
                return -1;
1070
0
            }
1071
3
            if (!successor_instance.has_recycle_state() ||
1072
3
                successor_instance.recycle_state() !=
1073
2
                        InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1074
2
                LOG(INFO) << "instance successor has not completed recycling, skip deleting kv,"
1075
2
                          << " instance_id=" << instance_id_
1076
2
                          << " successor_instance_id=" << instance_info_.successor_instance_id()
1077
2
                          << " successor_status=" << successor_instance.status()
1078
2
                          << " successor_recycled_state=" << successor_instance.recycle_state();
1079
2
                return 0;
1080
2
            }
1081
3
        } else if (err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1082
0
            LOG(WARNING) << "failed to get successor instance, instance_id=" << instance_id_
1083
0
                         << " successor_instance_id=" << instance_info_.successor_instance_id()
1084
0
                         << " err=" << err;
1085
0
            return -1;
1086
0
        }
1087
4
    }
1088
1089
    // delete all kv
1090
5
    std::unique_ptr<Transaction> txn;
1091
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1092
5
    if (err != TxnErrorCode::TXN_OK) {
1093
0
        LOG(WARNING) << "failed to create txn";
1094
0
        return -1;
1095
0
    }
1096
5
    LOG(INFO) << "begin to delete all kv, instance_id=" << instance_id_;
1097
    // delete kv before deleting objects to prevent the checker from misjudging data loss
1098
5
    std::string start_txn_key = txn_key_prefix(instance_id_);
1099
5
    std::string end_txn_key = txn_key_prefix(instance_id_ + '\x00');
1100
5
    txn->remove(start_txn_key, end_txn_key);
1101
5
    std::string start_version_key = version_key_prefix(instance_id_);
1102
5
    std::string end_version_key = version_key_prefix(instance_id_ + '\x00');
1103
5
    txn->remove(start_version_key, end_version_key);
1104
5
    std::string start_meta_key = meta_key_prefix(instance_id_);
1105
5
    std::string end_meta_key = meta_key_prefix(instance_id_ + '\x00');
1106
5
    txn->remove(start_meta_key, end_meta_key);
1107
5
    std::string start_recycle_key = recycle_key_prefix(instance_id_);
1108
5
    std::string end_recycle_key = recycle_key_prefix(instance_id_ + '\x00');
1109
5
    txn->remove(start_recycle_key, end_recycle_key);
1110
5
    std::string start_stats_tablet_key = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1111
5
    std::string end_stats_tablet_key = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1112
5
    txn->remove(start_stats_tablet_key, end_stats_tablet_key);
1113
5
    std::string start_copy_key = copy_key_prefix(instance_id_);
1114
5
    std::string end_copy_key = copy_key_prefix(instance_id_ + '\x00');
1115
5
    txn->remove(start_copy_key, end_copy_key);
1116
    // should not remove job key range, because we need to reserve job recycle kv
1117
    // 0:instance_id  1:table_id  2:index_id  3:part_id  4:tablet_id
1118
5
    std::string start_job_tablet_key = job_tablet_key({instance_id_, 0, 0, 0, 0});
1119
5
    std::string end_job_tablet_key = job_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1120
5
    txn->remove(start_job_tablet_key, end_job_tablet_key);
1121
5
    StorageVaultKeyInfo key_info0 {instance_id_, ""};
1122
5
    StorageVaultKeyInfo key_info1 {instance_id_, "\xff"};
1123
5
    std::string start_vault_key = storage_vault_key(key_info0);
1124
5
    std::string end_vault_key = storage_vault_key(key_info1);
1125
5
    txn->remove(start_vault_key, end_vault_key);
1126
5
    std::string versioned_version_key_start = versioned::version_key_prefix(instance_id_);
1127
5
    std::string versioned_version_key_end = versioned::version_key_prefix(instance_id_ + '\x00');
1128
5
    txn->remove(versioned_version_key_start, versioned_version_key_end);
1129
5
    std::string versioned_index_key_start = versioned::index_key_prefix(instance_id_);
1130
5
    std::string versioned_index_key_end = versioned::index_key_prefix(instance_id_ + '\x00');
1131
5
    txn->remove(versioned_index_key_start, versioned_index_key_end);
1132
5
    std::string versioned_stats_tablet_key_start = versioned::stats_key_prefix(instance_id_);
1133
5
    std::string versioned_stats_tablet_key_end = versioned::stats_key_prefix(instance_id_ + '\x00');
1134
5
    txn->remove(versioned_stats_tablet_key_start, versioned_stats_tablet_key_end);
1135
5
    std::string versioned_meta_key_start = versioned::meta_key_prefix(instance_id_);
1136
5
    std::string versioned_meta_key_end = versioned::meta_key_prefix(instance_id_ + '\x00');
1137
5
    txn->remove(versioned_meta_key_start, versioned_meta_key_end);
1138
5
    std::string versioned_data_key_start = versioned::data_key_prefix(instance_id_);
1139
5
    std::string versioned_data_key_end = versioned::data_key_prefix(instance_id_ + '\x00');
1140
5
    txn->remove(versioned_data_key_start, versioned_data_key_end);
1141
5
    std::string versioned_log_key_start = versioned::log_key_prefix(instance_id_);
1142
5
    std::string versioned_log_key_end = versioned::log_key_prefix(instance_id_ + '\x00');
1143
5
    txn->remove(versioned_log_key_start, versioned_log_key_end);
1144
1145
    // Updating the recycle state also commits this transaction, making the metadata deletions
1146
    // and state transition atomic.
1147
5
    if (update_instance_recycle_state(
1148
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING,
1149
5
                InstanceRecycleState::INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED, txn.get()) != 0) {
1150
0
        return -1;
1151
0
    }
1152
1153
5
    return 0;
1154
5
}
1155
1156
0
int InstanceRecycler::remove_instance_key() {
1157
0
    std::unique_ptr<Transaction> txn;
1158
0
    std::string key = instance_key(instance_info_.instance_id());
1159
0
    std::string value;
1160
0
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1161
0
    if (err != TxnErrorCode::TXN_OK) {
1162
0
        LOG(WARNING) << "failed to create txn";
1163
0
        return -1;
1164
0
    }
1165
1166
0
    err = txn->get(key, &value);
1167
0
    if (err != TxnErrorCode::TXN_OK) {
1168
0
        LOG(WARNING) << "failed to get instance, instance_id=" << instance_info_.instance_id()
1169
0
                     << ", err=" << err;
1170
0
        return -1;
1171
0
    }
1172
1173
0
    InstanceInfoPB instance;
1174
0
    if (!instance.ParseFromString(value)) {
1175
0
        LOG(WARNING) << "malformed instance info, key=" << key;
1176
0
        return -1;
1177
0
    }
1178
1179
0
    if (instance.status() != InstanceInfoPB::DELETED) {
1180
0
        LOG(WARNING) << "failed to remove instance key, instance is not deleted, instance_id="
1181
0
                     << instance_id_ << ", status=" << instance.status();
1182
0
        return -1;
1183
0
    }
1184
1185
0
    if (instance.recycle_state() != INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED) {
1186
0
        LOG(WARNING) << "failed to remove instance key, invalid recycle state, instance_id="
1187
0
                     << instance_id_
1188
0
                     << ", current_state=" << InstanceRecycleState_Name(instance.recycle_state())
1189
0
                     << ", expected_state="
1190
0
                     << InstanceRecycleState_Name(INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1191
0
        return -1;
1192
0
    }
1193
1194
0
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1195
0
    txn->remove(key);
1196
0
    err = txn->commit();
1197
0
    if (err != TxnErrorCode::TXN_OK) {
1198
0
        LOG(WARNING) << "failed to delete instance kv, instance_id=" << instance_id_
1199
0
                     << " err=" << err;
1200
0
        return -1;
1201
0
    }
1202
0
    return 0;
1203
0
}
1204
1205
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState expected_state,
1206
7
                                                    InstanceRecycleState target_state) {
1207
7
    std::unique_ptr<Transaction> txn;
1208
7
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1209
7
    if (err != TxnErrorCode::TXN_OK) {
1210
0
        LOG(WARNING) << "failed to create txn";
1211
0
        return -1;
1212
0
    }
1213
7
    return update_instance_recycle_state(expected_state, target_state, txn.get());
1214
7
}
1215
1216
int InstanceRecycler::update_instance_recycle_state(InstanceRecycleState current_state,
1217
                                                    InstanceRecycleState target_state,
1218
12
                                                    Transaction* txn) {
1219
12
    const bool valid_transition =
1220
12
            (current_state == INSTANCE_RECYCLE_STATE_DATA_CLEANUP_PENDING &&
1221
12
             target_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING) ||
1222
12
            (current_state == INSTANCE_RECYCLE_STATE_METADATA_CLEANUP_PENDING &&
1223
6
             target_state == INSTANCE_RECYCLE_STATE_CLEANUP_COMPLETED);
1224
1225
12
    if (!valid_transition) {
1226
1
        LOG_WARNING("invalid instance recycled state transition")
1227
1
                .tag("instance_id", instance_id_)
1228
1
                .tag("current_state", InstanceRecycleState_Name(current_state))
1229
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1230
1
        return -1;
1231
1
    }
1232
1233
11
    std::string key = instance_key({instance_id_});
1234
11
    std::string value;
1235
11
    TxnErrorCode err = txn->get(key, &value);
1236
11
    if (err != TxnErrorCode::TXN_OK) {
1237
0
        LOG_WARNING("failed to get instance when updating instance recycled state")
1238
0
                .tag("instance_id", instance_id_)
1239
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1240
0
                .tag("target_state", InstanceRecycleState_Name(target_state))
1241
0
                .tag("err", err);
1242
0
        return -1;
1243
0
    }
1244
1245
11
    InstanceInfoPB instance;
1246
11
    if (!instance.ParseFromString(value)) {
1247
0
        LOG_WARNING("failed to parse InstanceInfoPB when updating instance recycled state")
1248
0
                .tag("instance_id", instance_id_)
1249
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1250
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1251
0
        return -1;
1252
0
    }
1253
11
    if (instance.status() != InstanceInfoPB::DELETED) {
1254
0
        LOG_WARNING("instance is not deleted when updating instance recycled state")
1255
0
                .tag("instance_id", instance_id_)
1256
0
                .tag("status", instance.status())
1257
0
                .tag("current_state", InstanceRecycleState_Name(current_state))
1258
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1259
0
        return -1;
1260
0
    }
1261
11
    if (instance.recycle_state() != current_state) {
1262
1
        LOG_WARNING("instance recycled state changed before update")
1263
1
                .tag("instance_id", instance_id_)
1264
1
                .tag("current_state", InstanceRecycleState_Name(instance.recycle_state()))
1265
1
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1266
1
                .tag("target_state", InstanceRecycleState_Name(target_state));
1267
1
        return -1;
1268
1
    }
1269
1270
10
    instance.set_recycle_state(target_state);
1271
10
    instance.set_recycle_state_update_time_ms(
1272
10
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count());
1273
10
    if (!instance.SerializeToString(&value)) {
1274
0
        LOG_WARNING("failed to serialize InstanceInfoPB when updating instance recycled state")
1275
0
                .tag("instance_id", instance_id_)
1276
0
                .tag("expected_state", InstanceRecycleState_Name(current_state))
1277
0
                .tag("target_state", InstanceRecycleState_Name(target_state));
1278
0
        return -1;
1279
0
    }
1280
1281
10
    txn->atomic_add(system_meta_service_instance_update_key(), 1);
1282
10
    txn->put(key, value);
1283
10
    err = txn->commit();
1284
10
    if (err != TxnErrorCode::TXN_OK) {
1285
0
        LOG(WARNING) << "failed to commit fdb txn when updating instance recycled state, "
1286
0
                     << "instance_id=" << instance_id_ << ", err=" << err;
1287
0
        return -1;
1288
0
    }
1289
1290
10
    instance_info_.Swap(&instance);
1291
10
    LOG_INFO("updated instance recycled state")
1292
10
            .tag("instance_id", instance_id_)
1293
10
            .tag("recycle_state", InstanceRecycleState_Name(target_state));
1294
10
    return 0;
1295
10
}
1296
1297
int InstanceRecycler::check_rowset_exists(int64_t tablet_id, const std::string& rowset_id,
1298
9
                                          bool* exists, PackedFileRecycleStats* stats) {
1299
9
    if (exists == nullptr) {
1300
0
        return -1;
1301
0
    }
1302
9
    *exists = false;
1303
1304
9
    std::string begin = meta_rowset_key({instance_id_, tablet_id, 0});
1305
9
    std::string end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1306
9
    std::string scan_begin = begin;
1307
1308
9
    while (true) {
1309
9
        std::unique_ptr<RangeGetIterator> it_range;
1310
9
        int get_ret = txn_get(txn_kv_.get(), scan_begin, end, it_range);
1311
9
        if (get_ret < 0) {
1312
0
            LOG_WARNING("failed to scan rowset metas when recycling packed file")
1313
0
                    .tag("instance_id", instance_id_)
1314
0
                    .tag("tablet_id", tablet_id)
1315
0
                    .tag("ret", get_ret);
1316
0
            return -1;
1317
0
        }
1318
9
        if (get_ret == 1 || it_range == nullptr || !it_range->has_next()) {
1319
6
            return 0;
1320
6
        }
1321
1322
3
        std::string last_key;
1323
3
        while (it_range->has_next()) {
1324
3
            auto [k, v] = it_range->next();
1325
3
            last_key.assign(k.data(), k.size());
1326
3
            doris::RowsetMetaCloudPB rowset_meta;
1327
3
            if (!rowset_meta.ParseFromArray(v.data(), v.size())) {
1328
0
                LOG_WARNING("malformed rowset meta when checking packed file rowset existence")
1329
0
                        .tag("instance_id", instance_id_)
1330
0
                        .tag("tablet_id", tablet_id)
1331
0
                        .tag("key", hex(k));
1332
0
                continue;
1333
0
            }
1334
3
            if (stats) {
1335
3
                ++stats->rowset_scan_count;
1336
3
            }
1337
3
            if (rowset_meta.rowset_id_v2() == rowset_id) {
1338
3
                *exists = true;
1339
3
                return 0;
1340
3
            }
1341
3
        }
1342
1343
0
        if (!it_range->more()) {
1344
0
            return 0;
1345
0
        }
1346
1347
        // Continue scanning from the next key to keep each transaction short.
1348
0
        scan_begin = std::move(last_key);
1349
0
        scan_begin.push_back('\x00');
1350
0
    }
1351
9
}
1352
1353
int InstanceRecycler::check_recycle_and_tmp_rowset_exists(int64_t tablet_id,
1354
                                                          const std::string& rowset_id,
1355
                                                          int64_t txn_id, bool* recycle_exists,
1356
11
                                                          bool* tmp_exists) {
1357
11
    if (recycle_exists == nullptr || tmp_exists == nullptr) {
1358
0
        return -1;
1359
0
    }
1360
11
    *recycle_exists = false;
1361
11
    *tmp_exists = false;
1362
1363
11
    if (txn_id <= 0) {
1364
0
        LOG_WARNING("invalid txn id when checking recycle/tmp rowset existence")
1365
0
                .tag("instance_id", instance_id_)
1366
0
                .tag("tablet_id", tablet_id)
1367
0
                .tag("rowset_id", rowset_id)
1368
0
                .tag("txn_id", txn_id);
1369
0
        return -1;
1370
0
    }
1371
1372
11
    std::unique_ptr<Transaction> txn;
1373
11
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1374
11
    if (err != TxnErrorCode::TXN_OK) {
1375
0
        LOG_WARNING("failed to create txn when checking recycle/tmp rowset existence")
1376
0
                .tag("instance_id", instance_id_)
1377
0
                .tag("tablet_id", tablet_id)
1378
0
                .tag("rowset_id", rowset_id)
1379
0
                .tag("txn_id", txn_id)
1380
0
                .tag("err", err);
1381
0
        return -1;
1382
0
    }
1383
1384
11
    std::string recycle_key = recycle_rowset_key({instance_id_, tablet_id, rowset_id});
1385
11
    auto ret = key_exists(txn.get(), recycle_key, true);
1386
11
    if (ret == TxnErrorCode::TXN_OK) {
1387
1
        *recycle_exists = true;
1388
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1389
0
        LOG_WARNING("failed to check recycle rowset existence")
1390
0
                .tag("instance_id", instance_id_)
1391
0
                .tag("tablet_id", tablet_id)
1392
0
                .tag("rowset_id", rowset_id)
1393
0
                .tag("key", hex(recycle_key))
1394
0
                .tag("err", ret);
1395
0
        return -1;
1396
0
    }
1397
1398
11
    std::string tmp_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
1399
11
    ret = key_exists(txn.get(), tmp_key, true);
1400
11
    if (ret == TxnErrorCode::TXN_OK) {
1401
1
        *tmp_exists = true;
1402
10
    } else if (ret != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1403
0
        LOG_WARNING("failed to check tmp rowset existence")
1404
0
                .tag("instance_id", instance_id_)
1405
0
                .tag("tablet_id", tablet_id)
1406
0
                .tag("txn_id", txn_id)
1407
0
                .tag("key", hex(tmp_key))
1408
0
                .tag("err", ret);
1409
0
        return -1;
1410
0
    }
1411
1412
11
    return 0;
1413
11
}
1414
1415
std::pair<std::string, std::shared_ptr<StorageVaultAccessor>>
1416
9
InstanceRecycler::resolve_packed_file_accessor(const std::string& hint) {
1417
9
    if (!hint.empty()) {
1418
9
        if (auto it = accessor_map_.find(hint); it != accessor_map_.end()) {
1419
9
            return {hint, it->second};
1420
9
        }
1421
9
    }
1422
1423
0
    return {"", nullptr};
1424
9
}
1425
1426
int InstanceRecycler::correct_packed_file_info(cloud::PackedFileInfoPB* packed_info, bool* changed,
1427
                                               const std::string& packed_file_path,
1428
3
                                               PackedFileRecycleStats* stats) {
1429
3
    bool local_changed = false;
1430
3
    int64_t left_num = 0;
1431
3
    int64_t left_bytes = 0;
1432
3
    bool all_small_files_confirmed = true;
1433
3
    LOG(INFO) << "begin to correct file: " << packed_file_path;
1434
1435
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1436
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1437
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1438
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1439
14
        LOG_INFO("packed slice correction status")
1440
14
                .tag("instance_id", instance_id_)
1441
14
                .tag("packed_file_path", packed_file_path)
1442
14
                .tag("small_file_path", file.path())
1443
14
                .tag("tablet_id", tablet_id)
1444
14
                .tag("rowset_id", rowset_id)
1445
14
                .tag("txn_id", txn_id)
1446
14
                .tag("size", file.size())
1447
14
                .tag("deleted", file.deleted())
1448
14
                .tag("corrected", file.corrected())
1449
14
                .tag("confirmed_this_round", confirmed_this_round);
1450
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
1435
14
    auto log_small_file_status = [&](const cloud::PackedSlicePB& file, bool confirmed_this_round) {
1436
14
        int64_t tablet_id = file.has_tablet_id() ? file.tablet_id() : int64_t {-1};
1437
14
        std::string rowset_id = file.has_rowset_id() ? file.rowset_id() : std::string {};
1438
14
        int64_t txn_id = file.has_txn_id() ? file.txn_id() : int64_t {0};
1439
        LOG_INFO("packed slice correction status")
1440
14
                .tag("instance_id", instance_id_)
1441
14
                .tag("packed_file_path", packed_file_path)
1442
14
                .tag("small_file_path", file.path())
1443
14
                .tag("tablet_id", tablet_id)
1444
14
                .tag("rowset_id", rowset_id)
1445
14
                .tag("txn_id", txn_id)
1446
14
                .tag("size", file.size())
1447
14
                .tag("deleted", file.deleted())
1448
14
                .tag("corrected", file.corrected())
1449
14
                .tag("confirmed_this_round", confirmed_this_round);
1450
14
    };
1451
1452
17
    for (int i = 0; i < packed_info->slices_size(); ++i) {
1453
14
        auto* small_file = packed_info->mutable_slices(i);
1454
14
        if (small_file->deleted()) {
1455
3
            log_small_file_status(*small_file, small_file->corrected());
1456
3
            continue;
1457
3
        }
1458
1459
11
        if (small_file->corrected()) {
1460
0
            left_num++;
1461
0
            left_bytes += small_file->size();
1462
0
            log_small_file_status(*small_file, true);
1463
0
            continue;
1464
0
        }
1465
1466
11
        if (!small_file->has_tablet_id() || !small_file->has_rowset_id()) {
1467
0
            LOG_WARNING("packed file small file missing identifiers during correction")
1468
0
                    .tag("instance_id", instance_id_)
1469
0
                    .tag("small_file_path", small_file->path())
1470
0
                    .tag("index", i);
1471
0
            return -1;
1472
0
        }
1473
1474
11
        int64_t tablet_id = small_file->tablet_id();
1475
11
        const std::string& rowset_id = small_file->rowset_id();
1476
11
        if (!small_file->has_txn_id() || small_file->txn_id() <= 0) {
1477
0
            LOG_WARNING("packed file small file missing valid txn id during correction")
1478
0
                    .tag("instance_id", instance_id_)
1479
0
                    .tag("small_file_path", small_file->path())
1480
0
                    .tag("index", i)
1481
0
                    .tag("tablet_id", tablet_id)
1482
0
                    .tag("rowset_id", rowset_id)
1483
0
                    .tag("has_txn_id", small_file->has_txn_id())
1484
0
                    .tag("txn_id", small_file->has_txn_id() ? small_file->txn_id() : 0);
1485
0
            return -1;
1486
0
        }
1487
11
        int64_t txn_id = small_file->txn_id();
1488
11
        bool recycle_exists = false;
1489
11
        bool tmp_exists = false;
1490
11
        if (check_recycle_and_tmp_rowset_exists(tablet_id, rowset_id, txn_id, &recycle_exists,
1491
11
                                                &tmp_exists) != 0) {
1492
0
            return -1;
1493
0
        }
1494
1495
11
        bool small_file_confirmed = false;
1496
11
        if (tmp_exists) {
1497
1
            left_num++;
1498
1
            left_bytes += small_file->size();
1499
1
            small_file_confirmed = true;
1500
10
        } else if (recycle_exists) {
1501
1
            left_num++;
1502
1
            left_bytes += small_file->size();
1503
            // keep small_file_confirmed=false so the packed file remains uncorrected
1504
9
        } else {
1505
9
            bool rowset_exists = false;
1506
9
            if (check_rowset_exists(tablet_id, rowset_id, &rowset_exists, stats) != 0) {
1507
0
                return -1;
1508
0
            }
1509
1510
9
            if (!rowset_exists) {
1511
6
                if (!small_file->deleted()) {
1512
6
                    small_file->set_deleted(true);
1513
6
                    local_changed = true;
1514
6
                }
1515
6
                if (!small_file->corrected()) {
1516
6
                    small_file->set_corrected(true);
1517
6
                    local_changed = true;
1518
6
                }
1519
6
                small_file_confirmed = true;
1520
6
            } else {
1521
3
                left_num++;
1522
3
                left_bytes += small_file->size();
1523
3
                small_file_confirmed = true;
1524
3
            }
1525
9
        }
1526
1527
11
        if (!small_file_confirmed) {
1528
1
            all_small_files_confirmed = false;
1529
1
        }
1530
1531
11
        if (small_file->corrected() != small_file_confirmed) {
1532
4
            small_file->set_corrected(small_file_confirmed);
1533
4
            local_changed = true;
1534
4
        }
1535
1536
11
        log_small_file_status(*small_file, small_file_confirmed);
1537
11
    }
1538
1539
3
    if (packed_info->remaining_slice_bytes() != left_bytes) {
1540
3
        packed_info->set_remaining_slice_bytes(left_bytes);
1541
3
        local_changed = true;
1542
3
    }
1543
3
    if (packed_info->ref_cnt() != left_num) {
1544
3
        auto old_ref_cnt = packed_info->ref_cnt();
1545
3
        packed_info->set_ref_cnt(left_num);
1546
3
        LOG_INFO("corrected packed file ref count")
1547
3
                .tag("instance_id", instance_id_)
1548
3
                .tag("resource_id", packed_info->resource_id())
1549
3
                .tag("packed_file_path", packed_file_path)
1550
3
                .tag("old_ref_cnt", old_ref_cnt)
1551
3
                .tag("new_ref_cnt", left_num);
1552
3
        local_changed = true;
1553
3
    }
1554
3
    if (packed_info->corrected() != all_small_files_confirmed) {
1555
2
        packed_info->set_corrected(all_small_files_confirmed);
1556
2
        local_changed = true;
1557
2
    }
1558
3
    if (left_num == 0 && packed_info->state() != cloud::PackedFileInfoPB::RECYCLING) {
1559
1
        packed_info->set_state(cloud::PackedFileInfoPB::RECYCLING);
1560
1
        local_changed = true;
1561
1
    }
1562
1563
3
    if (changed != nullptr) {
1564
3
        *changed = local_changed;
1565
3
    }
1566
3
    return 0;
1567
3
}
1568
1569
int InstanceRecycler::process_single_packed_file(const std::string& packed_key,
1570
                                                 const std::string& packed_file_path,
1571
3
                                                 PackedFileRecycleStats* stats) {
1572
3
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
1573
3
    bool correction_ok = false;
1574
3
    cloud::PackedFileInfoPB packed_info;
1575
1576
3
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
1577
3
        if (stopped()) {
1578
0
            LOG_WARNING("recycler stopped before processing packed file")
1579
0
                    .tag("instance_id", instance_id_)
1580
0
                    .tag("packed_file_path", packed_file_path)
1581
0
                    .tag("attempt", attempt);
1582
0
            return -1;
1583
0
        }
1584
1585
3
        std::unique_ptr<Transaction> txn;
1586
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1587
3
        if (err != TxnErrorCode::TXN_OK) {
1588
0
            LOG_WARNING("failed to create txn when processing packed file")
1589
0
                    .tag("instance_id", instance_id_)
1590
0
                    .tag("packed_file_path", packed_file_path)
1591
0
                    .tag("attempt", attempt)
1592
0
                    .tag("err", err);
1593
0
            return -1;
1594
0
        }
1595
1596
3
        std::string packed_val;
1597
3
        err = txn->get(packed_key, &packed_val);
1598
3
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1599
0
            return 0;
1600
0
        }
1601
3
        if (err != TxnErrorCode::TXN_OK) {
1602
0
            LOG_WARNING("failed to get packed file kv")
1603
0
                    .tag("instance_id", instance_id_)
1604
0
                    .tag("packed_file_path", packed_file_path)
1605
0
                    .tag("attempt", attempt)
1606
0
                    .tag("err", err);
1607
0
            return -1;
1608
0
        }
1609
1610
3
        if (!packed_info.ParseFromString(packed_val)) {
1611
0
            LOG_WARNING("failed to parse packed file info")
1612
0
                    .tag("instance_id", instance_id_)
1613
0
                    .tag("packed_file_path", packed_file_path)
1614
0
                    .tag("attempt", attempt);
1615
0
            return -1;
1616
0
        }
1617
1618
3
        int64_t now_sec = ::time(nullptr);
1619
3
        bool corrected = packed_info.corrected();
1620
3
        bool due = config::force_immediate_recycle ||
1621
3
                   now_sec - packed_info.created_at_sec() >=
1622
3
                           config::packed_file_correction_delay_seconds;
1623
1624
3
        if (!corrected && due) {
1625
3
            bool changed = false;
1626
3
            if (correct_packed_file_info(&packed_info, &changed, packed_file_path, stats) != 0) {
1627
0
                LOG_WARNING("correct_packed_file_info failed")
1628
0
                        .tag("instance_id", instance_id_)
1629
0
                        .tag("packed_file_path", packed_file_path)
1630
0
                        .tag("attempt", attempt);
1631
0
                return -1;
1632
0
            }
1633
3
            if (changed) {
1634
3
                std::string updated;
1635
3
                if (!packed_info.SerializeToString(&updated)) {
1636
0
                    LOG_WARNING("failed to serialize packed file info after correction")
1637
0
                            .tag("instance_id", instance_id_)
1638
0
                            .tag("packed_file_path", packed_file_path)
1639
0
                            .tag("attempt", attempt);
1640
0
                    return -1;
1641
0
                }
1642
3
                txn->put(packed_key, updated);
1643
3
                err = txn->commit();
1644
3
                if (err == TxnErrorCode::TXN_OK) {
1645
3
                    if (stats) {
1646
3
                        ++stats->num_corrected;
1647
3
                    }
1648
3
                } else {
1649
0
                    if (err == TxnErrorCode::TXN_CONFLICT && attempt < max_retry_times) {
1650
0
                        LOG_WARNING(
1651
0
                                "failed to commit correction for packed file due to conflict, "
1652
0
                                "retrying")
1653
0
                                .tag("instance_id", instance_id_)
1654
0
                                .tag("packed_file_path", packed_file_path)
1655
0
                                .tag("attempt", attempt);
1656
0
                        sleep_for_packed_file_retry();
1657
0
                        packed_info.Clear();
1658
0
                        continue;
1659
0
                    }
1660
0
                    LOG_WARNING("failed to commit correction for packed file")
1661
0
                            .tag("instance_id", instance_id_)
1662
0
                            .tag("packed_file_path", packed_file_path)
1663
0
                            .tag("attempt", attempt)
1664
0
                            .tag("err", err);
1665
0
                    return -1;
1666
0
                }
1667
3
            }
1668
3
        }
1669
1670
3
        correction_ok = true;
1671
3
        break;
1672
3
    }
1673
1674
3
    if (!correction_ok) {
1675
0
        return -1;
1676
0
    }
1677
1678
3
    if (!(packed_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1679
3
          packed_info.ref_cnt() == 0)) {
1680
2
        return 0;
1681
2
    }
1682
1683
1
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
1684
0
        LOG_WARNING("packed file missing resource id when recycling")
1685
0
                .tag("instance_id", instance_id_)
1686
0
                .tag("packed_file_path", packed_file_path);
1687
0
        return -1;
1688
0
    }
1689
1
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
1690
1
    if (!accessor) {
1691
0
        LOG_WARNING("no accessor available to delete packed file")
1692
0
                .tag("instance_id", instance_id_)
1693
0
                .tag("packed_file_path", packed_file_path)
1694
0
                .tag("resource_id", packed_info.resource_id());
1695
0
        return -1;
1696
0
    }
1697
1
    int del_ret = accessor->delete_file(packed_file_path);
1698
1
    if (del_ret != 0 && del_ret != 1) {
1699
0
        LOG_WARNING("failed to delete packed file")
1700
0
                .tag("instance_id", instance_id_)
1701
0
                .tag("packed_file_path", packed_file_path)
1702
0
                .tag("resource_id", resource_id)
1703
0
                .tag("ret", del_ret);
1704
0
        return -1;
1705
0
    }
1706
1
    if (del_ret == 1) {
1707
0
        LOG_INFO("packed file already removed")
1708
0
                .tag("instance_id", instance_id_)
1709
0
                .tag("packed_file_path", packed_file_path)
1710
0
                .tag("resource_id", resource_id);
1711
1
    } else {
1712
1
        LOG_INFO("deleted packed file")
1713
1
                .tag("instance_id", instance_id_)
1714
1
                .tag("packed_file_path", packed_file_path)
1715
1
                .tag("resource_id", resource_id);
1716
1
    }
1717
1718
1
    for (int del_attempt = 1; del_attempt <= max_retry_times; ++del_attempt) {
1719
1
        std::unique_ptr<Transaction> del_txn;
1720
1
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
1721
1
        if (err != TxnErrorCode::TXN_OK) {
1722
0
            LOG_WARNING("failed to create txn when removing packed file kv")
1723
0
                    .tag("instance_id", instance_id_)
1724
0
                    .tag("packed_file_path", packed_file_path)
1725
0
                    .tag("del_attempt", del_attempt)
1726
0
                    .tag("err", err);
1727
0
            return -1;
1728
0
        }
1729
1730
1
        std::string latest_val;
1731
1
        err = del_txn->get(packed_key, &latest_val);
1732
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1733
0
            return 0;
1734
0
        }
1735
1
        if (err != TxnErrorCode::TXN_OK) {
1736
0
            LOG_WARNING("failed to re-read packed file kv before removal")
1737
0
                    .tag("instance_id", instance_id_)
1738
0
                    .tag("packed_file_path", packed_file_path)
1739
0
                    .tag("del_attempt", del_attempt)
1740
0
                    .tag("err", err);
1741
0
            return -1;
1742
0
        }
1743
1744
1
        cloud::PackedFileInfoPB latest_info;
1745
1
        if (!latest_info.ParseFromString(latest_val)) {
1746
0
            LOG_WARNING("failed to parse packed file info before removal")
1747
0
                    .tag("instance_id", instance_id_)
1748
0
                    .tag("packed_file_path", packed_file_path)
1749
0
                    .tag("del_attempt", del_attempt);
1750
0
            return -1;
1751
0
        }
1752
1753
1
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
1754
1
              latest_info.ref_cnt() == 0)) {
1755
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
1756
0
                    .tag("instance_id", instance_id_)
1757
0
                    .tag("packed_file_path", packed_file_path)
1758
0
                    .tag("del_attempt", del_attempt);
1759
0
            return 0;
1760
0
        }
1761
1762
1
        del_txn->remove(packed_key);
1763
1
        err = del_txn->commit();
1764
1
        if (err == TxnErrorCode::TXN_OK) {
1765
1
            if (stats) {
1766
1
                ++stats->num_deleted;
1767
1
                stats->bytes_deleted += static_cast<int64_t>(packed_key.size()) +
1768
1
                                        static_cast<int64_t>(latest_val.size());
1769
1
                if (del_ret == 0 || del_ret == 1) {
1770
1
                    ++stats->num_object_deleted;
1771
1
                    int64_t object_size = latest_info.total_slice_bytes();
1772
1
                    if (object_size <= 0) {
1773
0
                        object_size = packed_info.total_slice_bytes();
1774
0
                    }
1775
1
                    stats->bytes_object_deleted += object_size;
1776
1
                }
1777
1
            }
1778
1
            LOG_INFO("removed packed file metadata")
1779
1
                    .tag("instance_id", instance_id_)
1780
1
                    .tag("packed_file_path", packed_file_path);
1781
1
            return 0;
1782
1
        }
1783
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
1784
0
            if (del_attempt >= max_retry_times) {
1785
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
1786
0
                        .tag("instance_id", instance_id_)
1787
0
                        .tag("packed_file_path", packed_file_path)
1788
0
                        .tag("del_attempt", del_attempt);
1789
0
                return -1;
1790
0
            }
1791
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
1792
0
                    .tag("instance_id", instance_id_)
1793
0
                    .tag("packed_file_path", packed_file_path)
1794
0
                    .tag("del_attempt", del_attempt);
1795
0
            sleep_for_packed_file_retry();
1796
0
            continue;
1797
0
        }
1798
0
        LOG_WARNING("failed to remove packed file kv")
1799
0
                .tag("instance_id", instance_id_)
1800
0
                .tag("packed_file_path", packed_file_path)
1801
0
                .tag("del_attempt", del_attempt)
1802
0
                .tag("err", err);
1803
0
        return -1;
1804
0
    }
1805
1806
0
    return -1;
1807
1
}
1808
1809
int InstanceRecycler::handle_packed_file_kv(std::string_view key, std::string_view value,
1810
4
                                            PackedFileRecycleStats* stats, int* ret) {
1811
4
    if (stats) {
1812
4
        ++stats->num_scanned;
1813
4
    }
1814
4
    std::string packed_file_path;
1815
4
    if (!decode_packed_file_key(key, &packed_file_path)) {
1816
0
        LOG_WARNING("failed to decode packed file key")
1817
0
                .tag("instance_id", instance_id_)
1818
0
                .tag("key", hex(key));
1819
0
        if (stats) {
1820
0
            ++stats->num_failed;
1821
0
        }
1822
0
        if (ret) {
1823
0
            *ret = -1;
1824
0
        }
1825
0
        return 0;
1826
0
    }
1827
1828
4
    cloud::PackedFileInfoPB packed_info;
1829
4
    if (!packed_info.ParseFromArray(value.data(), value.size())) {
1830
0
        LOG_WARNING("failed to parse packed file info from scan")
1831
0
                .tag("instance_id", instance_id_)
1832
0
                .tag("packed_file_path", packed_file_path);
1833
0
        if (stats) {
1834
0
            ++stats->num_failed;
1835
0
        }
1836
0
        if (ret) {
1837
0
            *ret = -1;
1838
0
        }
1839
0
        return 0;
1840
0
    }
1841
1842
4
    const int64_t now_sec = ::time(nullptr);
1843
4
    const bool due =
1844
4
            config::force_immediate_recycle ||
1845
4
            now_sec - packed_info.created_at_sec() >= config::packed_file_correction_delay_seconds;
1846
4
    const bool need_correction = !packed_info.corrected() && due;
1847
4
    const bool need_recycle =
1848
4
            packed_info.state() == cloud::PackedFileInfoPB::RECYCLING && packed_info.ref_cnt() == 0;
1849
4
    if (!need_correction && !need_recycle) {
1850
1
        return 0;
1851
1
    }
1852
1853
3
    std::string packed_key(key);
1854
3
    int process_ret = process_single_packed_file(packed_key, packed_file_path, stats);
1855
3
    if (process_ret != 0) {
1856
0
        if (stats) {
1857
0
            ++stats->num_failed;
1858
0
        }
1859
0
        if (ret) {
1860
0
            *ret = -1;
1861
0
        }
1862
0
    }
1863
3
    return 0;
1864
4
}
1865
1866
int64_t calculate_rowset_expired_time(const std::string& instance_id_, const RecycleRowsetPB& rs,
1867
6.30k
                                      int64_t* earlest_ts /* rowset earliest expiration ts */) {
1868
6.30k
    if (config::force_immediate_recycle) {
1869
295
        return 0L;
1870
295
    }
1871
    // RecycleRowsetPB created by compacted or dropped rowset has no expiration time, and will be recycled when exceed retention time
1872
6.00k
    int64_t expiration = rs.expiration() > 0 ? rs.expiration() : rs.creation_time();
1873
6.00k
    int64_t retention_seconds = config::retention_seconds;
1874
6.00k
    if (rs.type() == RecycleRowsetPB::COMPACT || rs.type() == RecycleRowsetPB::DROP) {
1875
4.70k
        retention_seconds = std::min(config::compacted_rowset_retention_seconds, retention_seconds);
1876
4.70k
    }
1877
6.00k
    int64_t final_expiration = expiration + retention_seconds;
1878
6.00k
    if (*earlest_ts > final_expiration) {
1879
6
        *earlest_ts = final_expiration;
1880
6
        g_bvar_recycler_recycle_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1881
6
    }
1882
6.00k
    return final_expiration;
1883
6.30k
}
1884
1885
int64_t calculate_partition_expired_time(
1886
        const std::string& instance_id_, const RecyclePartitionPB& partition_meta_pb,
1887
13
        int64_t* earlest_ts /* partition earliest expiration ts */) {
1888
13
    if (config::force_immediate_recycle) {
1889
7
        return 0L;
1890
7
    }
1891
6
    int64_t expiration = partition_meta_pb.expiration() > 0 ? partition_meta_pb.expiration()
1892
6
                                                            : partition_meta_pb.creation_time();
1893
6
    int64_t retention_seconds = config::retention_seconds;
1894
6
    if (partition_meta_pb.state() == RecyclePartitionPB::DROPPED) {
1895
6
        retention_seconds =
1896
6
                std::min(config::dropped_partition_retention_seconds, retention_seconds);
1897
6
    }
1898
6
    int64_t final_expiration = expiration + retention_seconds;
1899
6
    if (*earlest_ts > final_expiration) {
1900
2
        *earlest_ts = final_expiration;
1901
2
        g_bvar_recycler_recycle_partition_earlest_ts.put(instance_id_, *earlest_ts);
1902
2
    }
1903
6
    return final_expiration;
1904
13
}
1905
1906
int64_t calculate_index_expired_time(const std::string& instance_id_,
1907
                                     const RecycleIndexPB& index_meta_pb,
1908
18
                                     int64_t* earlest_ts /* index earliest expiration ts */) {
1909
18
    if (config::force_immediate_recycle) {
1910
12
        return 0L;
1911
12
    }
1912
6
    int64_t expiration = index_meta_pb.expiration() > 0 ? index_meta_pb.expiration()
1913
6
                                                        : index_meta_pb.creation_time();
1914
6
    int64_t retention_seconds = config::retention_seconds;
1915
6
    if (index_meta_pb.state() == RecycleIndexPB::DROPPED) {
1916
6
        retention_seconds = std::min(config::dropped_index_retention_seconds, retention_seconds);
1917
6
    }
1918
6
    int64_t final_expiration = expiration + retention_seconds;
1919
6
    if (*earlest_ts > final_expiration) {
1920
2
        *earlest_ts = final_expiration;
1921
2
        g_bvar_recycler_recycle_index_earlest_ts.put(instance_id_, *earlest_ts);
1922
2
    }
1923
6
    return final_expiration;
1924
18
}
1925
1926
int64_t calculate_tmp_rowset_expired_time(
1927
        const std::string& instance_id_, const doris::RowsetMetaCloudPB& tmp_rowset_meta_pb,
1928
53.2k
        int64_t* earlest_ts /* tmp_rowset earliest expiration ts */) {
1929
    // ATTN: `txn_expiration` should > 0, however we use `creation_time` + a large `retention_time` (> 1 day in production environment)
1930
    //  when `txn_expiration` <= 0 in some unexpected situation (usually when there are bugs). This is usually safe, coz loading
1931
    //  duration or timeout always < `retention_time` in practice.
1932
53.2k
    int64_t expiration = tmp_rowset_meta_pb.txn_expiration() > 0
1933
53.2k
                                 ? tmp_rowset_meta_pb.txn_expiration()
1934
53.2k
                                 : tmp_rowset_meta_pb.creation_time();
1935
53.2k
    expiration = config::force_immediate_recycle ? 0 : expiration;
1936
53.2k
    int64_t final_expiration = expiration + config::retention_seconds;
1937
53.2k
    if (*earlest_ts > final_expiration) {
1938
20
        *earlest_ts = final_expiration;
1939
20
        g_bvar_recycler_recycle_tmp_rowset_earlest_ts.put(instance_id_, *earlest_ts);
1940
20
    }
1941
53.2k
    return final_expiration;
1942
53.2k
}
1943
1944
int64_t calculate_txn_expired_time(const std::string& instance_id_, const RecycleTxnPB& txn_meta_pb,
1945
50.0k
                                   int64_t* earlest_ts /* txn earliest expiration ts */) {
1946
50.0k
    int64_t final_expiration = txn_meta_pb.creation_time() + config::label_keep_max_second * 1000L;
1947
50.0k
    if (*earlest_ts > final_expiration / 1000) {
1948
11
        *earlest_ts = final_expiration / 1000;
1949
11
        g_bvar_recycler_recycle_expired_txn_label_earlest_ts.put(instance_id_, *earlest_ts);
1950
11
    }
1951
50.0k
    return final_expiration;
1952
50.0k
}
1953
1954
int64_t calculate_restore_job_expired_time(
1955
        const std::string& instance_id_, const RestoreJobCloudPB& restore_job,
1956
41
        int64_t* earlest_ts /* restore job earliest expiration ts */) {
1957
41
    if (config::force_immediate_recycle || restore_job.state() == RestoreJobCloudPB::DROPPED ||
1958
41
        restore_job.state() == RestoreJobCloudPB::COMPLETED ||
1959
41
        restore_job.state() == RestoreJobCloudPB::RECYCLING) {
1960
        // final state, recycle immediately
1961
41
        return 0L;
1962
41
    }
1963
    // not final state, wait much longer than the FE's timeout(1 day)
1964
0
    int64_t last_modified_s =
1965
0
            restore_job.has_mtime_s() ? restore_job.mtime_s() : restore_job.ctime_s();
1966
0
    int64_t expiration = restore_job.expired_at_s() > 0
1967
0
                                 ? last_modified_s + restore_job.expired_at_s()
1968
0
                                 : last_modified_s;
1969
0
    int64_t final_expiration = expiration + config::retention_seconds;
1970
0
    if (*earlest_ts > final_expiration) {
1971
0
        *earlest_ts = final_expiration;
1972
0
        g_bvar_recycler_recycle_restore_job_earlest_ts.put(instance_id_, *earlest_ts);
1973
0
    }
1974
0
    return final_expiration;
1975
41
}
1976
1977
537
int InstanceRecycler::abort_txn_for_related_rowset(int64_t txn_id) {
1978
537
    AbortTxnRequest req;
1979
537
    TxnInfoPB txn_info;
1980
537
    MetaServiceCode code = MetaServiceCode::OK;
1981
537
    std::string msg;
1982
537
    std::stringstream ss;
1983
537
    std::unique_ptr<Transaction> txn;
1984
537
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1985
537
    if (err != TxnErrorCode::TXN_OK) {
1986
0
        LOG_WARNING("failed to create txn").tag("err", err);
1987
0
        return -1;
1988
0
    }
1989
1990
    // get txn index
1991
537
    TxnIndexPB txn_idx_pb;
1992
537
    auto index_key = txn_index_key({instance_id_, txn_id});
1993
537
    std::string index_val;
1994
537
    err = txn->get(index_key, &index_val);
1995
537
    if (err != TxnErrorCode::TXN_OK) {
1996
2
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1997
            // maybe recycled
1998
2
            LOG_WARNING("txn index not found, txn_id={} instance_id={}", txn_id, instance_id_)
1999
2
                    .tag("key", hex(index_key))
2000
2
                    .tag("txn_id", txn_id);
2001
2
            return 0;
2002
2
        }
2003
0
        LOG_WARNING("failed to get txn index")
2004
0
                .tag("err", err)
2005
0
                .tag("key", hex(index_key))
2006
0
                .tag("txn_id", txn_id);
2007
0
        return -1;
2008
2
    }
2009
535
    if (!txn_idx_pb.ParseFromString(index_val)) {
2010
1
        LOG_WARNING("failed to parse txn index")
2011
1
                .tag("err", err)
2012
1
                .tag("key", hex(index_key))
2013
1
                .tag("txn_id", txn_id);
2014
1
        return -1;
2015
1
    }
2016
534
    if (!txn_idx_pb.has_tablet_index() || !txn_idx_pb.tablet_index().has_db_id() ||
2017
534
        txn_idx_pb.tablet_index().db_id() <= 0) {
2018
3
        LOG_WARNING("malformed txn index, tablet index is missing or db id is invalid")
2019
3
                .tag("key", hex(index_key))
2020
3
                .tag("txn_id", txn_id)
2021
3
                .tag("db_id",
2022
3
                     txn_idx_pb.has_tablet_index() ? txn_idx_pb.tablet_index().db_id() : 0);
2023
3
        return -1;
2024
3
    }
2025
2026
531
    const int64_t db_id = txn_idx_pb.tablet_index().db_id();
2027
531
    const int64_t owner_txn_id =
2028
531
            txn_idx_pb.has_parent_txn_id() ? txn_idx_pb.parent_txn_id() : txn_id;
2029
531
    if (owner_txn_id <= 0) {
2030
1
        LOG_WARNING("malformed txn index, owner txn id is invalid")
2031
1
                .tag("key", hex(index_key))
2032
1
                .tag("txn_id", txn_id)
2033
1
                .tag("owner_txn_id", owner_txn_id);
2034
1
        return -1;
2035
1
    }
2036
2037
530
    auto info_key = txn_info_key({instance_id_, db_id, owner_txn_id});
2038
530
    std::string info_val;
2039
530
    err = txn->get(info_key, &info_val);
2040
530
    if (err != TxnErrorCode::TXN_OK) {
2041
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2042
            // maybe recycled
2043
1
            LOG_WARNING("txn info not found, txn_id={} owner_txn_id={} instance_id={}", txn_id,
2044
1
                        owner_txn_id, instance_id_)
2045
1
                    .tag("key", hex(info_key))
2046
1
                    .tag("txn_id", txn_id)
2047
1
                    .tag("owner_txn_id", owner_txn_id);
2048
1
            return 0;
2049
1
        }
2050
0
        LOG_WARNING("failed to get txn info")
2051
0
                .tag("err", err)
2052
0
                .tag("key", hex(info_key))
2053
0
                .tag("txn_id", txn_id)
2054
0
                .tag("owner_txn_id", owner_txn_id);
2055
0
        return -1;
2056
1
    }
2057
529
    if (!txn_info.ParseFromString(info_val)) {
2058
1
        LOG_WARNING("failed to parse txn info")
2059
1
                .tag("err", err)
2060
1
                .tag("key", hex(info_key))
2061
1
                .tag("txn_id", txn_id)
2062
1
                .tag("owner_txn_id", owner_txn_id);
2063
1
        return -1;
2064
1
    }
2065
528
    if (!txn_info.has_txn_id() || txn_info.txn_id() != owner_txn_id) {
2066
1
        LOG_WARNING("malformed txn info, txn id does not match owner txn id")
2067
1
                .tag("key", hex(info_key))
2068
1
                .tag("txn_id", txn_id)
2069
1
                .tag("owner_txn_id", owner_txn_id)
2070
1
                .tag("txn_info_txn_id", txn_info.txn_id());
2071
1
        return -1;
2072
1
    }
2073
2074
527
    if (txn_info.status() == TxnStatusPB::TXN_STATUS_ABORTED) {
2075
514
        LOG_INFO("txn has already been aborted, txn_id={} owner_txn_id={}", txn_id, owner_txn_id)
2076
514
                .tag("key", hex(info_key))
2077
514
                .tag("txn_id", txn_id)
2078
514
                .tag("owner_txn_id", owner_txn_id);
2079
514
        return 0;
2080
514
    }
2081
13
    if (txn_info.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2082
4
        LOG_WARNING("txn cannot be aborted, txn_id={} owner_txn_id={} status={}", txn_id,
2083
4
                    owner_txn_id, txn_info.status())
2084
4
                .tag("key", hex(info_key))
2085
4
                .tag("txn_id", txn_id)
2086
4
                .tag("owner_txn_id", owner_txn_id);
2087
4
        return -1;
2088
4
    }
2089
2090
9
    req.set_txn_id(owner_txn_id);
2091
9
    req.set_db_id(db_id);
2092
2093
9
    LOG(WARNING) << "begin abort txn for related rowset, txn_id=" << txn_id
2094
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2095
9
                 << " txn_info=" << txn_info.ShortDebugString();
2096
2097
9
    _abort_txn(instance_id_, &req, txn.get(), txn_info, ss, code, msg);
2098
9
    if (code != MetaServiceCode::OK) {
2099
0
        LOG(WARNING) << "failed to abort txn for related rowset, txn_id=" << txn_id
2100
0
                     << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2101
0
                     << " code=" << code << " msg=" << msg;
2102
0
        return -1;
2103
0
    }
2104
2105
9
    err = txn->commit();
2106
9
    if (err != TxnErrorCode::TXN_OK) {
2107
0
        code = cast_as<ErrCategory::COMMIT>(err);
2108
0
        ss << "failed to commit kv txn, txn_id=" << txn_info.txn_id() << " err=" << err;
2109
0
        msg = ss.str();
2110
0
        return -1;
2111
0
    }
2112
2113
9
    LOG(WARNING) << "finish abort txn for related rowset, txn_id=" << txn_id
2114
9
                 << " owner_txn_id=" << owner_txn_id << " instance_id=" << instance_id_
2115
9
                 << " txn_info=" << txn_info.ShortDebugString() << " code=" << code
2116
9
                 << " msg=" << msg;
2117
2118
9
    return 0;
2119
9
}
2120
2121
int InstanceRecycler::abort_job_for_related_rowset(int64_t tablet_id, const std::string& rowset_id,
2122
11
                                                   const std::string& job_id) {
2123
11
    FinishTabletJobRequest req;
2124
11
    FinishTabletJobResponse res;
2125
11
    req.set_action(FinishTabletJobRequest::ABORT);
2126
11
    MetaServiceCode code = MetaServiceCode::OK;
2127
11
    std::string msg;
2128
11
    std::stringstream ss;
2129
2130
11
    TabletIndexPB tablet_idx;
2131
11
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_idx);
2132
11
    if (ret == 1) {
2133
        // tablet maybe recycled, directly return 0
2134
1
        return 0;
2135
10
    } else if (ret != 0) {
2136
0
        LOG(WARNING) << "failed to get tablet index, tablet_id=" << tablet_id
2137
0
                     << " instance_id=" << instance_id_ << " ret=" << ret;
2138
0
        return ret;
2139
0
    }
2140
2141
10
    std::unique_ptr<Transaction> txn;
2142
10
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2143
10
    if (err != TxnErrorCode::TXN_OK) {
2144
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id_ << " err=" << err;
2145
0
        return -1;
2146
0
    }
2147
2148
10
    std::string job_key =
2149
10
            job_tablet_key({instance_id_, tablet_idx.table_id(), tablet_idx.index_id(),
2150
10
                            tablet_idx.partition_id(), tablet_idx.tablet_id()});
2151
10
    std::string job_val;
2152
10
    err = txn->get(job_key, &job_val);
2153
10
    if (err != TxnErrorCode::TXN_OK) {
2154
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2155
1
            LOG(INFO) << "job not exists, instance_id=" << instance_id_
2156
1
                      << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2157
            // A previous recycler round may have aborted the job. The caller must recheck the
2158
            // recycle key before deleting object data.
2159
1
            return 0;
2160
1
        }
2161
1
        LOG(WARNING) << "failed to get job, instance_id=" << instance_id_
2162
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " err=" << err
2163
0
                     << " key=" << hex(job_key);
2164
0
        return -1;
2165
1
    }
2166
2167
9
    TabletJobInfoPB job_pb;
2168
9
    if (!job_pb.ParseFromString(job_val)) {
2169
0
        LOG(WARNING) << "failed to parse job, instance_id=" << instance_id_
2170
0
                     << " tablet_id=" << tablet_idx.tablet_id() << " key=" << hex(job_key);
2171
0
        return -1;
2172
0
    }
2173
2174
9
    const TabletCompactionJobPB* matched_compaction = nullptr;
2175
9
    for (const auto& compaction : job_pb.compaction()) {
2176
9
        if (compaction.id() == job_id) {
2177
5
            matched_compaction = &compaction;
2178
5
            break;
2179
5
        }
2180
9
    }
2181
9
    const TabletSchemaChangeJobPB* matched_schema_change = nullptr;
2182
9
    if (matched_compaction == nullptr && job_pb.has_schema_change() &&
2183
9
        job_pb.schema_change().id() == job_id) {
2184
3
        matched_schema_change = &job_pb.schema_change();
2185
3
    }
2186
2187
9
    if (matched_compaction != nullptr || matched_schema_change != nullptr) {
2188
8
        LOG(WARNING) << "begin to abort job for related rowset, job_id=" << job_id
2189
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id();
2190
        // Compaction jobs belong to the rowset's tablet. A schema-change job is mirrored under
2191
        // the new tablet key, but its recorded index remains the base tablet so ABORT can remove
2192
        // both the base and mirrored schema-change records.
2193
8
        if (matched_compaction != nullptr) {
2194
5
            req.mutable_job()->mutable_idx()->CopyFrom(tablet_idx);
2195
5
            req.mutable_job()->add_compaction()->CopyFrom(*matched_compaction);
2196
5
        } else {
2197
3
            req.mutable_job()->mutable_idx()->CopyFrom(job_pb.idx());
2198
3
            req.mutable_job()->mutable_schema_change()->CopyFrom(*matched_schema_change);
2199
3
        }
2200
8
        req.set_action(FinishTabletJobRequest::ABORT);
2201
8
        _finish_tablet_job(&req, &res, instance_id_, txn, txn_kv_.get(),
2202
8
                           delete_bitmap_lock_white_list_.get(), resource_mgr_.get(), code, msg,
2203
8
                           ss);
2204
8
        if (code != MetaServiceCode::OK) {
2205
            // These two codes mean that the job cannot be aborted anymore.
2206
            // TABLET_NOT_FOUND means that the tablet has been dropped or recycled.
2207
            // There is no running job that still owns the PREPARE rowset, so the caller may
2208
            // recheck the recycle key.
2209
0
            bool no_job_to_abort = code == MetaServiceCode::TABLET_NOT_FOUND;
2210
            // INVALID_ARGUMENT has more than one meaning. It may mean that this job was removed or
2211
            // replaced by a newer job, but it may also report invalid metadata. Read the current
2212
            // job again and continue recycling only when the target job id no longer exists.
2213
0
            if (!no_job_to_abort && code == MetaServiceCode::INVALID_ARGUMENT) {
2214
0
                std::unique_ptr<Transaction> check_txn;
2215
0
                err = txn_kv_->create_txn(&check_txn);
2216
0
                if (err != TxnErrorCode::TXN_OK) {
2217
0
                    LOG(WARNING) << "failed to create txn to check related job, instance_id="
2218
0
                                 << instance_id_ << " err=" << err;
2219
0
                    return -1;
2220
0
                }
2221
2222
0
                const auto& idx = req.job().idx();
2223
0
                std::string current_job_key =
2224
0
                        job_tablet_key({instance_id_, idx.table_id(), idx.index_id(),
2225
0
                                        idx.partition_id(), idx.tablet_id()});
2226
0
                std::string current_job_val;
2227
0
                err = check_txn->get(current_job_key, &current_job_val);
2228
0
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2229
0
                    no_job_to_abort = true;
2230
0
                } else if (err != TxnErrorCode::TXN_OK) {
2231
0
                    LOG(WARNING) << "failed to check related job, instance_id=" << instance_id_
2232
0
                                 << " tablet_id=" << idx.tablet_id() << " err=" << err
2233
0
                                 << " key=" << hex(current_job_key);
2234
0
                    return -1;
2235
0
                } else {
2236
0
                    TabletJobInfoPB current_job;
2237
0
                    if (!current_job.ParseFromString(current_job_val)) {
2238
0
                        LOG(WARNING) << "failed to parse related job, instance_id=" << instance_id_
2239
0
                                     << " tablet_id=" << idx.tablet_id()
2240
0
                                     << " key=" << hex(current_job_key);
2241
0
                        return -1;
2242
0
                    }
2243
0
                    if (matched_compaction != nullptr) {
2244
0
                        no_job_to_abort = true;
2245
0
                        for (const auto& compaction : current_job.compaction()) {
2246
0
                            if (compaction.id() == job_id) {
2247
0
                                no_job_to_abort = false;
2248
0
                                break;
2249
0
                            }
2250
0
                        }
2251
0
                    } else {
2252
0
                        no_job_to_abort = !current_job.has_schema_change() ||
2253
0
                                          current_job.schema_change().id() != job_id;
2254
0
                    }
2255
0
                }
2256
0
            }
2257
0
            if (no_job_to_abort) {
2258
0
                return 0;
2259
0
            }
2260
0
            LOG(WARNING) << "failed to abort job, instance_id=" << instance_id_
2261
0
                         << " tablet_id=" << tablet_idx.tablet_id() << " code=" << code
2262
0
                         << " msg=" << msg;
2263
0
            return -1;
2264
0
        }
2265
8
        LOG(WARNING) << "finish abort job for related rowset, job_id=" << job_id
2266
8
                     << " instance_id=" << instance_id_ << " tablet_id=" << tablet_idx.tablet_id()
2267
8
                     << " code=" << code << " msg=" << msg;
2268
8
    } else {
2269
        // clang-format off
2270
1
        LOG(INFO) << "there is no job for related rowset, recheck recycle rowset before deletion"
2271
1
                  << ", instance_id=" << instance_id_ 
2272
1
                  << ", tablet_id=" << tablet_idx.tablet_id() 
2273
1
                  << ", job_id=" << job_id
2274
1
                  << ", rowset_id=" << rowset_id;
2275
        // clang-format on
2276
1
    }
2277
2278
9
    return 0;
2279
9
}
2280
2281
template <typename T>
2282
22
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2283
22
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2284
13
        return rowset_meta_pb.mutable_rowset_meta();
2285
13
    } else {
2286
9
        return &rowset_meta_pb;
2287
9
    }
2288
22
}
_ZN5doris5cloud19mutable_rowset_metaINS0_15RecycleRowsetPBEEEPNS_17RowsetMetaCloudPBERT_
Line
Count
Source
2282
13
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2283
13
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2284
13
        return rowset_meta_pb.mutable_rowset_meta();
2285
    } else {
2286
        return &rowset_meta_pb;
2287
    }
2288
13
}
_ZN5doris5cloud19mutable_rowset_metaINS_17RowsetMetaCloudPBEEEPS2_RT_
Line
Count
Source
2282
9
RowsetMetaCloudPB* mutable_rowset_meta(T& rowset_meta_pb) {
2283
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2284
        return rowset_meta_pb.mutable_rowset_meta();
2285
9
    } else {
2286
9
        return &rowset_meta_pb;
2287
9
    }
2288
9
}
2289
2290
template <typename T>
2291
1.63k
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2292
1.63k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2293
833
        return rowset_meta_pb.rowset_meta();
2294
833
    } else {
2295
799
        return rowset_meta_pb;
2296
799
    }
2297
1.63k
}
_ZN5doris5cloud11rowset_metaINS0_15RecycleRowsetPBEEERKNS_17RowsetMetaCloudPBERKT_
Line
Count
Source
2291
833
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2292
833
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2293
833
        return rowset_meta_pb.rowset_meta();
2294
    } else {
2295
        return rowset_meta_pb;
2296
    }
2297
833
}
_ZN5doris5cloud11rowset_metaINS_17RowsetMetaCloudPBEEERKS2_RKT_
Line
Count
Source
2291
799
const RowsetMetaCloudPB& rowset_meta(const T& rowset_meta_pb) {
2292
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2293
        return rowset_meta_pb.rowset_meta();
2294
799
    } else {
2295
799
        return rowset_meta_pb;
2296
799
    }
2297
799
}
2298
2299
template <typename T>
2300
std::optional<RelatedTxnOrJobAbortTask> make_related_txn_or_job_abort_task(
2301
1.07k
        const T& rowset_meta_pb) {
2302
1.07k
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2303
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2304
0
            return std::nullopt;
2305
0
        }
2306
545
    }
2307
2308
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2309
1.07k
    RelatedTxnOrJobAbortTask task;
2310
1.07k
    task.tablet_id = rs_meta.tablet_id();
2311
1.07k
    task.start_version = rs_meta.start_version();
2312
1.07k
    task.end_version = rs_meta.end_version();
2313
1.07k
    task.rowset_id = rs_meta.rowset_id_v2();
2314
1.07k
    if (rs_meta.has_load_id()) {
2315
1.05k
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2316
1.05k
        task.txn_id = rs_meta.txn_id();
2317
1.05k
        return task;
2318
1.05k
    }
2319
19
    if (rs_meta.has_job_id()) {
2320
14
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2321
14
        task.job_id = rs_meta.job_id();
2322
14
        return task;
2323
14
    }
2324
5
    return std::nullopt;
2325
19
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2301
545
        const T& rowset_meta_pb) {
2302
545
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2303
545
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2304
0
            return std::nullopt;
2305
0
        }
2306
545
    }
2307
2308
545
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2309
545
    RelatedTxnOrJobAbortTask task;
2310
545
    task.tablet_id = rs_meta.tablet_id();
2311
545
    task.start_version = rs_meta.start_version();
2312
545
    task.end_version = rs_meta.end_version();
2313
545
    task.rowset_id = rs_meta.rowset_id_v2();
2314
545
    if (rs_meta.has_load_id()) {
2315
534
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2316
534
        task.txn_id = rs_meta.txn_id();
2317
534
        return task;
2318
534
    }
2319
11
    if (rs_meta.has_job_id()) {
2320
10
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2321
10
        task.job_id = rs_meta.job_id();
2322
10
        return task;
2323
10
    }
2324
1
    return std::nullopt;
2325
11
}
_ZN5doris5cloud34make_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEESt8optionalINS0_24RelatedTxnOrJobAbortTaskEERKT_
Line
Count
Source
2301
526
        const T& rowset_meta_pb) {
2302
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2303
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2304
            return std::nullopt;
2305
        }
2306
    }
2307
2308
526
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2309
526
    RelatedTxnOrJobAbortTask task;
2310
526
    task.tablet_id = rs_meta.tablet_id();
2311
526
    task.start_version = rs_meta.start_version();
2312
526
    task.end_version = rs_meta.end_version();
2313
526
    task.rowset_id = rs_meta.rowset_id_v2();
2314
526
    if (rs_meta.has_load_id()) {
2315
518
        task.type = RelatedTxnOrJobAbortTask::Type::TXN;
2316
518
        task.txn_id = rs_meta.txn_id();
2317
518
        return task;
2318
518
    }
2319
8
    if (rs_meta.has_job_id()) {
2320
4
        task.type = RelatedTxnOrJobAbortTask::Type::JOB;
2321
4
        task.job_id = rs_meta.job_id();
2322
4
        return task;
2323
4
    }
2324
4
    return std::nullopt;
2325
8
}
2326
2327
template <typename T>
2328
bool matches_related_txn_or_job_abort_task(const T& rowset_meta_pb,
2329
529
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2330
529
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2331
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2332
0
            return false;
2333
0
        }
2334
268
    }
2335
2336
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2337
529
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2338
529
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2339
0
        return false;
2340
0
    }
2341
529
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2342
523
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2343
523
    }
2344
6
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2345
529
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS0_15RecycleRowsetPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2329
268
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2330
268
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2331
268
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2332
0
            return false;
2333
0
        }
2334
268
    }
2335
2336
268
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2337
268
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2338
268
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2339
0
        return false;
2340
0
    }
2341
268
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2342
264
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2343
264
    }
2344
4
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2345
268
}
_ZN5doris5cloud37matches_related_txn_or_job_abort_taskINS_17RowsetMetaCloudPBEEEbRKT_RKNS0_24RelatedTxnOrJobAbortTaskE
Line
Count
Source
2329
261
                                           const RelatedTxnOrJobAbortTask& abort_task) {
2330
    if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2331
        if (rowset_meta_pb.type() != RecycleRowsetPB::PREPARE) {
2332
            return false;
2333
        }
2334
    }
2335
2336
261
    const auto& rs_meta = rowset_meta(rowset_meta_pb);
2337
261
    if (rs_meta.tablet_id() != abort_task.tablet_id ||
2338
261
        rs_meta.rowset_id_v2() != abort_task.rowset_id) {
2339
0
        return false;
2340
0
    }
2341
261
    if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2342
259
        return rs_meta.has_load_id() && rs_meta.txn_id() == abort_task.txn_id;
2343
259
    }
2344
2
    return rs_meta.has_job_id() && rs_meta.job_id() == abort_task.job_id;
2345
261
}
2346
2347
71
bool need_mark_rowset_as_recycled(const RowsetMetaCloudPB& rowset_meta_pb) {
2348
71
    return !rowset_meta_pb.has_is_recycled() || !rowset_meta_pb.is_recycled();
2349
71
}
2350
2351
template <typename T>
2352
int batch_mark_rowsets_as_recycled(TxnKv* txn_kv, const std::string& instance_id,
2353
18
                                   const std::vector<std::string>& keys) {
2354
35
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2355
18
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2356
18
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2357
18
        std::unique_ptr<Transaction> txn;
2358
18
        TxnErrorCode err = txn_kv->create_txn(&txn);
2359
18
        if (err != TxnErrorCode::TXN_OK) {
2360
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2361
0
            return -1;
2362
0
        }
2363
18
        std::vector<std::optional<std::string>> values;
2364
18
        err = txn->batch_get(&values, batch_keys);
2365
18
        if (err != TxnErrorCode::TXN_OK) {
2366
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2367
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2368
0
            return -1;
2369
0
        }
2370
18
        DCHECK_EQ(values.size(), batch_keys.size());
2371
40
        for (size_t i = 0; i < batch_keys.size(); i++) {
2372
22
            if (!values[i].has_value()) {
2373
                // has already been removed by commit_rowset
2374
0
                continue;
2375
0
            }
2376
22
            const auto& key = batch_keys[i];
2377
22
            auto val = values[i].value();
2378
22
            T rowset_meta_pb;
2379
22
            if (!rowset_meta_pb.ParseFromString(val)) {
2380
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2381
0
                             << " key=" << hex(key);
2382
0
                return -1;
2383
0
            }
2384
22
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2385
0
                continue;
2386
0
            }
2387
22
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2388
22
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2389
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2390
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2391
13
            }
2392
22
            val.clear();
2393
22
            rowset_meta_pb.SerializeToString(&val);
2394
22
            txn->put(key, val);
2395
22
        }
2396
18
        err = txn->commit();
2397
18
        if (err != TxnErrorCode::TXN_OK) {
2398
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2399
1
            return -1;
2400
1
        }
2401
18
    }
2402
2403
17
    return 0;
2404
18
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2353
11
                                   const std::vector<std::string>& keys) {
2354
21
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2355
11
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2356
11
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2357
11
        std::unique_ptr<Transaction> txn;
2358
11
        TxnErrorCode err = txn_kv->create_txn(&txn);
2359
11
        if (err != TxnErrorCode::TXN_OK) {
2360
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2361
0
            return -1;
2362
0
        }
2363
11
        std::vector<std::optional<std::string>> values;
2364
11
        err = txn->batch_get(&values, batch_keys);
2365
11
        if (err != TxnErrorCode::TXN_OK) {
2366
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2367
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2368
0
            return -1;
2369
0
        }
2370
11
        DCHECK_EQ(values.size(), batch_keys.size());
2371
24
        for (size_t i = 0; i < batch_keys.size(); i++) {
2372
13
            if (!values[i].has_value()) {
2373
                // has already been removed by commit_rowset
2374
0
                continue;
2375
0
            }
2376
13
            const auto& key = batch_keys[i];
2377
13
            auto val = values[i].value();
2378
13
            T rowset_meta_pb;
2379
13
            if (!rowset_meta_pb.ParseFromString(val)) {
2380
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2381
0
                             << " key=" << hex(key);
2382
0
                return -1;
2383
0
            }
2384
13
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2385
0
                continue;
2386
0
            }
2387
13
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2388
13
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2389
13
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2390
13
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2391
13
            }
2392
13
            val.clear();
2393
13
            rowset_meta_pb.SerializeToString(&val);
2394
13
            txn->put(key, val);
2395
13
        }
2396
11
        err = txn->commit();
2397
11
        if (err != TxnErrorCode::TXN_OK) {
2398
1
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2399
1
            return -1;
2400
1
        }
2401
11
    }
2402
2403
10
    return 0;
2404
11
}
_ZN5doris5cloud30batch_mark_rowsets_as_recycledINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EE
Line
Count
Source
2353
7
                                   const std::vector<std::string>& keys) {
2354
14
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2355
7
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2356
7
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2357
7
        std::unique_ptr<Transaction> txn;
2358
7
        TxnErrorCode err = txn_kv->create_txn(&txn);
2359
7
        if (err != TxnErrorCode::TXN_OK) {
2360
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2361
0
            return -1;
2362
0
        }
2363
7
        std::vector<std::optional<std::string>> values;
2364
7
        err = txn->batch_get(&values, batch_keys);
2365
7
        if (err != TxnErrorCode::TXN_OK) {
2366
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id << ' '
2367
0
                         << "keys size=" << batch_keys.size() << ' ' << "err=" << err;
2368
0
            return -1;
2369
0
        }
2370
7
        DCHECK_EQ(values.size(), batch_keys.size());
2371
16
        for (size_t i = 0; i < batch_keys.size(); i++) {
2372
9
            if (!values[i].has_value()) {
2373
                // has already been removed by commit_rowset
2374
0
                continue;
2375
0
            }
2376
9
            const auto& key = batch_keys[i];
2377
9
            auto val = values[i].value();
2378
9
            T rowset_meta_pb;
2379
9
            if (!rowset_meta_pb.ParseFromString(val)) {
2380
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2381
0
                             << " key=" << hex(key);
2382
0
                return -1;
2383
0
            }
2384
9
            if (!need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2385
0
                continue;
2386
0
            }
2387
9
            mutable_rowset_meta(rowset_meta_pb)->set_is_recycled(true);
2388
            if constexpr (std::is_same_v<T, RecycleRowsetPB>) {
2389
                [[maybe_unused]] auto type = rowset_meta_pb.type();
2390
                TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_mark_rowsets_as_recycled", &type);
2391
            }
2392
9
            val.clear();
2393
9
            rowset_meta_pb.SerializeToString(&val);
2394
9
            txn->put(key, val);
2395
9
        }
2396
7
        err = txn->commit();
2397
7
        if (err != TxnErrorCode::TXN_OK) {
2398
0
            LOG(WARNING) << "failed to commit txn, instance_id=" << instance_id;
2399
0
            return -1;
2400
0
        }
2401
7
    }
2402
2403
7
    return 0;
2404
7
}
2405
2406
template <typename T>
2407
void InstanceRecycler::submit_batch_mark_rowsets_as_recycled_job(
2408
18
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2409
18
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2410
18
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2411
1
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2412
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2413
1
        }
2414
18
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2409
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2410
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2411
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2412
1
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2413
1
        }
2414
11
    });
_ZZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EEENKUlvE_clEv
Line
Count
Source
2409
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2410
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2411
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2412
0
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2413
0
        }
2414
7
    });
2415
18
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS0_15RecycleRowsetPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2408
11
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2409
11
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2410
11
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2411
11
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2412
11
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2413
11
        }
2414
11
    });
2415
11
}
_ZN5doris5cloud16InstanceRecycler41submit_batch_mark_rowsets_as_recycled_jobINS_17RowsetMetaCloudPBEEEvRNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISC_EE
Line
Count
Source
2408
7
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_mark) {
2409
7
    worker_pool.submit([this, mark_keys = std::move(rowset_keys_to_mark)]() {
2410
7
        if (batch_mark_rowsets_as_recycled<T>(txn_kv_.get(), instance_id_, mark_keys) != 0) {
2411
7
            LOG(WARNING) << "failed to batch mark rowsets as recycled, instance_id=" << instance_id_
2412
7
                         << ' ' << "rowset_keys_to_mark.size()=" << mark_keys.size();
2413
7
        }
2414
7
    });
2415
7
}
2416
2417
template <typename T>
2418
int collect_deferred_abort_tasks(TxnKv* txn_kv, const std::string& instance_id,
2419
                                 const std::vector<std::string>& keys,
2420
20
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2421
42
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2422
22
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2423
22
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2424
22
        std::unique_ptr<Transaction> txn;
2425
22
        TxnErrorCode err = txn_kv->create_txn(&txn);
2426
22
        if (err != TxnErrorCode::TXN_OK) {
2427
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2428
0
            return -1;
2429
0
        }
2430
22
        std::vector<std::optional<std::string>> values;
2431
22
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2432
22
        if (err != TxnErrorCode::TXN_OK) {
2433
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2434
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2435
0
            return -1;
2436
0
        }
2437
22
        DCHECK_EQ(values.size(), batch_keys.size());
2438
555
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2439
533
            const std::string& key = batch_keys[idx];
2440
533
            if (!values[idx].has_value()) {
2441
                // has already been removed
2442
0
                continue;
2443
0
            }
2444
533
            T rowset_meta_pb;
2445
533
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2446
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2447
0
                             << " key=" << hex(key);
2448
0
                return -1;
2449
0
            }
2450
533
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2451
533
                abort_task.has_value()) {
2452
533
                abort_task->key = key;
2453
533
                abort_tasks->emplace_back(std::move(*abort_task));
2454
533
            }
2455
533
        }
2456
22
    }
2457
20
    return 0;
2458
20
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2420
15
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2421
31
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2422
16
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2423
16
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2424
16
        std::unique_ptr<Transaction> txn;
2425
16
        TxnErrorCode err = txn_kv->create_txn(&txn);
2426
16
        if (err != TxnErrorCode::TXN_OK) {
2427
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2428
0
            return -1;
2429
0
        }
2430
16
        std::vector<std::optional<std::string>> values;
2431
16
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2432
16
        if (err != TxnErrorCode::TXN_OK) {
2433
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2434
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2435
0
            return -1;
2436
0
        }
2437
16
        DCHECK_EQ(values.size(), batch_keys.size());
2438
288
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2439
272
            const std::string& key = batch_keys[idx];
2440
272
            if (!values[idx].has_value()) {
2441
                // has already been removed
2442
0
                continue;
2443
0
            }
2444
272
            T rowset_meta_pb;
2445
272
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2446
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2447
0
                             << " key=" << hex(key);
2448
0
                return -1;
2449
0
            }
2450
272
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2451
272
                abort_task.has_value()) {
2452
272
                abort_task->key = key;
2453
272
                abort_tasks->emplace_back(std::move(*abort_task));
2454
272
            }
2455
272
        }
2456
16
    }
2457
15
    return 0;
2458
15
}
_ZN5doris5cloud28collect_deferred_abort_tasksINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISA_SaISA_EEPSD_INS0_24RelatedTxnOrJobAbortTaskESaISI_EE
Line
Count
Source
2420
5
                                 std::vector<RelatedTxnOrJobAbortTask>* abort_tasks) {
2421
11
    for (size_t offset = 0; offset < keys.size(); offset += kRowsetBatchGetSize) {
2422
6
        size_t limit = std::min(keys.size(), offset + kRowsetBatchGetSize);
2423
6
        std::vector<std::string> batch_keys(keys.begin() + offset, keys.begin() + limit);
2424
6
        std::unique_ptr<Transaction> txn;
2425
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2426
6
        if (err != TxnErrorCode::TXN_OK) {
2427
0
            LOG(WARNING) << "failed to create txn, instance_id=" << instance_id;
2428
0
            return -1;
2429
0
        }
2430
6
        std::vector<std::optional<std::string>> values;
2431
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2432
6
        if (err != TxnErrorCode::TXN_OK) {
2433
0
            LOG(WARNING) << "failed to batch get rowset meta, instance_id=" << instance_id
2434
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2435
0
            return -1;
2436
0
        }
2437
6
        DCHECK_EQ(values.size(), batch_keys.size());
2438
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2439
261
            const std::string& key = batch_keys[idx];
2440
261
            if (!values[idx].has_value()) {
2441
                // has already been removed
2442
0
                continue;
2443
0
            }
2444
261
            T rowset_meta_pb;
2445
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2446
0
                LOG(WARNING) << "failed to parse rowset meta, instance_id=" << instance_id
2447
0
                             << " key=" << hex(key);
2448
0
                return -1;
2449
0
            }
2450
261
            if (auto abort_task = make_related_txn_or_job_abort_task(rowset_meta_pb);
2451
261
                abort_task.has_value()) {
2452
261
                abort_task->key = key;
2453
261
                abort_tasks->emplace_back(std::move(*abort_task));
2454
261
            }
2455
261
        }
2456
6
    }
2457
5
    return 0;
2458
5
}
2459
2460
template <typename T>
2461
int batch_recheck_rowsets_after_abort(
2462
        TxnKv* txn_kv, const std::string& instance_id,
2463
        const std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck,
2464
18
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2465
18
    int ret = 0;
2466
38
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2467
20
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2468
20
        std::vector<std::string> batch_keys;
2469
20
        batch_keys.reserve(limit - offset);
2470
550
        for (size_t idx = offset; idx < limit; ++idx) {
2471
530
            batch_keys.push_back(keys_to_recheck[idx].first);
2472
530
        }
2473
2474
20
        std::unique_ptr<Transaction> txn;
2475
20
        TxnErrorCode err = txn_kv->create_txn(&txn);
2476
20
        if (err != TxnErrorCode::TXN_OK) {
2477
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2478
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2479
0
            ret = -1;
2480
0
            continue;
2481
0
        }
2482
2483
20
        std::vector<std::optional<std::string>> values;
2484
20
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2485
20
        if (err != TxnErrorCode::TXN_OK) {
2486
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2487
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2488
0
            ret = -1;
2489
0
            continue;
2490
0
        }
2491
20
        DCHECK_EQ(values.size(), batch_keys.size());
2492
20
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2493
20
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2494
20
                                 &batch_size);
2495
2496
550
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2497
530
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2498
530
            if (!values[idx].has_value()) {
2499
1
                continue;
2500
1
            }
2501
2502
529
            T rowset_meta_pb;
2503
529
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2504
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2505
0
                             << instance_id << " key=" << hex(key);
2506
0
                ret = -1;
2507
0
                continue;
2508
0
            }
2509
529
            if (config::enable_mark_delete_rowset_before_recycle &&
2510
529
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2511
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2512
0
                             << instance_id << " key=" << hex(key);
2513
0
                continue;
2514
0
            }
2515
529
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2516
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2517
1
                             << instance_id << " key=" << hex(key);
2518
1
                continue;
2519
1
            }
2520
528
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2521
528
        }
2522
20
    }
2523
18
    return ret;
2524
18
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS0_15RecycleRowsetPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2464
13
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2465
13
    int ret = 0;
2466
27
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2467
14
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2468
14
        std::vector<std::string> batch_keys;
2469
14
        batch_keys.reserve(limit - offset);
2470
283
        for (size_t idx = offset; idx < limit; ++idx) {
2471
269
            batch_keys.push_back(keys_to_recheck[idx].first);
2472
269
        }
2473
2474
14
        std::unique_ptr<Transaction> txn;
2475
14
        TxnErrorCode err = txn_kv->create_txn(&txn);
2476
14
        if (err != TxnErrorCode::TXN_OK) {
2477
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2478
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2479
0
            ret = -1;
2480
0
            continue;
2481
0
        }
2482
2483
14
        std::vector<std::optional<std::string>> values;
2484
14
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2485
14
        if (err != TxnErrorCode::TXN_OK) {
2486
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2487
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2488
0
            ret = -1;
2489
0
            continue;
2490
0
        }
2491
14
        DCHECK_EQ(values.size(), batch_keys.size());
2492
14
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2493
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2494
14
                                 &batch_size);
2495
2496
283
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2497
269
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2498
269
            if (!values[idx].has_value()) {
2499
1
                continue;
2500
1
            }
2501
2502
268
            T rowset_meta_pb;
2503
268
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2504
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2505
0
                             << instance_id << " key=" << hex(key);
2506
0
                ret = -1;
2507
0
                continue;
2508
0
            }
2509
268
            if (config::enable_mark_delete_rowset_before_recycle &&
2510
268
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2511
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2512
0
                             << instance_id << " key=" << hex(key);
2513
0
                continue;
2514
0
            }
2515
268
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2516
1
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2517
1
                             << instance_id << " key=" << hex(key);
2518
1
                continue;
2519
1
            }
2520
267
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2521
267
        }
2522
14
    }
2523
13
    return ret;
2524
13
}
_ZN5doris5cloud33batch_recheck_rowsets_after_abortINS_17RowsetMetaCloudPBEEEiPNS0_5TxnKvERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKSt6vectorISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISG_EEPSD_ISE_ISA_T_ESaISM_EE
Line
Count
Source
2464
5
        std::vector<std::pair<std::string, T>>* rowsets_to_recycle) {
2465
5
    int ret = 0;
2466
11
    for (size_t offset = 0; offset < keys_to_recheck.size(); offset += kRowsetBatchGetSize) {
2467
6
        size_t limit = std::min(keys_to_recheck.size(), offset + kRowsetBatchGetSize);
2468
6
        std::vector<std::string> batch_keys;
2469
6
        batch_keys.reserve(limit - offset);
2470
267
        for (size_t idx = offset; idx < limit; ++idx) {
2471
261
            batch_keys.push_back(keys_to_recheck[idx].first);
2472
261
        }
2473
2474
6
        std::unique_ptr<Transaction> txn;
2475
6
        TxnErrorCode err = txn_kv->create_txn(&txn);
2476
6
        if (err != TxnErrorCode::TXN_OK) {
2477
0
            LOG(WARNING) << "failed to create txn for rowset recheck, instance_id=" << instance_id
2478
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2479
0
            ret = -1;
2480
0
            continue;
2481
0
        }
2482
2483
6
        std::vector<std::optional<std::string>> values;
2484
6
        err = txn->batch_get(&values, batch_keys, Transaction::BatchGetOptions(true));
2485
6
        if (err != TxnErrorCode::TXN_OK) {
2486
0
            LOG(WARNING) << "failed to batch recheck rowset meta, instance_id=" << instance_id
2487
0
                         << " keys_size=" << batch_keys.size() << " err=" << err;
2488
0
            ret = -1;
2489
0
            continue;
2490
0
        }
2491
6
        DCHECK_EQ(values.size(), batch_keys.size());
2492
6
        [[maybe_unused]] size_t batch_size = batch_keys.size();
2493
6
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_recheck_rowsets_after_abort",
2494
6
                                 &batch_size);
2495
2496
267
        for (size_t idx = 0; idx < batch_keys.size(); ++idx) {
2497
261
            const auto& [key, abort_task] = keys_to_recheck[offset + idx];
2498
261
            if (!values[idx].has_value()) {
2499
0
                continue;
2500
0
            }
2501
2502
261
            T rowset_meta_pb;
2503
261
            if (!rowset_meta_pb.ParseFromString(*values[idx])) {
2504
0
                LOG(WARNING) << "failed to parse rowset meta during abort recheck, instance_id="
2505
0
                             << instance_id << " key=" << hex(key);
2506
0
                ret = -1;
2507
0
                continue;
2508
0
            }
2509
261
            if (config::enable_mark_delete_rowset_before_recycle &&
2510
261
                need_mark_rowset_as_recycled(rowset_meta(rowset_meta_pb))) {
2511
0
                LOG(WARNING) << "skip unmarked rowset during abort recheck, instance_id="
2512
0
                             << instance_id << " key=" << hex(key);
2513
0
                continue;
2514
0
            }
2515
261
            if (!matches_related_txn_or_job_abort_task(rowset_meta_pb, abort_task)) {
2516
0
                LOG(WARNING) << "skip changed rowset during abort recheck, instance_id="
2517
0
                             << instance_id << " key=" << hex(key);
2518
0
                continue;
2519
0
            }
2520
261
            rowsets_to_recycle->emplace_back(key, std::move(rowset_meta_pb));
2521
261
        }
2522
6
    }
2523
5
    return ret;
2524
5
}
2525
2526
template <typename T>
2527
int InstanceRecycler::batch_abort_txn_or_job_for_recycle(
2528
        const std::vector<std::string>& keys,
2529
20
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2530
20
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2531
20
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2532
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2533
0
        return -1;
2534
0
    }
2535
20
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2536
20
    int ret = 0;
2537
533
    for (const auto& abort_task : abort_tasks) {
2538
533
        int abort_ret = 0;
2539
533
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2540
526
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2541
526
        } else {
2542
7
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2543
7
                                                     abort_task.job_id);
2544
7
        }
2545
533
        if (abort_ret != 0) {
2546
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2547
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2548
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2549
3
            ret = abort_ret;
2550
3
            continue;
2551
3
        }
2552
530
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2553
530
    }
2554
20
    return ret;
2555
20
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS0_15RecycleRowsetPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2529
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2530
15
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2531
15
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2532
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2533
0
        return -1;
2534
0
    }
2535
15
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2536
15
    int ret = 0;
2537
272
    for (const auto& abort_task : abort_tasks) {
2538
272
        int abort_ret = 0;
2539
272
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2540
267
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2541
267
        } else {
2542
5
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2543
5
                                                     abort_task.job_id);
2544
5
        }
2545
272
        if (abort_ret != 0) {
2546
3
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2547
3
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2548
3
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2549
3
            ret = abort_ret;
2550
3
            continue;
2551
3
        }
2552
269
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2553
269
    }
2554
15
    return ret;
2555
15
}
_ZN5doris5cloud16InstanceRecycler34batch_abort_txn_or_job_for_recycleINS_17RowsetMetaCloudPBEEEiRKSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EERS4_ISt4pairISA_NS0_24RelatedTxnOrJobAbortTaskEESaISH_EE
Line
Count
Source
2529
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>>& keys_to_recheck) {
2530
5
    std::vector<RelatedTxnOrJobAbortTask> abort_tasks;
2531
5
    if (collect_deferred_abort_tasks<T>(txn_kv_.get(), instance_id_, keys, &abort_tasks) != 0) {
2532
0
        LOG(WARNING) << "failed to collect rowset abort tasks, instance_id=" << instance_id_;
2533
0
        return -1;
2534
0
    }
2535
5
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::batch_abort_txn_or_job_for_recycle::after_collect");
2536
5
    int ret = 0;
2537
261
    for (const auto& abort_task : abort_tasks) {
2538
261
        int abort_ret = 0;
2539
261
        if (abort_task.type == RelatedTxnOrJobAbortTask::Type::TXN) {
2540
259
            abort_ret = abort_txn_for_related_rowset(abort_task.txn_id);
2541
259
        } else {
2542
2
            abort_ret = abort_job_for_related_rowset(abort_task.tablet_id, abort_task.rowset_id,
2543
2
                                                     abort_task.job_id);
2544
2
        }
2545
261
        if (abort_ret != 0) {
2546
0
            LOG(WARNING) << "failed to abort txn or job for related rowset, instance_id="
2547
0
                         << instance_id_ << " tablet_id=" << abort_task.tablet_id << " version=["
2548
0
                         << abort_task.start_version << '-' << abort_task.end_version << "]";
2549
0
            ret = abort_ret;
2550
0
            continue;
2551
0
        }
2552
261
        keys_to_recheck.emplace_back(abort_task.key, abort_task);
2553
261
    }
2554
5
    return ret;
2555
5
}
2556
2557
void InstanceRecycler::submit_recycle_prepare_rowsets_job(
2558
        SimpleThreadPool& worker_pool, std::vector<std::string> rowset_keys_to_abort,
2559
15
        std::atomic_long* num_recycled, RecyclerMetricsContext* metrics_context) {
2560
15
    int ret = worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort),
2561
15
                                  num_recycled, metrics_context]() mutable {
2562
15
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2563
15
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2564
15
                                                                            keys_to_recheck);
2565
15
        if (abort_ret != 0) {
2566
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2567
2
                            "instance_id="
2568
2
                         << instance_id_;
2569
2
        }
2570
15
        if (keys_to_recheck.empty()) {
2571
2
            return;
2572
2
        }
2573
2574
13
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2575
13
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2576
13
                                                            keys_to_recheck, &rowsets_to_recycle);
2577
13
        if (recheck_ret != 0) {
2578
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2579
0
                         << instance_id_;
2580
0
        }
2581
267
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2582
267
            const auto& current_meta = current_rowset.rowset_meta();
2583
267
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2584
267
                                   current_meta.rowset_id_v2()) != 0) {
2585
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2586
1
                continue;
2587
1
            }
2588
266
            metrics_context->kv_recycled_bytes += current_rowset.rowset_meta().total_disk_size();
2589
266
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2590
266
                                                   current_meta.tablet_id(),
2591
266
                                                   current_meta.rowset_id_v2()) != 0) {
2592
0
                continue;
2593
0
            }
2594
266
            std::vector<std::string> keys {key};
2595
266
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2596
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2597
0
                continue;
2598
0
            }
2599
266
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2600
266
        }
2601
13
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2561
2
                                  num_recycled, metrics_context]() mutable {
2562
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2563
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2564
2
                                                                            keys_to_recheck);
2565
2
        if (abort_ret != 0) {
2566
0
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2567
0
                            "instance_id="
2568
0
                         << instance_id_;
2569
0
        }
2570
2
        if (keys_to_recheck.empty()) {
2571
0
            return;
2572
0
        }
2573
2574
2
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2575
2
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2576
2
                                                            keys_to_recheck, &rowsets_to_recycle);
2577
2
        if (recheck_ret != 0) {
2578
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2579
0
                         << instance_id_;
2580
0
        }
2581
2
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2582
2
            const auto& current_meta = current_rowset.rowset_meta();
2583
2
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2584
2
                                   current_meta.rowset_id_v2()) != 0) {
2585
0
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2586
0
                continue;
2587
0
            }
2588
2
            metrics_context->kv_recycled_bytes += current_rowset.rowset_meta().total_disk_size();
2589
2
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2590
2
                                                   current_meta.tablet_id(),
2591
2
                                                   current_meta.rowset_id_v2()) != 0) {
2592
0
                continue;
2593
0
            }
2594
2
            std::vector<std::string> keys {key};
2595
2
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2596
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2597
0
                continue;
2598
0
            }
2599
2
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2600
2
        }
2601
2
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34submit_recycle_prepare_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2561
13
                                  num_recycled, metrics_context]() mutable {
2562
13
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> keys_to_recheck;
2563
13
        int abort_ret = batch_abort_txn_or_job_for_recycle<RecycleRowsetPB>(rowset_keys_to_abort,
2564
13
                                                                            keys_to_recheck);
2565
13
        if (abort_ret != 0) {
2566
2
            LOG(WARNING) << "failed to abort some txn or job for related rowset, "
2567
2
                            "instance_id="
2568
2
                         << instance_id_;
2569
2
        }
2570
13
        if (keys_to_recheck.empty()) {
2571
2
            return;
2572
2
        }
2573
2574
11
        std::vector<std::pair<std::string, RecycleRowsetPB>> rowsets_to_recycle;
2575
11
        int recheck_ret = batch_recheck_rowsets_after_abort(txn_kv_.get(), instance_id_,
2576
11
                                                            keys_to_recheck, &rowsets_to_recycle);
2577
11
        if (recheck_ret != 0) {
2578
0
            LOG(WARNING) << "failed to recheck some recycle rowsets after abort, instance_id="
2579
0
                         << instance_id_;
2580
0
        }
2581
265
        for (const auto& [key, current_rowset] : rowsets_to_recycle) {
2582
265
            const auto& current_meta = current_rowset.rowset_meta();
2583
265
            if (delete_rowset_data(current_meta.resource_id(), current_meta.tablet_id(),
2584
265
                                   current_meta.rowset_id_v2()) != 0) {
2585
1
                LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
2586
1
                continue;
2587
1
            }
2588
264
            metrics_context->kv_recycled_bytes += current_rowset.rowset_meta().total_disk_size();
2589
264
            if (delete_versioned_delete_bitmap_kvs(current_meta.partition_id(),
2590
264
                                                   current_meta.tablet_id(),
2591
264
                                                   current_meta.rowset_id_v2()) != 0) {
2592
0
                continue;
2593
0
            }
2594
264
            std::vector<std::string> keys {key};
2595
264
            if (txn_remove(txn_kv_.get(), keys) != 0) {
2596
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
2597
0
                continue;
2598
0
            }
2599
264
            num_recycled->fetch_add(1, std::memory_order_relaxed);
2600
264
        }
2601
11
    });
2602
15
    if (ret != 0) {
2603
0
        LOG(WARNING) << "failed to submit recycle prepare rowset job, instance_id=" << instance_id_;
2604
0
    }
2605
15
}
2606
2607
void InstanceRecycler::submit_recycle_tmp_rowsets_job(SimpleThreadPool& worker_pool,
2608
                                                      std::vector<std::string> rowset_keys_to_abort,
2609
                                                      std::atomic_long* num_recycled,
2610
5
                                                      RecyclerMetricsContext* metrics_context) {
2611
5
    if (rowset_keys_to_abort.empty()) {
2612
0
        return;
2613
0
    }
2614
5
    worker_pool.submit([this, rowset_keys_to_abort = std::move(rowset_keys_to_abort), num_recycled,
2615
5
                        metrics_context]() mutable {
2616
5
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2617
5
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2618
5
                rowset_keys_to_abort, abort_keys_to_recheck);
2619
5
        if (abort_ret != 0) {
2620
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2621
0
                            "instance_id="
2622
0
                         << instance_id_;
2623
0
        }
2624
2625
5
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2626
5
        std::vector<std::string> keys_to_delete;
2627
5
        std::vector<std::string> ref_count_keys_to_delete;
2628
5
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2629
5
        int recheck_ret = batch_recheck_rowsets_after_abort(
2630
5
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2631
5
        if (recheck_ret != 0) {
2632
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2633
0
                         << instance_id_;
2634
0
        }
2635
261
        for (auto& [key, rowset] : rowsets_to_recycle) {
2636
261
            keys_to_delete.push_back(key);
2637
261
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2638
261
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2639
261
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2640
261
        }
2641
2642
5
        if (keys_to_delete.empty()) {
2643
0
            return;
2644
0
        }
2645
5
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2646
5
                               *metrics_context) != 0) {
2647
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2648
0
            return;
2649
0
        }
2650
261
        for (const auto& [_, rowset] : rowsets_to_delete) {
2651
261
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2652
261
                                                   rowset.rowset_id_v2()) != 0) {
2653
0
                return;
2654
0
            }
2655
261
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2656
0
                return;
2657
0
            }
2658
261
        }
2659
5
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2661
0
            return;
2662
0
        }
2663
5
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2664
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2665
0
                         << instance_id_;
2666
0
            return;
2667
0
        }
2668
5
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2669
5
    });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2615
3
                        metrics_context]() mutable {
2616
3
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2617
3
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2618
3
                rowset_keys_to_abort, abort_keys_to_recheck);
2619
3
        if (abort_ret != 0) {
2620
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2621
0
                            "instance_id="
2622
0
                         << instance_id_;
2623
0
        }
2624
2625
3
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2626
3
        std::vector<std::string> keys_to_delete;
2627
3
        std::vector<std::string> ref_count_keys_to_delete;
2628
3
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2629
3
        int recheck_ret = batch_recheck_rowsets_after_abort(
2630
3
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2631
3
        if (recheck_ret != 0) {
2632
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2633
0
                         << instance_id_;
2634
0
        }
2635
3
        for (auto& [key, rowset] : rowsets_to_recycle) {
2636
3
            keys_to_delete.push_back(key);
2637
3
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2638
3
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2639
3
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2640
3
        }
2641
2642
3
        if (keys_to_delete.empty()) {
2643
0
            return;
2644
0
        }
2645
3
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2646
3
                               *metrics_context) != 0) {
2647
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2648
0
            return;
2649
0
        }
2650
3
        for (const auto& [_, rowset] : rowsets_to_delete) {
2651
3
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2652
3
                                                   rowset.rowset_id_v2()) != 0) {
2653
0
                return;
2654
0
            }
2655
3
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2656
0
                return;
2657
0
            }
2658
3
        }
2659
3
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2661
0
            return;
2662
0
        }
2663
3
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2664
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2665
0
                         << instance_id_;
2666
0
            return;
2667
0
        }
2668
3
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2669
3
    });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler30submit_recycle_tmp_rowsets_jobERNS0_16SimpleThreadPoolESt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaISA_EEPSt6atomicIlEPNS0_22RecyclerMetricsContextEEN3$_0clEv
Line
Count
Source
2615
2
                        metrics_context]() mutable {
2616
2
        std::vector<std::pair<std::string, RelatedTxnOrJobAbortTask>> abort_keys_to_recheck;
2617
2
        int abort_ret = batch_abort_txn_or_job_for_recycle<RowsetMetaCloudPB>(
2618
2
                rowset_keys_to_abort, abort_keys_to_recheck);
2619
2
        if (abort_ret != 0) {
2620
0
            LOG(WARNING) << "failed to abort some txn or job for related tmp rowset, "
2621
0
                            "instance_id="
2622
0
                         << instance_id_;
2623
0
        }
2624
2625
2
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
2626
2
        std::vector<std::string> keys_to_delete;
2627
2
        std::vector<std::string> ref_count_keys_to_delete;
2628
2
        std::vector<std::pair<std::string, RowsetMetaCloudPB>> rowsets_to_recycle;
2629
2
        int recheck_ret = batch_recheck_rowsets_after_abort(
2630
2
                txn_kv_.get(), instance_id_, abort_keys_to_recheck, &rowsets_to_recycle);
2631
2
        if (recheck_ret != 0) {
2632
0
            LOG(WARNING) << "failed to recheck some tmp rowsets after abort, instance_id="
2633
0
                         << instance_id_;
2634
0
        }
2635
258
        for (auto& [key, rowset] : rowsets_to_recycle) {
2636
258
            keys_to_delete.push_back(key);
2637
258
            ref_count_keys_to_delete.push_back(versioned::data_rowset_ref_count_key(
2638
258
                    {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()}));
2639
258
            rowsets_to_delete.emplace(rowset.rowset_id_v2(), std::move(rowset));
2640
258
        }
2641
2642
2
        if (keys_to_delete.empty()) {
2643
0
            return;
2644
0
        }
2645
2
        if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
2646
2
                               *metrics_context) != 0) {
2647
0
            LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
2648
0
            return;
2649
0
        }
2650
258
        for (const auto& [_, rowset] : rowsets_to_delete) {
2651
258
            if (delete_versioned_delete_bitmap_kvs(rowset.partition_id(), rowset.tablet_id(),
2652
258
                                                   rowset.rowset_id_v2()) != 0) {
2653
0
                return;
2654
0
            }
2655
258
            if (delete_delete_bitmap_kvs(rowset.tablet_id(), rowset.rowset_id_v2()) != 0) {
2656
0
                return;
2657
0
            }
2658
258
        }
2659
2
        if (txn_remove(txn_kv_.get(), keys_to_delete) != 0) {
2660
0
            LOG(WARNING) << "failed to delete tmp rowset kv, instance_id=" << instance_id_;
2661
0
            return;
2662
0
        }
2663
2
        if (txn_remove(txn_kv_.get(), ref_count_keys_to_delete) != 0) {
2664
0
            LOG(WARNING) << "failed to delete tmp rowset ref count kv, instance_id="
2665
0
                         << instance_id_;
2666
0
            return;
2667
0
        }
2668
2
        num_recycled->fetch_add(keys_to_delete.size(), std::memory_order_relaxed);
2669
2
    });
2670
5
}
2671
2672
1
int InstanceRecycler::recycle_ref_rowsets(bool* has_unrecycled_rowsets) {
2673
1
    const std::string task_name = "recycle_ref_rowsets";
2674
1
    *has_unrecycled_rowsets = false;
2675
2676
1
    std::string data_rowset_ref_count_key_start =
2677
1
            versioned::data_rowset_ref_count_key({instance_id_, 0, ""});
2678
1
    std::string data_rowset_ref_count_key_end =
2679
1
            versioned::data_rowset_ref_count_key({instance_id_, INT64_MAX, ""});
2680
2681
1
    LOG_WARNING("begin to recycle ref rowsets").tag("instance_id", instance_id_);
2682
2683
1
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
2684
1
    register_recycle_task(task_name, start_time);
2685
2686
1
    DORIS_CLOUD_DEFER {
2687
1
        unregister_recycle_task(task_name);
2688
1
        int64_t cost =
2689
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2690
1
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2691
1
                .tag("instance_id", instance_id_);
2692
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_0clEv
Line
Count
Source
2686
1
    DORIS_CLOUD_DEFER {
2687
1
        unregister_recycle_task(task_name);
2688
1
        int64_t cost =
2689
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2690
        LOG_WARNING("recycle ref rowsets finished, cost={}s", cost)
2691
1
                .tag("instance_id", instance_id_);
2692
1
    };
2693
2694
    // Phase 1: Scan to collect all tablet_ids that have rowset ref counts
2695
1
    std::set<int64_t> tablets_with_refs;
2696
1
    int64_t num_scanned = 0;
2697
2698
1
    auto scan_func = [&](std::string_view k, std::string_view v) -> int {
2699
0
        ++num_scanned;
2700
0
        int64_t tablet_id;
2701
0
        std::string rowset_id;
2702
0
        std::string_view key(k);
2703
0
        if (!versioned::decode_data_rowset_ref_count_key(&key, &tablet_id, &rowset_id)) {
2704
0
            LOG_WARNING("failed to decode data rowset ref count key").tag("key", hex(k));
2705
0
            return 0; // Continue scanning
2706
0
        }
2707
2708
0
        tablets_with_refs.insert(tablet_id);
2709
0
        return 0;
2710
0
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_ref_rowsetsEPbENK3$_1clESt17basic_string_viewIcSt11char_traitsIcEES7_
2711
2712
1
    if (scan_and_recycle(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end,
2713
1
                         std::move(scan_func)) != 0) {
2714
0
        LOG_WARNING("failed to scan data rowset ref count keys");
2715
0
        return -1;
2716
0
    }
2717
2718
1
    LOG_INFO("collected {} tablets with rowset refs, scanned {} ref count keys",
2719
1
             tablets_with_refs.size(), num_scanned)
2720
1
            .tag("instance_id", instance_id_);
2721
2722
    // Phase 2: Recycle each tablet
2723
1
    int64_t num_recycled_tablets = 0;
2724
1
    for (int64_t tablet_id : tablets_with_refs) {
2725
0
        if (stopped()) {
2726
0
            LOG_INFO("recycler stopped, skip remaining tablets")
2727
0
                    .tag("instance_id", instance_id_)
2728
0
                    .tag("tablets_processed", num_recycled_tablets)
2729
0
                    .tag("tablets_remaining", tablets_with_refs.size() - num_recycled_tablets);
2730
0
            break;
2731
0
        }
2732
2733
0
        RecyclerMetricsContext metrics_context(instance_id_, task_name);
2734
0
        if (recycle_versioned_tablet(tablet_id, metrics_context) != 0) {
2735
0
            LOG_WARNING("failed to recycle tablet")
2736
0
                    .tag("instance_id", instance_id_)
2737
0
                    .tag("tablet_id", tablet_id);
2738
0
            return -1;
2739
0
        }
2740
0
        ++num_recycled_tablets;
2741
0
    }
2742
2743
1
    LOG_INFO("recycled {} tablets", num_recycled_tablets)
2744
1
            .tag("instance_id", instance_id_)
2745
1
            .tag("total_tablets", tablets_with_refs.size());
2746
2747
    // Phase 3: Scan again to check if any ref count keys still exist
2748
1
    std::unique_ptr<Transaction> txn;
2749
1
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2750
1
    if (err != TxnErrorCode::TXN_OK) {
2751
0
        LOG_WARNING("failed to create txn for final check")
2752
0
                .tag("instance_id", instance_id_)
2753
0
                .tag("err", err);
2754
0
        return -1;
2755
0
    }
2756
2757
1
    std::unique_ptr<RangeGetIterator> iter;
2758
1
    err = txn->get(data_rowset_ref_count_key_start, data_rowset_ref_count_key_end, &iter, true);
2759
1
    if (err != TxnErrorCode::TXN_OK) {
2760
0
        LOG_WARNING("failed to create range iterator for final check")
2761
0
                .tag("instance_id", instance_id_)
2762
0
                .tag("err", err);
2763
0
        return -1;
2764
0
    }
2765
2766
1
    *has_unrecycled_rowsets = iter->has_next();
2767
1
    if (*has_unrecycled_rowsets) {
2768
0
        LOG_INFO("still has unrecycled rowsets after recycle_ref_rowsets")
2769
0
                .tag("instance_id", instance_id_);
2770
0
    }
2771
2772
1
    return 0;
2773
1
}
2774
2775
int InstanceRecycler::recycle_table_stream_offset_prefix(std::string prefix,
2776
16
                                                         RecyclerMetricsContext* metrics_context) {
2777
16
    std::string end = prefix;
2778
16
    end.push_back('\xff');
2779
16
    std::vector<std::string_view> keys;
2780
20.0k
    auto collect_key = [&keys, &metrics_context](std::string_view key, std::string_view) -> int {
2781
20.0k
        metrics_context->kv_scanned_num++;
2782
20.0k
        keys.push_back(key);
2783
20.0k
        return 0;
2784
20.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2780
4
    auto collect_key = [&keys, &metrics_context](std::string_view key, std::string_view) -> int {
2781
4
        metrics_context->kv_scanned_num++;
2782
4
        keys.push_back(key);
2783
4
        return 0;
2784
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_1clESt17basic_string_viewIcS5_ESC_
Line
Count
Source
2780
20.0k
    auto collect_key = [&keys, &metrics_context](std::string_view key, std::string_view) -> int {
2781
20.0k
        metrics_context->kv_scanned_num++;
2782
20.0k
        keys.push_back(key);
2783
20.0k
        return 0;
2784
20.0k
    };
2785
16
    auto remove_keys = [this, &keys, &metrics_context]() -> int {
2786
16
        if (keys.empty()) {
2787
0
            return 0;
2788
0
        }
2789
16
        DORIS_CLOUD_DEFER {
2790
16
            keys.clear();
2791
16
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2789
4
        DORIS_CLOUD_DEFER {
2790
4
            keys.clear();
2791
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEvENKUlvE_clEv
Line
Count
Source
2789
12
        DORIS_CLOUD_DEFER {
2790
12
            keys.clear();
2791
12
        };
2792
16
        const size_t num_keys = keys.size();
2793
16
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2794
0
            LOG_WARNING("failed to delete table stream offsets")
2795
0
                    .tag("instance_id", instance_id_)
2796
0
                    .tag("num_keys", num_keys);
2797
0
            return -1;
2798
0
        }
2799
16
        metrics_context->kv_expired_num += keys.size();
2800
16
        metrics_context->kv_recycled_num += keys.size();
2801
16
        return 0;
2802
16
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2785
4
    auto remove_keys = [this, &keys, &metrics_context]() -> int {
2786
4
        if (keys.empty()) {
2787
0
            return 0;
2788
0
        }
2789
4
        DORIS_CLOUD_DEFER {
2790
4
            keys.clear();
2791
4
        };
2792
4
        const size_t num_keys = keys.size();
2793
4
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2794
0
            LOG_WARNING("failed to delete table stream offsets")
2795
0
                    .tag("instance_id", instance_id_)
2796
0
                    .tag("num_keys", num_keys);
2797
0
            return -1;
2798
0
        }
2799
4
        metrics_context->kv_expired_num += keys.size();
2800
4
        metrics_context->kv_recycled_num += keys.size();
2801
4
        return 0;
2802
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler34recycle_table_stream_offset_prefixENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEPNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
2785
12
    auto remove_keys = [this, &keys, &metrics_context]() -> int {
2786
12
        if (keys.empty()) {
2787
0
            return 0;
2788
0
        }
2789
12
        DORIS_CLOUD_DEFER {
2790
12
            keys.clear();
2791
12
        };
2792
12
        const size_t num_keys = keys.size();
2793
12
        if (txn_remove(txn_kv_.get(), keys) != 0) {
2794
0
            LOG_WARNING("failed to delete table stream offsets")
2795
0
                    .tag("instance_id", instance_id_)
2796
0
                    .tag("num_keys", num_keys);
2797
0
            return -1;
2798
0
        }
2799
12
        metrics_context->kv_expired_num += keys.size();
2800
12
        metrics_context->kv_recycled_num += keys.size();
2801
12
        return 0;
2802
12
    };
2803
16
    return scan_and_recycle(std::move(prefix), end, std::move(collect_key), std::move(remove_keys));
2804
16
}
2805
2806
int InstanceRecycler::finalize_recycle_stream(int64_t stream_id,
2807
                                              const RecycleIndexPB& recycle_index,
2808
8
                                              std::string_view recycle_key) {
2809
8
    std::unique_ptr<Transaction> txn;
2810
8
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2811
8
    if (err != TxnErrorCode::TXN_OK) {
2812
0
        LOG_WARNING("failed to create transaction for final table stream cleanup")
2813
0
                .tag("instance_id", instance_id_)
2814
0
                .tag("stream_id", stream_id)
2815
0
                .tag("err", err);
2816
0
        return -1;
2817
0
    }
2818
2819
8
    std::string current_recycle_value;
2820
8
    err = txn->get(recycle_key, &current_recycle_value);
2821
8
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
2822
0
        return 0;
2823
0
    }
2824
8
    if (err != TxnErrorCode::TXN_OK) {
2825
0
        LOG_WARNING("failed to read table stream recycle index")
2826
0
                .tag("instance_id", instance_id_)
2827
0
                .tag("stream_id", stream_id)
2828
0
                .tag("err", err);
2829
0
        return -1;
2830
0
    }
2831
8
    RecycleIndexPB current_recycle_index;
2832
8
    if (!current_recycle_index.ParseFromString(current_recycle_value) ||
2833
8
        current_recycle_index.state() != RecycleIndexPB::RECYCLING ||
2834
8
        current_recycle_index.object_type() != IndexObjectTypePB::TABLE_STREAM ||
2835
8
        current_recycle_index.db_id() != recycle_index.db_id() ||
2836
8
        current_recycle_index.table_id() != recycle_index.table_id() ||
2837
8
        current_recycle_index.stream_db_id() != recycle_index.stream_db_id()) {
2838
0
        LOG_WARNING("table stream recycle index changed during recycling")
2839
0
                .tag("instance_id", instance_id_)
2840
0
                .tag("stream_id", stream_id);
2841
0
        return -1;
2842
0
    }
2843
2844
8
    txn->remove(recycle_key);
2845
8
    err = txn->commit();
2846
8
    if (err != TxnErrorCode::TXN_OK) {
2847
0
        LOG_WARNING("failed to commit final table stream cleanup")
2848
0
                .tag("instance_id", instance_id_)
2849
0
                .tag("stream_id", stream_id)
2850
0
                .tag("err", err);
2851
0
        return -1;
2852
0
    }
2853
8
    return 0;
2854
8
}
2855
2856
int InstanceRecycler::recycle_stream(int64_t stream_id, const RecycleIndexPB& recycle_index,
2857
8
                                     std::string_view recycle_key) {
2858
8
    if (!recycle_index.has_db_id() || !recycle_index.has_stream_db_id()) {
2859
0
        LOG_WARNING("table stream recycle index is missing binding")
2860
0
                .tag("instance_id", instance_id_)
2861
0
                .tag("stream_id", stream_id);
2862
0
        return -1;
2863
0
    }
2864
2865
8
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream");
2866
8
    const std::string latest_offset_prefix = table_stream_offset_key_prefix(
2867
8
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2868
8
            recycle_index.stream_db_id(), stream_id);
2869
8
    if (recycle_table_stream_offset_prefix(latest_offset_prefix, &metrics_context) != 0) {
2870
0
        return -1;
2871
0
    }
2872
8
    const std::string versioned_offset_prefix = versioned::table_stream_offset_key_prefix(
2873
8
            instance_id_, recycle_index.db_id(), recycle_index.table_id(),
2874
8
            recycle_index.stream_db_id(), stream_id);
2875
8
    if (recycle_table_stream_offset_prefix(versioned_offset_prefix, &metrics_context) != 0 ||
2876
8
        stopped()) {
2877
0
        return -1;
2878
0
    }
2879
8
    return finalize_recycle_stream(stream_id, recycle_index, recycle_key);
2880
8
}
2881
2882
int InstanceRecycler::recycle_partition_table_stream_offsets(
2883
        int64_t db_id, int64_t table_id, int64_t partition_id,
2884
12
        const google::protobuf::RepeatedPtrField<TableStreamIdentityPB>& table_streams) {
2885
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_stream_partition_offsets");
2886
12
    metrics_context.kv_scanned_num += table_streams.size();
2887
12
    metrics_context.kv_expired_num += table_streams.size();
2888
12
    const size_t batch_size = std::max(1, config::recycler_max_tasks_per_batch);
2889
17
    for (size_t begin_index = 0; begin_index < table_streams.size(); begin_index += batch_size) {
2890
5
        const size_t end_index =
2891
5
                std::min(static_cast<size_t>(table_streams.size()), begin_index + batch_size);
2892
5
        std::unique_ptr<Transaction> txn;
2893
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2894
5
        if (err != TxnErrorCode::TXN_OK) {
2895
0
            LOG_WARNING("failed to create transaction for partition stream offset cleanup")
2896
0
                    .tag("instance_id", instance_id_)
2897
0
                    .tag("partition_id", partition_id)
2898
0
                    .tag("err", err);
2899
0
            return -1;
2900
0
        }
2901
12
        for (size_t i = begin_index; i < end_index; ++i) {
2902
7
            const TableStreamIdentityPB& stream = table_streams.Get(i);
2903
7
            if (stream.base_db_id() != db_id || stream.base_table_id() != table_id ||
2904
7
                stream.stream_db_id() <= 0 || stream.stream_id() <= 0) {
2905
0
                LOG_WARNING("invalid table stream binding in recycle partition")
2906
0
                        .tag("instance_id", instance_id_)
2907
0
                        .tag("partition_id", partition_id)
2908
0
                        .tag("stream_id", stream.stream_id());
2909
0
                return -1;
2910
0
            }
2911
7
            txn->remove(table_stream_offset_key({instance_id_, stream.base_db_id(),
2912
7
                                                 stream.base_table_id(), stream.stream_db_id(),
2913
7
                                                 stream.stream_id(), partition_id}));
2914
7
            versioned_remove_all(
2915
7
                    txn.get(), versioned::table_stream_offset_key(
2916
7
                                       {instance_id_, stream.base_db_id(), stream.base_table_id(),
2917
7
                                        stream.stream_db_id(), stream.stream_id(), partition_id}));
2918
7
        }
2919
5
        err = txn->commit();
2920
5
        if (err != TxnErrorCode::TXN_OK) {
2921
0
            LOG_WARNING("failed to commit partition stream offset cleanup")
2922
0
                    .tag("instance_id", instance_id_)
2923
0
                    .tag("partition_id", partition_id)
2924
0
                    .tag("err", err);
2925
0
            return -1;
2926
0
        }
2927
5
        metrics_context.kv_recycled_num += end_index - begin_index;
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
        metrics_context.kv_scanned_num.set(num_scanned);
2953
25
        metrics_context.kv_expired_num.set(num_expired);
2954
25
        metrics_context.kv_recycled_num.set(num_recycled);
2955
25
        unregister_recycle_task(task_name);
2956
25
        int64_t cost =
2957
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2958
25
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2959
25
                .tag("instance_id", instance_id_)
2960
25
                .tag("num_scanned", num_scanned)
2961
25
                .tag("num_expired", num_expired)
2962
25
                .tag("num_recycled", num_recycled);
2963
25
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2951
4
    DORIS_CLOUD_DEFER {
2952
4
        metrics_context.kv_scanned_num.set(num_scanned);
2953
4
        metrics_context.kv_expired_num.set(num_expired);
2954
4
        metrics_context.kv_recycled_num.set(num_recycled);
2955
4
        unregister_recycle_task(task_name);
2956
4
        int64_t cost =
2957
4
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2958
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2959
4
                .tag("instance_id", instance_id_)
2960
4
                .tag("num_scanned", num_scanned)
2961
4
                .tag("num_expired", num_expired)
2962
4
                .tag("num_recycled", num_recycled);
2963
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_0clEv
Line
Count
Source
2951
21
    DORIS_CLOUD_DEFER {
2952
21
        metrics_context.kv_scanned_num.set(num_scanned);
2953
21
        metrics_context.kv_expired_num.set(num_expired);
2954
21
        metrics_context.kv_recycled_num.set(num_recycled);
2955
21
        unregister_recycle_task(task_name);
2956
21
        int64_t cost =
2957
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
2958
        LOG_WARNING("recycle indexes finished, cost={}s", cost)
2959
21
                .tag("instance_id", instance_id_)
2960
21
                .tag("num_scanned", num_scanned)
2961
21
                .tag("num_expired", num_expired)
2962
21
                .tag("num_recycled", num_recycled);
2963
21
    };
2964
2965
25
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
2966
2967
    // Elements in `index_keys` has the same lifetime as `it` in `scan_and_recycle`
2968
25
    std::vector<std::string_view> index_keys;
2969
25
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2970
18
        ++num_scanned;
2971
18
        RecycleIndexPB index_pb;
2972
18
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2973
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2974
0
            return -1;
2975
0
        }
2976
18
        int64_t current_time = ::time(nullptr);
2977
18
        if (current_time <
2978
18
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2979
0
            return 0;
2980
0
        }
2981
18
        ++num_expired;
2982
        // decode index_id
2983
18
        auto k1 = k;
2984
18
        k1.remove_prefix(1);
2985
18
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2986
18
        decode_key(&k1, &out);
2987
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2988
18
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2989
18
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2990
18
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2991
18
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2992
        // Change state to RECYCLING
2993
18
        std::unique_ptr<Transaction> txn;
2994
18
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2995
18
        if (err != TxnErrorCode::TXN_OK) {
2996
0
            LOG_WARNING("failed to create txn").tag("err", err);
2997
0
            return -1;
2998
0
        }
2999
18
        std::string val;
3000
18
        err = txn->get(k, &val);
3001
18
        if (err ==
3002
18
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3003
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3004
0
            return 0;
3005
0
        }
3006
18
        if (err != TxnErrorCode::TXN_OK) {
3007
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3008
0
            return -1;
3009
0
        }
3010
18
        index_pb.Clear();
3011
18
        if (!index_pb.ParseFromString(val)) {
3012
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3013
0
            return -1;
3014
0
        }
3015
18
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3016
16
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3017
16
            txn->put(k, index_pb.SerializeAsString());
3018
16
            err = txn->commit();
3019
16
            if (err != TxnErrorCode::TXN_OK) {
3020
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3021
0
                return -1;
3022
0
            }
3023
16
        }
3024
18
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3025
8
            if (recycle_stream(index_id, index_pb, k) != 0) {
3026
0
                LOG_WARNING("failed to recycle table stream")
3027
0
                        .tag("instance_id", instance_id_)
3028
0
                        .tag("stream_id", index_id);
3029
0
                return -1;
3030
0
            }
3031
8
            ++num_recycled;
3032
8
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3033
8
            return 0;
3034
8
        }
3035
10
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3036
1
            LOG_WARNING("failed to recycle tablets under index")
3037
1
                    .tag("table_id", index_pb.table_id())
3038
1
                    .tag("instance_id", instance_id_)
3039
1
                    .tag("index_id", index_id);
3040
1
            return -1;
3041
1
        }
3042
3043
9
        if (index_pb.has_db_id()) {
3044
            // Recycle the versioned keys
3045
3
            std::unique_ptr<Transaction> txn;
3046
3
            err = txn_kv_->create_txn(&txn);
3047
3
            if (err != TxnErrorCode::TXN_OK) {
3048
0
                LOG_WARNING("failed to create txn").tag("err", err);
3049
0
                return -1;
3050
0
            }
3051
3
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3052
3
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3053
3
            std::string index_inverted_key = versioned::index_inverted_key(
3054
3
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3055
3
            versioned_remove_all(txn.get(), meta_key);
3056
3
            txn->remove(index_key);
3057
3
            txn->remove(index_inverted_key);
3058
3
            err = txn->commit();
3059
3
            if (err != TxnErrorCode::TXN_OK) {
3060
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3061
0
                return -1;
3062
0
            }
3063
3
        }
3064
3065
9
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3066
9
        index_keys.push_back(k);
3067
9
        return 0;
3068
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2969
5
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2970
5
        ++num_scanned;
2971
5
        RecycleIndexPB index_pb;
2972
5
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2973
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2974
0
            return -1;
2975
0
        }
2976
5
        int64_t current_time = ::time(nullptr);
2977
5
        if (current_time <
2978
5
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2979
0
            return 0;
2980
0
        }
2981
5
        ++num_expired;
2982
        // decode index_id
2983
5
        auto k1 = k;
2984
5
        k1.remove_prefix(1);
2985
5
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2986
5
        decode_key(&k1, &out);
2987
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2988
5
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2989
5
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2990
5
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2991
5
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2992
        // Change state to RECYCLING
2993
5
        std::unique_ptr<Transaction> txn;
2994
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2995
5
        if (err != TxnErrorCode::TXN_OK) {
2996
0
            LOG_WARNING("failed to create txn").tag("err", err);
2997
0
            return -1;
2998
0
        }
2999
5
        std::string val;
3000
5
        err = txn->get(k, &val);
3001
5
        if (err ==
3002
5
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3003
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3004
0
            return 0;
3005
0
        }
3006
5
        if (err != TxnErrorCode::TXN_OK) {
3007
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3008
0
            return -1;
3009
0
        }
3010
5
        index_pb.Clear();
3011
5
        if (!index_pb.ParseFromString(val)) {
3012
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3013
0
            return -1;
3014
0
        }
3015
5
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3016
4
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3017
4
            txn->put(k, index_pb.SerializeAsString());
3018
4
            err = txn->commit();
3019
4
            if (err != TxnErrorCode::TXN_OK) {
3020
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3021
0
                return -1;
3022
0
            }
3023
4
        }
3024
5
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3025
3
            if (recycle_stream(index_id, index_pb, k) != 0) {
3026
0
                LOG_WARNING("failed to recycle table stream")
3027
0
                        .tag("instance_id", instance_id_)
3028
0
                        .tag("stream_id", index_id);
3029
0
                return -1;
3030
0
            }
3031
3
            ++num_recycled;
3032
3
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3033
3
            return 0;
3034
3
        }
3035
2
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3036
1
            LOG_WARNING("failed to recycle tablets under index")
3037
1
                    .tag("table_id", index_pb.table_id())
3038
1
                    .tag("instance_id", instance_id_)
3039
1
                    .tag("index_id", index_id);
3040
1
            return -1;
3041
1
        }
3042
3043
1
        if (index_pb.has_db_id()) {
3044
            // Recycle the versioned keys
3045
1
            std::unique_ptr<Transaction> txn;
3046
1
            err = txn_kv_->create_txn(&txn);
3047
1
            if (err != TxnErrorCode::TXN_OK) {
3048
0
                LOG_WARNING("failed to create txn").tag("err", err);
3049
0
                return -1;
3050
0
            }
3051
1
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3052
1
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3053
1
            std::string index_inverted_key = versioned::index_inverted_key(
3054
1
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3055
1
            versioned_remove_all(txn.get(), meta_key);
3056
1
            txn->remove(index_key);
3057
1
            txn->remove(index_inverted_key);
3058
1
            err = txn->commit();
3059
1
            if (err != TxnErrorCode::TXN_OK) {
3060
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3061
0
                return -1;
3062
0
            }
3063
1
        }
3064
3065
1
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3066
1
        index_keys.push_back(k);
3067
1
        return 0;
3068
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
2969
13
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
2970
13
        ++num_scanned;
2971
13
        RecycleIndexPB index_pb;
2972
13
        if (!index_pb.ParseFromArray(v.data(), v.size())) {
2973
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
2974
0
            return -1;
2975
0
        }
2976
13
        int64_t current_time = ::time(nullptr);
2977
13
        if (current_time <
2978
13
            calculate_index_expired_time(instance_id_, index_pb, &earlest_ts)) { // not expired
2979
0
            return 0;
2980
0
        }
2981
13
        ++num_expired;
2982
        // decode index_id
2983
13
        auto k1 = k;
2984
13
        k1.remove_prefix(1);
2985
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2986
13
        decode_key(&k1, &out);
2987
        // 0x01 "recycle" ${instance_id} "index" ${index_id} -> RecycleIndexPB
2988
13
        auto index_id = std::get<int64_t>(std::get<0>(out[3]));
2989
13
        LOG(INFO) << "begin to recycle index, instance_id=" << instance_id_
2990
13
                  << " table_id=" << index_pb.table_id() << " index_id=" << index_id
2991
13
                  << " state=" << RecycleIndexPB::State_Name(index_pb.state());
2992
        // Change state to RECYCLING
2993
13
        std::unique_ptr<Transaction> txn;
2994
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2995
13
        if (err != TxnErrorCode::TXN_OK) {
2996
0
            LOG_WARNING("failed to create txn").tag("err", err);
2997
0
            return -1;
2998
0
        }
2999
13
        std::string val;
3000
13
        err = txn->get(k, &val);
3001
13
        if (err ==
3002
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3003
0
            LOG_INFO("index {} has been recycled or committed", index_id);
3004
0
            return 0;
3005
0
        }
3006
13
        if (err != TxnErrorCode::TXN_OK) {
3007
0
            LOG_WARNING("failed to get kv").tag("key", hex(k)).tag("err", err);
3008
0
            return -1;
3009
0
        }
3010
13
        index_pb.Clear();
3011
13
        if (!index_pb.ParseFromString(val)) {
3012
0
            LOG_WARNING("malformed recycle index value").tag("key", hex(k));
3013
0
            return -1;
3014
0
        }
3015
13
        if (index_pb.state() != RecycleIndexPB::RECYCLING) {
3016
12
            index_pb.set_state(RecycleIndexPB::RECYCLING);
3017
12
            txn->put(k, index_pb.SerializeAsString());
3018
12
            err = txn->commit();
3019
12
            if (err != TxnErrorCode::TXN_OK) {
3020
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3021
0
                return -1;
3022
0
            }
3023
12
        }
3024
13
        if (index_pb.object_type() == IndexObjectTypePB::TABLE_STREAM) {
3025
5
            if (recycle_stream(index_id, index_pb, k) != 0) {
3026
0
                LOG_WARNING("failed to recycle table stream")
3027
0
                        .tag("instance_id", instance_id_)
3028
0
                        .tag("stream_id", index_id);
3029
0
                return -1;
3030
0
            }
3031
5
            ++num_recycled;
3032
5
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3033
5
            return 0;
3034
5
        }
3035
8
        if (recycle_tablets(index_pb.table_id(), index_id, metrics_context) != 0) {
3036
0
            LOG_WARNING("failed to recycle tablets under index")
3037
0
                    .tag("table_id", index_pb.table_id())
3038
0
                    .tag("instance_id", instance_id_)
3039
0
                    .tag("index_id", index_id);
3040
0
            return -1;
3041
0
        }
3042
3043
8
        if (index_pb.has_db_id()) {
3044
            // Recycle the versioned keys
3045
2
            std::unique_ptr<Transaction> txn;
3046
2
            err = txn_kv_->create_txn(&txn);
3047
2
            if (err != TxnErrorCode::TXN_OK) {
3048
0
                LOG_WARNING("failed to create txn").tag("err", err);
3049
0
                return -1;
3050
0
            }
3051
2
            std::string meta_key = versioned::meta_index_key({instance_id_, index_id});
3052
2
            std::string index_key = versioned::index_index_key({instance_id_, index_id});
3053
2
            std::string index_inverted_key = versioned::index_inverted_key(
3054
2
                    {instance_id_, index_pb.db_id(), index_pb.table_id(), index_id});
3055
2
            versioned_remove_all(txn.get(), meta_key);
3056
2
            txn->remove(index_key);
3057
2
            txn->remove(index_inverted_key);
3058
2
            err = txn->commit();
3059
2
            if (err != TxnErrorCode::TXN_OK) {
3060
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3061
0
                return -1;
3062
0
            }
3063
2
        }
3064
3065
8
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3066
8
        index_keys.push_back(k);
3067
8
        return 0;
3068
8
    };
3069
3070
25
    auto loop_done = [&index_keys, this, &metrics_context, &num_scanned, &num_expired,
3071
25
                      &num_recycled]() -> int {
3072
13
        DORIS_CLOUD_DEFER {
3073
13
            metrics_context.kv_scanned_num.set(num_scanned);
3074
13
            metrics_context.kv_expired_num.set(num_expired);
3075
13
            metrics_context.kv_recycled_num.set(num_recycled);
3076
13
            metrics_context.update_metrics();
3077
13
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3072
4
        DORIS_CLOUD_DEFER {
3073
4
            metrics_context.kv_scanned_num.set(num_scanned);
3074
4
            metrics_context.kv_expired_num.set(num_expired);
3075
4
            metrics_context.kv_recycled_num.set(num_recycled);
3076
4
            metrics_context.update_metrics();
3077
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3072
9
        DORIS_CLOUD_DEFER {
3073
9
            metrics_context.kv_scanned_num.set(num_scanned);
3074
9
            metrics_context.kv_expired_num.set(num_expired);
3075
9
            metrics_context.kv_recycled_num.set(num_recycled);
3076
9
            metrics_context.update_metrics();
3077
9
        };
3078
13
        if (index_keys.empty()) return 0;
3079
5
        DORIS_CLOUD_DEFER {
3080
5
            index_keys.clear();
3081
5
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
3079
1
        DORIS_CLOUD_DEFER {
3080
1
            index_keys.clear();
3081
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
3079
4
        DORIS_CLOUD_DEFER {
3080
4
            index_keys.clear();
3081
4
        };
3082
5
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3083
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3084
0
            return -1;
3085
0
        }
3086
5
        num_recycled += index_keys.size();
3087
5
        return 0;
3088
5
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3071
4
                      &num_recycled]() -> int {
3072
4
        DORIS_CLOUD_DEFER {
3073
4
            metrics_context.kv_scanned_num.set(num_scanned);
3074
4
            metrics_context.kv_expired_num.set(num_expired);
3075
4
            metrics_context.kv_recycled_num.set(num_recycled);
3076
4
            metrics_context.update_metrics();
3077
4
        };
3078
4
        if (index_keys.empty()) return 0;
3079
1
        DORIS_CLOUD_DEFER {
3080
1
            index_keys.clear();
3081
1
        };
3082
1
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3083
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3084
0
            return -1;
3085
0
        }
3086
1
        num_recycled += index_keys.size();
3087
1
        return 0;
3088
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_indexesEvENK3$_1clEv
Line
Count
Source
3071
9
                      &num_recycled]() -> int {
3072
9
        DORIS_CLOUD_DEFER {
3073
9
            metrics_context.kv_scanned_num.set(num_scanned);
3074
9
            metrics_context.kv_expired_num.set(num_expired);
3075
9
            metrics_context.kv_recycled_num.set(num_recycled);
3076
9
            metrics_context.update_metrics();
3077
9
        };
3078
9
        if (index_keys.empty()) return 0;
3079
4
        DORIS_CLOUD_DEFER {
3080
4
            index_keys.clear();
3081
4
        };
3082
4
        if (0 != txn_remove(txn_kv_.get(), index_keys)) {
3083
0
            LOG(WARNING) << "failed to delete recycle index kv, instance_id=" << instance_id_;
3084
0
            return -1;
3085
0
        }
3086
4
        num_recycled += index_keys.size();
3087
4
        return 0;
3088
4
    };
3089
3090
    // recycle_func and loop_done for scan and recycle
3091
25
    return scan_and_recycle(index_key0, index_key1, std::move(recycle_func), std::move(loop_done));
3092
25
}
3093
3094
bool check_lazy_txn_finished(std::shared_ptr<TxnKv> txn_kv, const std::string instance_id,
3095
8.25k
                             int64_t tablet_id) {
3096
8.25k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("check_lazy_txn_finished::bypass_check", true);
3097
3098
8.25k
    std::unique_ptr<Transaction> txn;
3099
8.25k
    TxnErrorCode err = txn_kv->create_txn(&txn);
3100
8.25k
    if (err != TxnErrorCode::TXN_OK) {
3101
0
        LOG(WARNING) << "failed to create txn, instance_id=" << instance_id
3102
0
                     << " tablet_id=" << tablet_id << " err=" << err;
3103
0
        return false;
3104
0
    }
3105
3106
8.25k
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id, tablet_id});
3107
8.25k
    std::string tablet_idx_val;
3108
8.25k
    err = txn->get(tablet_idx_key, &tablet_idx_val);
3109
8.25k
    if (TxnErrorCode::TXN_OK != err) {
3110
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id
3111
0
                     << " tablet_id=" << tablet_id << " err=" << err
3112
0
                     << " key=" << hex(tablet_idx_key);
3113
0
        return false;
3114
0
    }
3115
3116
8.25k
    TabletIndexPB tablet_idx_pb;
3117
8.25k
    if (!tablet_idx_pb.ParseFromString(tablet_idx_val)) {
3118
0
        LOG(WARNING) << "failed to parse tablet_idx_pb, instance_id=" << instance_id
3119
0
                     << " tablet_id=" << tablet_id;
3120
0
        return false;
3121
0
    }
3122
3123
8.25k
    if (!tablet_idx_pb.has_db_id()) {
3124
        // In the previous version, the db_id was not set in the index_pb.
3125
        // If updating to the version which enable txn lazy commit, the db_id will be set.
3126
0
        LOG(INFO) << "txn index has no db_id, tablet_id=" << tablet_id
3127
0
                  << " instance_id=" << instance_id
3128
0
                  << " tablet_idx_pb=" << tablet_idx_pb.ShortDebugString();
3129
0
        return true;
3130
0
    }
3131
3132
8.25k
    std::string ver_val;
3133
8.25k
    std::string ver_key =
3134
8.25k
            partition_version_key({instance_id, tablet_idx_pb.db_id(), tablet_idx_pb.table_id(),
3135
8.25k
                                   tablet_idx_pb.partition_id()});
3136
8.25k
    err = txn->get(ver_key, &ver_val);
3137
3138
8.25k
    if (TxnErrorCode::TXN_KEY_NOT_FOUND == err) {
3139
214
        LOG(INFO) << ""
3140
214
                     "partition version not found, instance_id="
3141
214
                  << instance_id << " db_id=" << tablet_idx_pb.db_id()
3142
214
                  << " table_id=" << tablet_idx_pb.table_id()
3143
214
                  << " partition_id=" << tablet_idx_pb.partition_id() << " tablet_id=" << tablet_id
3144
214
                  << " key=" << hex(ver_key);
3145
214
        return true;
3146
214
    }
3147
3148
8.03k
    if (TxnErrorCode::TXN_OK != err) {
3149
0
        LOG(WARNING) << "failed to get partition version, instance_id=" << instance_id
3150
0
                     << " db_id=" << tablet_idx_pb.db_id()
3151
0
                     << " table_id=" << tablet_idx_pb.table_id()
3152
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3153
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key) << " err=" << err;
3154
0
        return false;
3155
0
    }
3156
3157
8.03k
    VersionPB version_pb;
3158
8.03k
    if (!version_pb.ParseFromString(ver_val)) {
3159
0
        LOG(WARNING) << "failed to parse version_pb, instance_id=" << instance_id
3160
0
                     << " db_id=" << tablet_idx_pb.db_id()
3161
0
                     << " table_id=" << tablet_idx_pb.table_id()
3162
0
                     << " partition_id=" << tablet_idx_pb.partition_id()
3163
0
                     << " tablet_id=" << tablet_id << " key=" << hex(ver_key);
3164
0
        return false;
3165
0
    }
3166
3167
8.03k
    if (version_pb.pending_txn_ids_size() > 0) {
3168
4.00k
        TEST_SYNC_POINT_CALLBACK("check_lazy_txn_finished::txn_not_finished");
3169
4.00k
        DCHECK(version_pb.pending_txn_ids_size() == 1);
3170
4.00k
        LOG(WARNING) << "lazy txn not finished, instance_id=" << instance_id
3171
4.00k
                     << " db_id=" << tablet_idx_pb.db_id()
3172
4.00k
                     << " table_id=" << tablet_idx_pb.table_id()
3173
4.00k
                     << " partition_id=" << tablet_idx_pb.partition_id()
3174
4.00k
                     << " tablet_id=" << tablet_id << " txn_id=" << version_pb.pending_txn_ids(0)
3175
4.00k
                     << " key=" << hex(ver_key);
3176
4.00k
        return false;
3177
4.00k
    }
3178
4.03k
    return true;
3179
8.03k
}
3180
3181
20
int InstanceRecycler::recycle_partitions() {
3182
20
    const std::string task_name = "recycle_partitions";
3183
20
    int64_t num_scanned = 0;
3184
20
    int64_t num_expired = 0;
3185
20
    int64_t num_recycled = 0;
3186
20
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
3187
3188
20
    RecyclePartKeyInfo part_key_info0 {instance_id_, 0};
3189
20
    RecyclePartKeyInfo part_key_info1 {instance_id_, INT64_MAX};
3190
20
    std::string part_key0;
3191
20
    std::string part_key1;
3192
20
    recycle_partition_key(part_key_info0, &part_key0);
3193
20
    recycle_partition_key(part_key_info1, &part_key1);
3194
3195
20
    LOG_WARNING("begin to recycle partitions").tag("instance_id", instance_id_);
3196
3197
20
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
3198
20
    register_recycle_task(task_name, start_time);
3199
3200
20
    DORIS_CLOUD_DEFER {
3201
20
        metrics_context.kv_scanned_num.set(num_scanned);
3202
20
        metrics_context.kv_expired_num.set(num_expired);
3203
20
        metrics_context.kv_recycled_num.set(num_recycled);
3204
20
        unregister_recycle_task(task_name);
3205
20
        int64_t cost =
3206
20
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3207
20
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3208
20
                .tag("instance_id", instance_id_)
3209
20
                .tag("num_scanned", num_scanned)
3210
20
                .tag("num_expired", num_expired)
3211
20
                .tag("num_recycled", num_recycled);
3212
20
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3200
2
    DORIS_CLOUD_DEFER {
3201
2
        metrics_context.kv_scanned_num.set(num_scanned);
3202
2
        metrics_context.kv_expired_num.set(num_expired);
3203
2
        metrics_context.kv_recycled_num.set(num_recycled);
3204
2
        unregister_recycle_task(task_name);
3205
2
        int64_t cost =
3206
2
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3207
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3208
2
                .tag("instance_id", instance_id_)
3209
2
                .tag("num_scanned", num_scanned)
3210
2
                .tag("num_expired", num_expired)
3211
2
                .tag("num_recycled", num_recycled);
3212
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_0clEv
Line
Count
Source
3200
18
    DORIS_CLOUD_DEFER {
3201
18
        metrics_context.kv_scanned_num.set(num_scanned);
3202
18
        metrics_context.kv_expired_num.set(num_expired);
3203
18
        metrics_context.kv_recycled_num.set(num_recycled);
3204
18
        unregister_recycle_task(task_name);
3205
18
        int64_t cost =
3206
18
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
3207
        LOG_WARNING("recycle partitions finished, cost={}s", cost)
3208
18
                .tag("instance_id", instance_id_)
3209
18
                .tag("num_scanned", num_scanned)
3210
18
                .tag("num_expired", num_expired)
3211
18
                .tag("num_recycled", num_recycled);
3212
18
    };
3213
3214
20
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
3215
3216
    // Elements in `partition_keys` has the same lifetime as `it` in `scan_and_recycle`
3217
20
    std::vector<std::string_view> partition_keys;
3218
20
    std::vector<std::string> partition_version_keys;
3219
20
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3220
13
        ++num_scanned;
3221
13
        RecyclePartitionPB part_pb;
3222
13
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3223
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3224
0
            return -1;
3225
0
        }
3226
13
        int64_t current_time = ::time(nullptr);
3227
13
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3228
13
                                                            &earlest_ts)) { // not expired
3229
0
            return 0;
3230
0
        }
3231
13
        ++num_expired;
3232
        // decode partition_id
3233
13
        auto k1 = k;
3234
13
        k1.remove_prefix(1);
3235
13
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3236
13
        decode_key(&k1, &out);
3237
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3238
13
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3239
13
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3240
13
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3241
13
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3242
        // Change state to RECYCLING
3243
13
        std::unique_ptr<Transaction> txn;
3244
13
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3245
13
        if (err != TxnErrorCode::TXN_OK) {
3246
0
            LOG_WARNING("failed to create txn").tag("err", err);
3247
0
            return -1;
3248
0
        }
3249
13
        std::string val;
3250
13
        err = txn->get(k, &val);
3251
13
        if (err ==
3252
13
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3253
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3254
0
            return 0;
3255
0
        }
3256
13
        if (err != TxnErrorCode::TXN_OK) {
3257
0
            LOG_WARNING("failed to get kv");
3258
0
            return -1;
3259
0
        }
3260
13
        part_pb.Clear();
3261
13
        if (!part_pb.ParseFromString(val)) {
3262
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3263
0
            return -1;
3264
0
        }
3265
        // Partitions with PREPARED state MUST have no data
3266
13
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3267
11
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3268
11
            txn->put(k, part_pb.SerializeAsString());
3269
11
            err = txn->commit();
3270
11
            if (err != TxnErrorCode::TXN_OK) {
3271
0
                LOG_WARNING("failed to commit txn: {}", err);
3272
0
                return -1;
3273
0
            }
3274
11
        }
3275
3276
13
        int ret = 0;
3277
37
        for (int64_t index_id : part_pb.index_id()) {
3278
37
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3279
1
                LOG_WARNING("failed to recycle tablets under partition")
3280
1
                        .tag("table_id", part_pb.table_id())
3281
1
                        .tag("instance_id", instance_id_)
3282
1
                        .tag("index_id", index_id)
3283
1
                        .tag("partition_id", partition_id);
3284
1
                ret = -1;
3285
1
            }
3286
37
        }
3287
13
        if (ret == 0 && part_pb.has_db_id() &&
3288
13
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3289
12
                                                   partition_id, part_pb.table_streams()) != 0) {
3290
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3291
0
                    .tag("instance_id", instance_id_)
3292
0
                    .tag("table_id", part_pb.table_id())
3293
0
                    .tag("partition_id", partition_id);
3294
0
            ret = -1;
3295
0
        }
3296
13
        if (ret == 0 && part_pb.has_db_id()) {
3297
            // Recycle the versioned keys
3298
12
            std::unique_ptr<Transaction> txn;
3299
12
            err = txn_kv_->create_txn(&txn);
3300
12
            if (err != TxnErrorCode::TXN_OK) {
3301
0
                LOG_WARNING("failed to create txn").tag("err", err);
3302
0
                return -1;
3303
0
            }
3304
12
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3305
12
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3306
12
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3307
12
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3308
12
            std::string partition_version_key =
3309
12
                    versioned::partition_version_key({instance_id_, partition_id});
3310
12
            versioned_remove_all(txn.get(), meta_key);
3311
12
            txn->remove(index_key);
3312
12
            txn->remove(inverted_index_key);
3313
12
            versioned_remove_all(txn.get(), partition_version_key);
3314
12
            err = txn->commit();
3315
12
            if (err != TxnErrorCode::TXN_OK) {
3316
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3317
0
                return -1;
3318
0
            }
3319
12
        }
3320
3321
13
        if (ret == 0) {
3322
12
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3323
12
            partition_keys.push_back(k);
3324
12
            if (part_pb.db_id() > 0) {
3325
12
                partition_version_keys.push_back(partition_version_key(
3326
12
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3327
12
            }
3328
12
        }
3329
13
        return ret;
3330
13
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3219
2
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3220
2
        ++num_scanned;
3221
2
        RecyclePartitionPB part_pb;
3222
2
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3223
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3224
0
            return -1;
3225
0
        }
3226
2
        int64_t current_time = ::time(nullptr);
3227
2
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3228
2
                                                            &earlest_ts)) { // not expired
3229
0
            return 0;
3230
0
        }
3231
2
        ++num_expired;
3232
        // decode partition_id
3233
2
        auto k1 = k;
3234
2
        k1.remove_prefix(1);
3235
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3236
2
        decode_key(&k1, &out);
3237
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3238
2
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3239
2
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3240
2
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3241
2
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3242
        // Change state to RECYCLING
3243
2
        std::unique_ptr<Transaction> txn;
3244
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3245
2
        if (err != TxnErrorCode::TXN_OK) {
3246
0
            LOG_WARNING("failed to create txn").tag("err", err);
3247
0
            return -1;
3248
0
        }
3249
2
        std::string val;
3250
2
        err = txn->get(k, &val);
3251
2
        if (err ==
3252
2
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3253
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3254
0
            return 0;
3255
0
        }
3256
2
        if (err != TxnErrorCode::TXN_OK) {
3257
0
            LOG_WARNING("failed to get kv");
3258
0
            return -1;
3259
0
        }
3260
2
        part_pb.Clear();
3261
2
        if (!part_pb.ParseFromString(val)) {
3262
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3263
0
            return -1;
3264
0
        }
3265
        // Partitions with PREPARED state MUST have no data
3266
2
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3267
1
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3268
1
            txn->put(k, part_pb.SerializeAsString());
3269
1
            err = txn->commit();
3270
1
            if (err != TxnErrorCode::TXN_OK) {
3271
0
                LOG_WARNING("failed to commit txn: {}", err);
3272
0
                return -1;
3273
0
            }
3274
1
        }
3275
3276
2
        int ret = 0;
3277
2
        for (int64_t index_id : part_pb.index_id()) {
3278
2
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3279
1
                LOG_WARNING("failed to recycle tablets under partition")
3280
1
                        .tag("table_id", part_pb.table_id())
3281
1
                        .tag("instance_id", instance_id_)
3282
1
                        .tag("index_id", index_id)
3283
1
                        .tag("partition_id", partition_id);
3284
1
                ret = -1;
3285
1
            }
3286
2
        }
3287
2
        if (ret == 0 && part_pb.has_db_id() &&
3288
2
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3289
1
                                                   partition_id, part_pb.table_streams()) != 0) {
3290
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3291
0
                    .tag("instance_id", instance_id_)
3292
0
                    .tag("table_id", part_pb.table_id())
3293
0
                    .tag("partition_id", partition_id);
3294
0
            ret = -1;
3295
0
        }
3296
2
        if (ret == 0 && part_pb.has_db_id()) {
3297
            // Recycle the versioned keys
3298
1
            std::unique_ptr<Transaction> txn;
3299
1
            err = txn_kv_->create_txn(&txn);
3300
1
            if (err != TxnErrorCode::TXN_OK) {
3301
0
                LOG_WARNING("failed to create txn").tag("err", err);
3302
0
                return -1;
3303
0
            }
3304
1
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3305
1
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3306
1
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3307
1
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3308
1
            std::string partition_version_key =
3309
1
                    versioned::partition_version_key({instance_id_, partition_id});
3310
1
            versioned_remove_all(txn.get(), meta_key);
3311
1
            txn->remove(index_key);
3312
1
            txn->remove(inverted_index_key);
3313
1
            versioned_remove_all(txn.get(), partition_version_key);
3314
1
            err = txn->commit();
3315
1
            if (err != TxnErrorCode::TXN_OK) {
3316
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3317
0
                return -1;
3318
0
            }
3319
1
        }
3320
3321
2
        if (ret == 0) {
3322
1
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3323
1
            partition_keys.push_back(k);
3324
1
            if (part_pb.db_id() > 0) {
3325
1
                partition_version_keys.push_back(partition_version_key(
3326
1
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3327
1
            }
3328
1
        }
3329
2
        return ret;
3330
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3219
11
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3220
11
        ++num_scanned;
3221
11
        RecyclePartitionPB part_pb;
3222
11
        if (!part_pb.ParseFromArray(v.data(), v.size())) {
3223
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3224
0
            return -1;
3225
0
        }
3226
11
        int64_t current_time = ::time(nullptr);
3227
11
        if (current_time < calculate_partition_expired_time(instance_id_, part_pb,
3228
11
                                                            &earlest_ts)) { // not expired
3229
0
            return 0;
3230
0
        }
3231
11
        ++num_expired;
3232
        // decode partition_id
3233
11
        auto k1 = k;
3234
11
        k1.remove_prefix(1);
3235
11
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3236
11
        decode_key(&k1, &out);
3237
        // 0x01 "recycle" ${instance_id} "partition" ${partition_id} -> RecyclePartitionPB
3238
11
        auto partition_id = std::get<int64_t>(std::get<0>(out[3]));
3239
11
        LOG(INFO) << "begin to recycle partition, instance_id=" << instance_id_
3240
11
                  << " table_id=" << part_pb.table_id() << " partition_id=" << partition_id
3241
11
                  << " state=" << RecyclePartitionPB::State_Name(part_pb.state());
3242
        // Change state to RECYCLING
3243
11
        std::unique_ptr<Transaction> txn;
3244
11
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3245
11
        if (err != TxnErrorCode::TXN_OK) {
3246
0
            LOG_WARNING("failed to create txn").tag("err", err);
3247
0
            return -1;
3248
0
        }
3249
11
        std::string val;
3250
11
        err = txn->get(k, &val);
3251
11
        if (err ==
3252
11
            TxnErrorCode::TXN_KEY_NOT_FOUND) { // UNKNOWN, maybe recycled or committed, skip it
3253
0
            LOG_INFO("partition {} has been recycled or committed", partition_id);
3254
0
            return 0;
3255
0
        }
3256
11
        if (err != TxnErrorCode::TXN_OK) {
3257
0
            LOG_WARNING("failed to get kv");
3258
0
            return -1;
3259
0
        }
3260
11
        part_pb.Clear();
3261
11
        if (!part_pb.ParseFromString(val)) {
3262
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
3263
0
            return -1;
3264
0
        }
3265
        // Partitions with PREPARED state MUST have no data
3266
11
        if (part_pb.state() != RecyclePartitionPB::RECYCLING) {
3267
10
            part_pb.set_state(RecyclePartitionPB::RECYCLING);
3268
10
            txn->put(k, part_pb.SerializeAsString());
3269
10
            err = txn->commit();
3270
10
            if (err != TxnErrorCode::TXN_OK) {
3271
0
                LOG_WARNING("failed to commit txn: {}", err);
3272
0
                return -1;
3273
0
            }
3274
10
        }
3275
3276
11
        int ret = 0;
3277
35
        for (int64_t index_id : part_pb.index_id()) {
3278
35
            if (recycle_tablets(part_pb.table_id(), index_id, metrics_context, partition_id) != 0) {
3279
0
                LOG_WARNING("failed to recycle tablets under partition")
3280
0
                        .tag("table_id", part_pb.table_id())
3281
0
                        .tag("instance_id", instance_id_)
3282
0
                        .tag("index_id", index_id)
3283
0
                        .tag("partition_id", partition_id);
3284
0
                ret = -1;
3285
0
            }
3286
35
        }
3287
11
        if (ret == 0 && part_pb.has_db_id() &&
3288
11
            recycle_partition_table_stream_offsets(part_pb.db_id(), part_pb.table_id(),
3289
11
                                                   partition_id, part_pb.table_streams()) != 0) {
3290
0
            LOG_WARNING("failed to recycle table stream offsets under partition")
3291
0
                    .tag("instance_id", instance_id_)
3292
0
                    .tag("table_id", part_pb.table_id())
3293
0
                    .tag("partition_id", partition_id);
3294
0
            ret = -1;
3295
0
        }
3296
11
        if (ret == 0 && part_pb.has_db_id()) {
3297
            // Recycle the versioned keys
3298
11
            std::unique_ptr<Transaction> txn;
3299
11
            err = txn_kv_->create_txn(&txn);
3300
11
            if (err != TxnErrorCode::TXN_OK) {
3301
0
                LOG_WARNING("failed to create txn").tag("err", err);
3302
0
                return -1;
3303
0
            }
3304
11
            std::string meta_key = versioned::meta_partition_key({instance_id_, partition_id});
3305
11
            std::string index_key = versioned::partition_index_key({instance_id_, partition_id});
3306
11
            std::string inverted_index_key = versioned::partition_inverted_index_key(
3307
11
                    {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id});
3308
11
            std::string partition_version_key =
3309
11
                    versioned::partition_version_key({instance_id_, partition_id});
3310
11
            versioned_remove_all(txn.get(), meta_key);
3311
11
            txn->remove(index_key);
3312
11
            txn->remove(inverted_index_key);
3313
11
            versioned_remove_all(txn.get(), partition_version_key);
3314
11
            err = txn->commit();
3315
11
            if (err != TxnErrorCode::TXN_OK) {
3316
0
                LOG_WARNING("failed to commit txn").tag("err", err);
3317
0
                return -1;
3318
0
            }
3319
11
        }
3320
3321
11
        if (ret == 0) {
3322
11
            check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
3323
11
            partition_keys.push_back(k);
3324
11
            if (part_pb.db_id() > 0) {
3325
11
                partition_version_keys.push_back(partition_version_key(
3326
11
                        {instance_id_, part_pb.db_id(), part_pb.table_id(), partition_id}));
3327
11
            }
3328
11
        }
3329
11
        return ret;
3330
11
    };
3331
3332
20
    auto loop_done = [&partition_keys, &partition_version_keys, this, &metrics_context,
3333
20
                      &num_scanned, &num_expired, &num_recycled]() -> int {
3334
9
        DORIS_CLOUD_DEFER {
3335
9
            metrics_context.kv_scanned_num.set(num_scanned);
3336
9
            metrics_context.kv_expired_num.set(num_expired);
3337
9
            metrics_context.kv_recycled_num.set(num_recycled);
3338
9
            metrics_context.update_metrics();
3339
9
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3334
2
        DORIS_CLOUD_DEFER {
3335
2
            metrics_context.kv_scanned_num.set(num_scanned);
3336
2
            metrics_context.kv_expired_num.set(num_expired);
3337
2
            metrics_context.kv_recycled_num.set(num_recycled);
3338
2
            metrics_context.update_metrics();
3339
2
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3334
7
        DORIS_CLOUD_DEFER {
3335
7
            metrics_context.kv_scanned_num.set(num_scanned);
3336
7
            metrics_context.kv_expired_num.set(num_expired);
3337
7
            metrics_context.kv_recycled_num.set(num_recycled);
3338
7
            metrics_context.update_metrics();
3339
7
        };
3340
9
        if (partition_keys.empty()) return 0;
3341
8
        DORIS_CLOUD_DEFER {
3342
8
            partition_keys.clear();
3343
8
            partition_version_keys.clear();
3344
8
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
3341
1
        DORIS_CLOUD_DEFER {
3342
1
            partition_keys.clear();
3343
1
            partition_version_keys.clear();
3344
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
3341
7
        DORIS_CLOUD_DEFER {
3342
7
            partition_keys.clear();
3343
7
            partition_version_keys.clear();
3344
7
        };
3345
8
        std::unique_ptr<Transaction> txn;
3346
8
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3347
8
        if (err != TxnErrorCode::TXN_OK) {
3348
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3349
0
            return -1;
3350
0
        }
3351
12
        for (auto& k : partition_keys) {
3352
12
            txn->remove(k);
3353
12
        }
3354
12
        for (auto& k : partition_version_keys) {
3355
12
            txn->remove(k);
3356
12
        }
3357
8
        err = txn->commit();
3358
8
        if (err != TxnErrorCode::TXN_OK) {
3359
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3360
0
                         << " err=" << err;
3361
0
            return -1;
3362
0
        }
3363
8
        num_recycled += partition_keys.size();
3364
8
        return 0;
3365
8
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3333
2
                      &num_scanned, &num_expired, &num_recycled]() -> int {
3334
2
        DORIS_CLOUD_DEFER {
3335
2
            metrics_context.kv_scanned_num.set(num_scanned);
3336
2
            metrics_context.kv_expired_num.set(num_expired);
3337
2
            metrics_context.kv_recycled_num.set(num_recycled);
3338
2
            metrics_context.update_metrics();
3339
2
        };
3340
2
        if (partition_keys.empty()) return 0;
3341
1
        DORIS_CLOUD_DEFER {
3342
1
            partition_keys.clear();
3343
1
            partition_version_keys.clear();
3344
1
        };
3345
1
        std::unique_ptr<Transaction> txn;
3346
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3347
1
        if (err != TxnErrorCode::TXN_OK) {
3348
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3349
0
            return -1;
3350
0
        }
3351
1
        for (auto& k : partition_keys) {
3352
1
            txn->remove(k);
3353
1
        }
3354
1
        for (auto& k : partition_version_keys) {
3355
1
            txn->remove(k);
3356
1
        }
3357
1
        err = txn->commit();
3358
1
        if (err != TxnErrorCode::TXN_OK) {
3359
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3360
0
                         << " err=" << err;
3361
0
            return -1;
3362
0
        }
3363
1
        num_recycled += partition_keys.size();
3364
1
        return 0;
3365
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18recycle_partitionsEvENK3$_1clEv
Line
Count
Source
3333
7
                      &num_scanned, &num_expired, &num_recycled]() -> int {
3334
7
        DORIS_CLOUD_DEFER {
3335
7
            metrics_context.kv_scanned_num.set(num_scanned);
3336
7
            metrics_context.kv_expired_num.set(num_expired);
3337
7
            metrics_context.kv_recycled_num.set(num_recycled);
3338
7
            metrics_context.update_metrics();
3339
7
        };
3340
7
        if (partition_keys.empty()) return 0;
3341
7
        DORIS_CLOUD_DEFER {
3342
7
            partition_keys.clear();
3343
7
            partition_version_keys.clear();
3344
7
        };
3345
7
        std::unique_ptr<Transaction> txn;
3346
7
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3347
7
        if (err != TxnErrorCode::TXN_OK) {
3348
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
3349
0
            return -1;
3350
0
        }
3351
11
        for (auto& k : partition_keys) {
3352
11
            txn->remove(k);
3353
11
        }
3354
11
        for (auto& k : partition_version_keys) {
3355
11
            txn->remove(k);
3356
11
        }
3357
7
        err = txn->commit();
3358
7
        if (err != TxnErrorCode::TXN_OK) {
3359
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_
3360
0
                         << " err=" << err;
3361
0
            return -1;
3362
0
        }
3363
7
        num_recycled += partition_keys.size();
3364
7
        return 0;
3365
7
    };
3366
3367
    // recycle_func and loop_done for scan and recycle
3368
20
    return scan_and_recycle(part_key0, part_key1, std::move(recycle_func), std::move(loop_done));
3369
20
}
3370
3371
14
int InstanceRecycler::recycle_versions() {
3372
14
    if (should_recycle_versioned_keys()) {
3373
2
        return recycle_orphan_partitions();
3374
2
    }
3375
3376
12
    int64_t num_scanned = 0;
3377
12
    int64_t num_expired = 0;
3378
12
    int64_t num_recycled = 0;
3379
12
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_versions");
3380
3381
12
    LOG_WARNING("begin to recycle table and partition versions").tag("instance_id", instance_id_);
3382
3383
12
    auto start_time = steady_clock::now();
3384
3385
12
    DORIS_CLOUD_DEFER {
3386
12
        metrics_context.kv_scanned_num.set(num_scanned);
3387
12
        metrics_context.kv_expired_num.set(num_expired);
3388
12
        metrics_context.kv_recycled_num.set(num_recycled);
3389
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3390
12
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3391
12
                .tag("instance_id", instance_id_)
3392
12
                .tag("num_scanned", num_scanned)
3393
12
                .tag("num_recycled", num_recycled);
3394
12
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_0clEv
Line
Count
Source
3385
12
    DORIS_CLOUD_DEFER {
3386
12
        metrics_context.kv_scanned_num.set(num_scanned);
3387
12
        metrics_context.kv_expired_num.set(num_expired);
3388
12
        metrics_context.kv_recycled_num.set(num_recycled);
3389
12
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3390
        LOG_WARNING("recycle table and partition versions finished, cost={}s", cost)
3391
12
                .tag("instance_id", instance_id_)
3392
12
                .tag("num_scanned", num_scanned)
3393
12
                .tag("num_recycled", num_recycled);
3394
12
    };
3395
3396
12
    auto version_key_begin = partition_version_key({instance_id_, 0, 0, 0});
3397
12
    auto version_key_end = partition_version_key({instance_id_, INT64_MAX, 0, 0});
3398
12
    int64_t last_scanned_table_id = 0;
3399
12
    bool is_recycled = false; // Is last scanned kv recycled
3400
12
    auto recycle_func = [&num_scanned, &num_expired, &num_recycled, &last_scanned_table_id,
3401
12
                         &is_recycled, this](std::string_view k, std::string_view) {
3402
2
        ++num_scanned;
3403
2
        auto k1 = k;
3404
2
        k1.remove_prefix(1);
3405
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3406
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3407
2
        decode_key(&k1, &out);
3408
2
        DCHECK_EQ(out.size(), 6) << k;
3409
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3410
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3411
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3412
0
            return 0;
3413
0
        }
3414
2
        last_scanned_table_id = table_id;
3415
2
        is_recycled = false;
3416
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3417
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3418
2
        std::unique_ptr<Transaction> txn;
3419
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3420
2
        if (err != TxnErrorCode::TXN_OK) {
3421
0
            return -1;
3422
0
        }
3423
2
        std::unique_ptr<RangeGetIterator> iter;
3424
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3425
2
        if (err != TxnErrorCode::TXN_OK) {
3426
0
            return -1;
3427
0
        }
3428
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3429
1
            return 0;
3430
1
        }
3431
1
        ++num_expired;
3432
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3433
        // 1. Remove all partition version kvs of this table
3434
1
        auto partition_version_key_begin =
3435
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3436
1
        auto partition_version_key_end =
3437
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3438
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3439
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3440
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3441
1
                     << " table_id=" << table_id;
3442
        // 2. Remove the table version kv of this table
3443
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3444
1
        txn->remove(tbl_version_key);
3445
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3446
        // 3. Remove mow delete bitmap update lock and tablet job lock
3447
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3448
1
        txn->remove(lock_key);
3449
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3450
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3451
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3452
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3453
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3454
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3455
1
                     << " table_id=" << table_id;
3456
1
        err = txn->commit();
3457
1
        if (err != TxnErrorCode::TXN_OK) {
3458
0
            return -1;
3459
0
        }
3460
1
        ++num_recycled;
3461
1
        is_recycled = true;
3462
1
        return 0;
3463
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3401
2
                         &is_recycled, this](std::string_view k, std::string_view) {
3402
2
        ++num_scanned;
3403
2
        auto k1 = k;
3404
2
        k1.remove_prefix(1);
3405
        // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
3406
2
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
3407
2
        decode_key(&k1, &out);
3408
2
        DCHECK_EQ(out.size(), 6) << k;
3409
2
        auto table_id = std::get<int64_t>(std::get<0>(out[4]));
3410
2
        if (table_id == last_scanned_table_id) { // Already handle kvs of this table
3411
0
            num_recycled += is_recycled;         // Version kv of this table has been recycled
3412
0
            return 0;
3413
0
        }
3414
2
        last_scanned_table_id = table_id;
3415
2
        is_recycled = false;
3416
2
        auto tablet_key_begin = stats_tablet_key({instance_id_, table_id, 0, 0, 0});
3417
2
        auto tablet_key_end = stats_tablet_key({instance_id_, table_id, INT64_MAX, 0, 0});
3418
2
        std::unique_ptr<Transaction> txn;
3419
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3420
2
        if (err != TxnErrorCode::TXN_OK) {
3421
0
            return -1;
3422
0
        }
3423
2
        std::unique_ptr<RangeGetIterator> iter;
3424
2
        err = txn->get(tablet_key_begin, tablet_key_end, &iter, false, 1);
3425
2
        if (err != TxnErrorCode::TXN_OK) {
3426
0
            return -1;
3427
0
        }
3428
2
        if (iter->has_next()) { // Table is useful, should not recycle table and partition versions
3429
1
            return 0;
3430
1
        }
3431
1
        ++num_expired;
3432
1
        auto db_id = std::get<int64_t>(std::get<0>(out[3]));
3433
        // 1. Remove all partition version kvs of this table
3434
1
        auto partition_version_key_begin =
3435
1
                partition_version_key({instance_id_, db_id, table_id, 0});
3436
1
        auto partition_version_key_end =
3437
1
                partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
3438
1
        txn->remove(partition_version_key_begin, partition_version_key_end);
3439
1
        LOG(WARNING) << "remove partition version kv, begin=" << hex(partition_version_key_begin)
3440
1
                     << " end=" << hex(partition_version_key_end) << " db_id=" << db_id
3441
1
                     << " table_id=" << table_id;
3442
        // 2. Remove the table version kv of this table
3443
1
        auto tbl_version_key = table_version_key({instance_id_, db_id, table_id});
3444
1
        txn->remove(tbl_version_key);
3445
1
        LOG(WARNING) << "remove table version kv " << hex(tbl_version_key);
3446
        // 3. Remove mow delete bitmap update lock and tablet job lock
3447
1
        std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3448
1
        txn->remove(lock_key);
3449
1
        LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3450
1
        std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3451
1
        std::string tablet_job_key_end = mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3452
1
        txn->remove(tablet_job_key_begin, tablet_job_key_end);
3453
1
        LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3454
1
                     << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3455
1
                     << " table_id=" << table_id;
3456
1
        err = txn->commit();
3457
1
        if (err != TxnErrorCode::TXN_OK) {
3458
0
            return -1;
3459
0
        }
3460
1
        ++num_recycled;
3461
1
        is_recycled = true;
3462
1
        return 0;
3463
1
    };
3464
3465
12
    auto loop_done = [&]() -> int {
3466
2
        DORIS_CLOUD_DEFER {
3467
2
            metrics_context.kv_scanned_num.set(num_scanned);
3468
2
            metrics_context.kv_expired_num.set(num_expired);
3469
2
            metrics_context.kv_recycled_num.set(num_recycled);
3470
2
            metrics_context.update_metrics();
3471
2
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3466
2
        DORIS_CLOUD_DEFER {
3467
2
            metrics_context.kv_scanned_num.set(num_scanned);
3468
2
            metrics_context.kv_expired_num.set(num_expired);
3469
2
            metrics_context.kv_recycled_num.set(num_recycled);
3470
2
            metrics_context.update_metrics();
3471
2
        };
3472
2
        return 0;
3473
2
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16recycle_versionsEvENK3$_1clEv
Line
Count
Source
3465
2
    auto loop_done = [&]() -> int {
3466
2
        DORIS_CLOUD_DEFER {
3467
2
            metrics_context.kv_scanned_num.set(num_scanned);
3468
2
            metrics_context.kv_expired_num.set(num_expired);
3469
2
            metrics_context.kv_recycled_num.set(num_recycled);
3470
2
            metrics_context.update_metrics();
3471
2
        };
3472
2
        return 0;
3473
2
    };
3474
3475
    // recycle_func and loop_done for scan and recycle
3476
12
    return scan_and_recycle(version_key_begin, version_key_end, std::move(recycle_func),
3477
12
                            std::move(loop_done));
3478
14
}
3479
3480
3
int InstanceRecycler::recycle_orphan_partitions() {
3481
3
    int64_t num_scanned = 0;
3482
3
    int64_t num_expired = 0;
3483
3
    int64_t num_recycled = 0;
3484
3
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_orphan_partitions");
3485
3486
3
    LOG_WARNING("begin to recycle orphan table and partition versions")
3487
3
            .tag("instance_id", instance_id_);
3488
3489
3
    auto start_time = steady_clock::now();
3490
3491
3
    DORIS_CLOUD_DEFER {
3492
3
        metrics_context.kv_scanned_num.set(num_scanned);
3493
3
        metrics_context.kv_expired_num.set(num_expired);
3494
3
        metrics_context.kv_recycled_num.set(num_recycled);
3495
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3496
3
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3497
3
                .tag("instance_id", instance_id_)
3498
3
                .tag("num_scanned", num_scanned)
3499
3
                .tag("num_recycled", num_recycled);
3500
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_0clEv
Line
Count
Source
3491
3
    DORIS_CLOUD_DEFER {
3492
3
        metrics_context.kv_scanned_num.set(num_scanned);
3493
3
        metrics_context.kv_expired_num.set(num_expired);
3494
3
        metrics_context.kv_recycled_num.set(num_recycled);
3495
3
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3496
        LOG_WARNING("recycle orphan table and partition versions finished, cost={}s", cost)
3497
3
                .tag("instance_id", instance_id_)
3498
3
                .tag("num_scanned", num_scanned)
3499
3
                .tag("num_recycled", num_recycled);
3500
3
    };
3501
3502
3
    bool is_empty_table = false;        // whether the table has no indexes
3503
3
    bool is_table_kvs_recycled = false; // whether the table related kvs have been recycled
3504
3
    int64_t current_table_id = 0;       // current scanning table id
3505
3
    auto recycle_func = [&num_scanned, &num_expired, &num_recycled, &is_empty_table,
3506
3
                         &current_table_id, &is_table_kvs_recycled,
3507
3
                         this](std::string_view k, std::string_view) {
3508
2
        ++num_scanned;
3509
3510
2
        std::string_view k1(k);
3511
2
        int64_t db_id, table_id, partition_id;
3512
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3513
2
                                                            &partition_id)) {
3514
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3515
0
            return -1;
3516
2
        } else if (table_id != current_table_id) {
3517
2
            current_table_id = table_id;
3518
2
            is_table_kvs_recycled = false;
3519
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3520
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3521
2
            if (err != TxnErrorCode::TXN_OK) {
3522
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3523
0
                             << " table_id=" << table_id << " err=" << err;
3524
0
                return -1;
3525
0
            }
3526
2
        }
3527
3528
2
        if (!is_empty_table) {
3529
            // table is not empty, skip recycle
3530
1
            return 0;
3531
1
        }
3532
1
        num_expired++;
3533
3534
1
        std::unique_ptr<Transaction> txn;
3535
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3536
1
        if (err != TxnErrorCode::TXN_OK) {
3537
0
            return -1;
3538
0
        }
3539
3540
        // 1. Remove all partition related kvs
3541
1
        std::string partition_meta_key =
3542
1
                versioned::meta_partition_key({instance_id_, partition_id});
3543
1
        std::string partition_index_key =
3544
1
                versioned::partition_index_key({instance_id_, partition_id});
3545
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3546
1
                {instance_id_, db_id, table_id, partition_id});
3547
1
        std::string partition_version_key =
3548
1
                versioned::partition_version_key({instance_id_, partition_id});
3549
1
        txn->remove(partition_index_key);
3550
1
        txn->remove(partition_inverted_key);
3551
1
        versioned_remove_all(txn.get(), partition_meta_key);
3552
1
        versioned_remove_all(txn.get(), partition_version_key);
3553
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3554
1
                     << " table_id=" << table_id << " db_id=" << db_id
3555
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3556
1
                     << " partition_version_key=" << hex(partition_version_key);
3557
3558
1
        if (!is_table_kvs_recycled) {
3559
1
            is_table_kvs_recycled = true;
3560
3561
            // 2. Remove the table version kv of this table
3562
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3563
1
            versioned_remove_all(txn.get(), table_version_key);
3564
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3565
            // 3. Remove mow delete bitmap update lock and tablet job lock
3566
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3567
1
            txn->remove(lock_key);
3568
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3569
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3570
1
            std::string tablet_job_key_end =
3571
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3572
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3573
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3574
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3575
1
                         << " table_id=" << table_id;
3576
1
        }
3577
3578
1
        err = txn->commit();
3579
1
        if (err != TxnErrorCode::TXN_OK) {
3580
0
            return -1;
3581
0
        }
3582
1
        ++num_recycled;
3583
1
        return 0;
3584
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
3507
2
                         this](std::string_view k, std::string_view) {
3508
2
        ++num_scanned;
3509
3510
2
        std::string_view k1(k);
3511
2
        int64_t db_id, table_id, partition_id;
3512
2
        if (!versioned::decode_partition_inverted_index_key(&k1, &db_id, &table_id,
3513
2
                                                            &partition_id)) {
3514
0
            LOG(WARNING) << "malformed partition inverted index key " << hex(k);
3515
0
            return -1;
3516
2
        } else if (table_id != current_table_id) {
3517
2
            current_table_id = table_id;
3518
2
            is_table_kvs_recycled = false;
3519
2
            MetaReader meta_reader(instance_id_, txn_kv_.get());
3520
2
            TxnErrorCode err = meta_reader.has_no_indexes(db_id, table_id, &is_empty_table);
3521
2
            if (err != TxnErrorCode::TXN_OK) {
3522
0
                LOG(WARNING) << "failed to check whether table has no indexes, db_id=" << db_id
3523
0
                             << " table_id=" << table_id << " err=" << err;
3524
0
                return -1;
3525
0
            }
3526
2
        }
3527
3528
2
        if (!is_empty_table) {
3529
            // table is not empty, skip recycle
3530
1
            return 0;
3531
1
        }
3532
1
        num_expired++;
3533
3534
1
        std::unique_ptr<Transaction> txn;
3535
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3536
1
        if (err != TxnErrorCode::TXN_OK) {
3537
0
            return -1;
3538
0
        }
3539
3540
        // 1. Remove all partition related kvs
3541
1
        std::string partition_meta_key =
3542
1
                versioned::meta_partition_key({instance_id_, partition_id});
3543
1
        std::string partition_index_key =
3544
1
                versioned::partition_index_key({instance_id_, partition_id});
3545
1
        std::string partition_inverted_key = versioned::partition_inverted_index_key(
3546
1
                {instance_id_, db_id, table_id, partition_id});
3547
1
        std::string partition_version_key =
3548
1
                versioned::partition_version_key({instance_id_, partition_id});
3549
1
        txn->remove(partition_index_key);
3550
1
        txn->remove(partition_inverted_key);
3551
1
        versioned_remove_all(txn.get(), partition_meta_key);
3552
1
        versioned_remove_all(txn.get(), partition_version_key);
3553
1
        LOG(WARNING) << "remove partition related kvs, partition_id=" << partition_id
3554
1
                     << " table_id=" << table_id << " db_id=" << db_id
3555
1
                     << " partition_meta_key=" << hex(partition_meta_key)
3556
1
                     << " partition_version_key=" << hex(partition_version_key);
3557
3558
1
        if (!is_table_kvs_recycled) {
3559
1
            is_table_kvs_recycled = true;
3560
3561
            // 2. Remove the table version kv of this table
3562
1
            std::string table_version_key = versioned::table_version_key({instance_id_, table_id});
3563
1
            versioned_remove_all(txn.get(), table_version_key);
3564
1
            LOG(WARNING) << "remove table version kv " << hex(table_version_key);
3565
            // 3. Remove mow delete bitmap update lock and tablet job lock
3566
1
            std::string lock_key = meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
3567
1
            txn->remove(lock_key);
3568
1
            LOG(WARNING) << "remove delete bitmap update lock kv " << hex(lock_key);
3569
1
            std::string tablet_job_key_begin = mow_tablet_job_key({instance_id_, table_id, 0});
3570
1
            std::string tablet_job_key_end =
3571
1
                    mow_tablet_job_key({instance_id_, table_id, INT64_MAX});
3572
1
            txn->remove(tablet_job_key_begin, tablet_job_key_end);
3573
1
            LOG(WARNING) << "remove mow tablet job kv, begin=" << hex(tablet_job_key_begin)
3574
1
                         << " end=" << hex(tablet_job_key_end) << " db_id=" << db_id
3575
1
                         << " table_id=" << table_id;
3576
1
        }
3577
3578
1
        err = txn->commit();
3579
1
        if (err != TxnErrorCode::TXN_OK) {
3580
0
            return -1;
3581
0
        }
3582
1
        ++num_recycled;
3583
1
        return 0;
3584
1
    };
3585
3586
3
    auto loop_done = [&]() -> int {
3587
2
        DORIS_CLOUD_DEFER {
3588
2
            metrics_context.kv_scanned_num.set(num_scanned);
3589
2
            metrics_context.kv_expired_num.set(num_expired);
3590
2
            metrics_context.kv_recycled_num.set(num_recycled);
3591
2
            metrics_context.update_metrics();
3592
2
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
3587
2
        DORIS_CLOUD_DEFER {
3588
2
            metrics_context.kv_scanned_num.set(num_scanned);
3589
2
            metrics_context.kv_expired_num.set(num_expired);
3590
2
            metrics_context.kv_recycled_num.set(num_recycled);
3591
2
            metrics_context.update_metrics();
3592
2
        };
3593
2
        return 0;
3594
2
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_orphan_partitionsEvENK3$_1clEv
Line
Count
Source
3586
2
    auto loop_done = [&]() -> int {
3587
2
        DORIS_CLOUD_DEFER {
3588
2
            metrics_context.kv_scanned_num.set(num_scanned);
3589
2
            metrics_context.kv_expired_num.set(num_expired);
3590
2
            metrics_context.kv_recycled_num.set(num_recycled);
3591
2
            metrics_context.update_metrics();
3592
2
        };
3593
2
        return 0;
3594
2
    };
3595
3596
    // recycle_func and loop_done for scan and recycle
3597
3
    return scan_and_recycle(
3598
3
            versioned::partition_inverted_index_key({instance_id_, 0, 0, 0}),
3599
3
            versioned::partition_inverted_index_key({instance_id_, INT64_MAX, 0, 0}),
3600
3
            std::move(recycle_func), std::move(loop_done));
3601
3
}
3602
3603
int InstanceRecycler::recycle_tablets(int64_t table_id, int64_t index_id,
3604
                                      RecyclerMetricsContext& metrics_context,
3605
56
                                      int64_t partition_id) {
3606
56
    bool is_multi_version =
3607
56
            instance_info_.has_multi_version_status() &&
3608
56
            instance_info_.multi_version_status() != MultiVersionStatus::MULTI_VERSION_DISABLED;
3609
56
    int64_t num_scanned = 0;
3610
56
    std::atomic_long num_recycled = 0;
3611
3612
56
    std::string tablet_key_begin, tablet_key_end;
3613
56
    std::string stats_key_begin, stats_key_end;
3614
56
    std::string job_key_begin, job_key_end;
3615
3616
56
    std::string tablet_belongs;
3617
56
    if (partition_id > 0) {
3618
        // recycle tablets in a partition belonging to the index
3619
37
        meta_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &tablet_key_begin);
3620
37
        meta_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &tablet_key_end);
3621
37
        stats_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &stats_key_begin);
3622
37
        stats_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &stats_key_end);
3623
37
        job_tablet_key({instance_id_, table_id, index_id, partition_id, 0}, &job_key_begin);
3624
37
        job_tablet_key({instance_id_, table_id, index_id, partition_id + 1, 0}, &job_key_end);
3625
37
        tablet_belongs = "partition";
3626
37
    } else {
3627
        // recycle tablets in the index
3628
19
        meta_tablet_key({instance_id_, table_id, index_id, 0, 0}, &tablet_key_begin);
3629
19
        meta_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &tablet_key_end);
3630
19
        stats_tablet_key({instance_id_, table_id, index_id, 0, 0}, &stats_key_begin);
3631
19
        stats_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &stats_key_end);
3632
19
        job_tablet_key({instance_id_, table_id, index_id, 0, 0}, &job_key_begin);
3633
19
        job_tablet_key({instance_id_, table_id, index_id + 1, 0, 0}, &job_key_end);
3634
19
        tablet_belongs = "index";
3635
19
    }
3636
3637
56
    LOG_INFO("begin to recycle tablets of the " + tablet_belongs)
3638
56
            .tag("table_id", table_id)
3639
56
            .tag("index_id", index_id)
3640
56
            .tag("partition_id", partition_id);
3641
3642
56
    auto start_time = steady_clock::now();
3643
3644
56
    DORIS_CLOUD_DEFER {
3645
56
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3646
56
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3647
56
                .tag("instance_id", instance_id_)
3648
56
                .tag("table_id", table_id)
3649
56
                .tag("index_id", index_id)
3650
56
                .tag("partition_id", partition_id)
3651
56
                .tag("num_scanned", num_scanned)
3652
56
                .tag("num_recycled", num_recycled);
3653
56
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3644
4
    DORIS_CLOUD_DEFER {
3645
4
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3646
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3647
4
                .tag("instance_id", instance_id_)
3648
4
                .tag("table_id", table_id)
3649
4
                .tag("index_id", index_id)
3650
4
                .tag("partition_id", partition_id)
3651
4
                .tag("num_scanned", num_scanned)
3652
4
                .tag("num_recycled", num_recycled);
3653
4
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_0clEv
Line
Count
Source
3644
52
    DORIS_CLOUD_DEFER {
3645
52
        auto cost = duration<float>(steady_clock::now() - start_time).count();
3646
        LOG_INFO("recycle tablets of " + tablet_belongs + " finished, cost={}s", cost)
3647
52
                .tag("instance_id", instance_id_)
3648
52
                .tag("table_id", table_id)
3649
52
                .tag("index_id", index_id)
3650
52
                .tag("partition_id", partition_id)
3651
52
                .tag("num_scanned", num_scanned)
3652
52
                .tag("num_recycled", num_recycled);
3653
52
    };
3654
3655
    // The tablet key and id which have been recycled.
3656
56
    struct TabletInfo {
3657
56
        std::string_view tablet_meta_key;
3658
56
        int64_t tablet_id;
3659
56
    };
3660
56
    SyncExecutor<TabletInfo> sync_executor(
3661
56
            _thread_pool_group.recycle_tablet_pool,
3662
56
            fmt::format("recycle tablets, tablet id {}, index id {}, partition id {}", table_id,
3663
56
                        index_id, partition_id),
3664
4.24k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3664
4.00k
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_1clERKZNS1_15recycle_tabletsEllS3_lE10TabletInfo
Line
Count
Source
3664
241
            [](const TabletInfo& k) { return k.tablet_meta_key.empty(); });
3665
3666
    // Elements in `tablets_info` has the same lifetime as `it` in `scan_and_recycle`
3667
56
    std::vector<std::string> init_rs_keys;
3668
56
    bool has_failure = false;
3669
8.25k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3670
8.25k
        ++num_scanned;
3671
8.25k
        doris::TabletMetaCloudPB tablet_meta_pb;
3672
8.25k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3673
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3674
0
            has_failure = true;
3675
0
            return -1;
3676
0
        }
3677
8.25k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3678
3679
8.25k
        if (config::enable_recycler_check_lazy_txn_finished &&
3680
8.25k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3681
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3682
4.00k
            has_failure = true;
3683
4.00k
            return -1;
3684
4.00k
        }
3685
3686
8.25k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3687
4.25k
        sync_executor.add(
3688
4.25k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3689
4.25k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3690
2
                        LOG_WARNING("failed to recycle tablet")
3691
2
                                .tag("instance_id", instance_id_)
3692
2
                                .tag("tablet_id", tid);
3693
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3694
2
                    }
3695
4.25k
                    ++num_recycled;
3696
4.25k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3697
4.25k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3698
4.25k
                });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3688
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3689
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3690
0
                        LOG_WARNING("failed to recycle tablet")
3691
0
                                .tag("instance_id", instance_id_)
3692
0
                                .tag("tablet_id", tid);
3693
0
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3694
0
                    }
3695
4.00k
                    ++num_recycled;
3696
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3697
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3698
4.00k
                });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_ENKUlvE_clEv
Line
Count
Source
3688
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3689
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3690
2
                        LOG_WARNING("failed to recycle tablet")
3691
2
                                .tag("instance_id", instance_id_)
3692
2
                                .tag("tablet_id", tid);
3693
2
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3694
2
                    }
3695
248
                    ++num_recycled;
3696
248
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3697
248
                    return {.tablet_meta_key = k, .tablet_id = tid};
3698
250
                });
3699
4.25k
        return 0;
3700
4.25k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3669
8.00k
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3670
8.00k
        ++num_scanned;
3671
8.00k
        doris::TabletMetaCloudPB tablet_meta_pb;
3672
8.00k
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3673
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3674
0
            has_failure = true;
3675
0
            return -1;
3676
0
        }
3677
8.00k
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3678
3679
8.00k
        if (config::enable_recycler_check_lazy_txn_finished &&
3680
8.00k
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3681
4.00k
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3682
4.00k
            has_failure = true;
3683
4.00k
            return -1;
3684
4.00k
        }
3685
3686
8.00k
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3687
4.00k
        sync_executor.add(
3688
4.00k
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3689
4.00k
                    if (recycle_tablet(tid, metrics_context) != 0) {
3690
4.00k
                        LOG_WARNING("failed to recycle tablet")
3691
4.00k
                                .tag("instance_id", instance_id_)
3692
4.00k
                                .tag("tablet_id", tid);
3693
4.00k
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3694
4.00k
                    }
3695
4.00k
                    ++num_recycled;
3696
4.00k
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3697
4.00k
                    return {.tablet_meta_key = k, .tablet_id = tid};
3698
4.00k
                });
3699
4.00k
        return 0;
3700
4.00k
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES8_
Line
Count
Source
3669
251
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
3670
251
        ++num_scanned;
3671
251
        doris::TabletMetaCloudPB tablet_meta_pb;
3672
251
        if (!tablet_meta_pb.ParseFromArray(v.data(), v.size())) {
3673
0
            LOG_WARNING("malformed tablet meta").tag("key", hex(k));
3674
0
            has_failure = true;
3675
0
            return -1;
3676
0
        }
3677
251
        int64_t tablet_id = tablet_meta_pb.tablet_id();
3678
3679
251
        if (config::enable_recycler_check_lazy_txn_finished &&
3680
251
            !check_lazy_txn_finished(txn_kv_, instance_id_, tablet_meta_pb.tablet_id())) {
3681
1
            LOG(WARNING) << "lazy txn not finished tablet_id=" << tablet_meta_pb.tablet_id();
3682
1
            has_failure = true;
3683
1
            return -1;
3684
1
        }
3685
3686
251
        TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::bypass_check", false);
3687
250
        sync_executor.add(
3688
250
                [this, &num_recycled, tid = tablet_id, &metrics_context, k]() -> TabletInfo {
3689
250
                    if (recycle_tablet(tid, metrics_context) != 0) {
3690
250
                        LOG_WARNING("failed to recycle tablet")
3691
250
                                .tag("instance_id", instance_id_)
3692
250
                                .tag("tablet_id", tid);
3693
250
                        return {.tablet_meta_key = std::string_view(), .tablet_id = tid};
3694
250
                    }
3695
250
                    ++num_recycled;
3696
250
                    LOG(INFO) << "recycle_tablets scan, key=" << (k.empty() ? "(empty)" : hex(k));
3697
250
                    return {.tablet_meta_key = k, .tablet_id = tid};
3698
250
                });
3699
250
        return 0;
3700
250
    };
3701
3702
56
    auto loop_done = [&, this]() -> int {
3703
52
        int ret = 0;
3704
52
        bool finished = true;
3705
52
        bool has_empty_key = false;
3706
52
        DORIS_CLOUD_DEFER {
3707
52
            init_rs_keys.clear();
3708
52
            has_failure = false;
3709
52
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3706
4
        DORIS_CLOUD_DEFER {
3707
4
            init_rs_keys.clear();
3708
4
            has_failure = false;
3709
4
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlvE_clEv
Line
Count
Source
3706
48
        DORIS_CLOUD_DEFER {
3707
48
            init_rs_keys.clear();
3708
48
            has_failure = false;
3709
48
        };
3710
52
        auto tablets_info = sync_executor.when_all(&finished);
3711
52
        if (!finished) {
3712
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3713
1
            return -1;
3714
1
        }
3715
3716
51
        size_t size_before_erase = tablets_info.size();
3717
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
3717
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
3717
249
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3718
51
        if (tablets_info.empty()) {
3719
2
            return size_before_erase == 0 ? 0 : -1;
3720
49
        } else if (size_before_erase != tablets_info.size()) {
3721
1
            has_empty_key = true;
3722
1
        }
3723
3724
49
        ret = has_empty_key ? -1 : 0;
3725
        // sort the vector using key's order
3726
49.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3727
49.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3728
49.4k
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3726
48.4k
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3727
48.4k
            return prev.tablet_meta_key < last.tablet_meta_key;
3728
48.4k
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEvENKUlRKT_RKT0_E_clIZNS1_15recycle_tabletsEllS3_lE10TabletInfoSD_EEDaS7_SA_
Line
Count
Source
3726
958
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3727
958
            return prev.tablet_meta_key < last.tablet_meta_key;
3728
958
        });
3729
49
        std::unique_ptr<Transaction> txn;
3730
49
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3731
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3732
0
            return -1;
3733
0
        }
3734
49
        std::string tablet_key_end;
3735
49
        if (!tablets_info.empty()) {
3736
49
            if (!has_empty_key && !has_failure) {
3737
47
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3738
47
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3739
47
            } else {
3740
8
                for (auto& tablet_info : tablets_info) {
3741
8
                    txn->remove(tablet_info.tablet_meta_key);
3742
8
                }
3743
2
            }
3744
49
        }
3745
49
        if (is_multi_version) {
3746
6
            for (auto& tablet_info : tablets_info) {
3747
                // Remove all versions of tablet compact stats for recycled tablet
3748
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3749
6
                LOG_INFO("remove versioned tablet compact stats key")
3750
6
                        .tag("compact_stats_key", hex(k));
3751
6
                versioned_remove_all(txn.get(), k);
3752
6
            }
3753
6
            for (auto& tablet_info : tablets_info) {
3754
                // Remove all versions of tablet load stats for recycled tablet
3755
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3756
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3757
6
                versioned_remove_all(txn.get(), k);
3758
6
            }
3759
6
            for (auto& tablet_info : tablets_info) {
3760
                // Remove all versions of meta tablet for recycled tablet
3761
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3762
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3763
6
                versioned_remove_all(txn.get(), k);
3764
6
            }
3765
5
        }
3766
4.25k
        for (auto& tablet_info : tablets_info) {
3767
4.25k
            std::string k;
3768
4.25k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3769
4.25k
            txn->remove(k);
3770
4.25k
        }
3771
4.25k
        for (auto& tablet_info : tablets_info) {
3772
4.25k
            std::string k;
3773
4.25k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3774
4.25k
            txn->remove(k);
3775
4.25k
        }
3776
49
        for (auto& k : init_rs_keys) {
3777
0
            txn->remove(k);
3778
0
        }
3779
49
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3780
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3781
0
                         << ", err=" << err;
3782
0
            return -1;
3783
0
        }
3784
49
        return ret;
3785
49
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3702
4
    auto loop_done = [&, this]() -> int {
3703
4
        int ret = 0;
3704
4
        bool finished = true;
3705
4
        bool has_empty_key = false;
3706
4
        DORIS_CLOUD_DEFER {
3707
4
            init_rs_keys.clear();
3708
4
            has_failure = false;
3709
4
        };
3710
4
        auto tablets_info = sync_executor.when_all(&finished);
3711
4
        if (!finished) {
3712
0
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3713
0
            return -1;
3714
0
        }
3715
3716
4
        size_t size_before_erase = tablets_info.size();
3717
4
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3718
4
        if (tablets_info.empty()) {
3719
2
            return size_before_erase == 0 ? 0 : -1;
3720
2
        } else if (size_before_erase != tablets_info.size()) {
3721
0
            has_empty_key = true;
3722
0
        }
3723
3724
2
        ret = has_empty_key ? -1 : 0;
3725
        // sort the vector using key's order
3726
2
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3727
2
            return prev.tablet_meta_key < last.tablet_meta_key;
3728
2
        });
3729
2
        std::unique_ptr<Transaction> txn;
3730
2
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3731
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3732
0
            return -1;
3733
0
        }
3734
2
        std::string tablet_key_end;
3735
2
        if (!tablets_info.empty()) {
3736
2
            if (!has_empty_key && !has_failure) {
3737
2
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3738
2
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3739
2
            } else {
3740
0
                for (auto& tablet_info : tablets_info) {
3741
0
                    txn->remove(tablet_info.tablet_meta_key);
3742
0
                }
3743
0
            }
3744
2
        }
3745
2
        if (is_multi_version) {
3746
0
            for (auto& tablet_info : tablets_info) {
3747
                // Remove all versions of tablet compact stats for recycled tablet
3748
0
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3749
0
                LOG_INFO("remove versioned tablet compact stats key")
3750
0
                        .tag("compact_stats_key", hex(k));
3751
0
                versioned_remove_all(txn.get(), k);
3752
0
            }
3753
0
            for (auto& tablet_info : tablets_info) {
3754
                // Remove all versions of tablet load stats for recycled tablet
3755
0
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3756
0
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3757
0
                versioned_remove_all(txn.get(), k);
3758
0
            }
3759
0
            for (auto& tablet_info : tablets_info) {
3760
                // Remove all versions of meta tablet for recycled tablet
3761
0
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3762
0
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3763
0
                versioned_remove_all(txn.get(), k);
3764
0
            }
3765
0
        }
3766
4.00k
        for (auto& tablet_info : tablets_info) {
3767
4.00k
            std::string k;
3768
4.00k
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3769
4.00k
            txn->remove(k);
3770
4.00k
        }
3771
4.00k
        for (auto& tablet_info : tablets_info) {
3772
4.00k
            std::string k;
3773
4.00k
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3774
4.00k
            txn->remove(k);
3775
4.00k
        }
3776
2
        for (auto& k : init_rs_keys) {
3777
0
            txn->remove(k);
3778
0
        }
3779
2
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3780
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3781
0
                         << ", err=" << err;
3782
0
            return -1;
3783
0
        }
3784
2
        return ret;
3785
2
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_tabletsEllRNS0_22RecyclerMetricsContextElENK3$_3clEv
Line
Count
Source
3702
48
    auto loop_done = [&, this]() -> int {
3703
48
        int ret = 0;
3704
48
        bool finished = true;
3705
48
        bool has_empty_key = false;
3706
48
        DORIS_CLOUD_DEFER {
3707
48
            init_rs_keys.clear();
3708
48
            has_failure = false;
3709
48
        };
3710
48
        auto tablets_info = sync_executor.when_all(&finished);
3711
48
        if (!finished) {
3712
1
            LOG_WARNING("failed to recycle tablet").tag("instance_id", instance_id_);
3713
1
            return -1;
3714
1
        }
3715
3716
47
        size_t size_before_erase = tablets_info.size();
3717
47
        std::erase_if(tablets_info, [](const TabletInfo& t) { return t.tablet_meta_key.empty(); });
3718
47
        if (tablets_info.empty()) {
3719
0
            return size_before_erase == 0 ? 0 : -1;
3720
47
        } else if (size_before_erase != tablets_info.size()) {
3721
1
            has_empty_key = true;
3722
1
        }
3723
3724
47
        ret = has_empty_key ? -1 : 0;
3725
        // sort the vector using key's order
3726
47
        std::ranges::sort(tablets_info, [](const auto& prev, const auto& last) {
3727
47
            return prev.tablet_meta_key < last.tablet_meta_key;
3728
47
        });
3729
47
        std::unique_ptr<Transaction> txn;
3730
47
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3731
0
            LOG(WARNING) << "failed to delete tablet meta kv, instance_id=" << instance_id_;
3732
0
            return -1;
3733
0
        }
3734
47
        std::string tablet_key_end;
3735
47
        if (!tablets_info.empty()) {
3736
47
            if (!has_empty_key && !has_failure) {
3737
45
                tablet_key_end = std::string(tablets_info.back().tablet_meta_key) + '\x00';
3738
45
                txn->remove(tablets_info.front().tablet_meta_key, tablet_key_end);
3739
45
            } else {
3740
8
                for (auto& tablet_info : tablets_info) {
3741
8
                    txn->remove(tablet_info.tablet_meta_key);
3742
8
                }
3743
2
            }
3744
47
        }
3745
47
        if (is_multi_version) {
3746
6
            for (auto& tablet_info : tablets_info) {
3747
                // Remove all versions of tablet compact stats for recycled tablet
3748
6
                auto k = versioned::tablet_compact_stats_key({instance_id_, tablet_info.tablet_id});
3749
6
                LOG_INFO("remove versioned tablet compact stats key")
3750
6
                        .tag("compact_stats_key", hex(k));
3751
6
                versioned_remove_all(txn.get(), k);
3752
6
            }
3753
6
            for (auto& tablet_info : tablets_info) {
3754
                // Remove all versions of tablet load stats for recycled tablet
3755
6
                auto k = versioned::tablet_load_stats_key({instance_id_, tablet_info.tablet_id});
3756
6
                LOG_INFO("remove versioned tablet load stats key").tag("load_stats_key", hex(k));
3757
6
                versioned_remove_all(txn.get(), k);
3758
6
            }
3759
6
            for (auto& tablet_info : tablets_info) {
3760
                // Remove all versions of meta tablet for recycled tablet
3761
6
                auto k = versioned::meta_tablet_key({instance_id_, tablet_info.tablet_id});
3762
6
                LOG_INFO("remove versioned meta tablet key").tag("meta_tablet_key", hex(k));
3763
6
                versioned_remove_all(txn.get(), k);
3764
6
            }
3765
5
        }
3766
248
        for (auto& tablet_info : tablets_info) {
3767
248
            std::string k;
3768
248
            meta_tablet_idx_key({instance_id_, tablet_info.tablet_id}, &k);
3769
248
            txn->remove(k);
3770
248
        }
3771
248
        for (auto& tablet_info : tablets_info) {
3772
248
            std::string k;
3773
248
            job_restore_tablet_key({instance_id_, tablet_info.tablet_id}, &k);
3774
248
            txn->remove(k);
3775
248
        }
3776
47
        for (auto& k : init_rs_keys) {
3777
0
            txn->remove(k);
3778
0
        }
3779
47
        if (TxnErrorCode err = txn->commit(); err != TxnErrorCode::TXN_OK) {
3780
0
            LOG(WARNING) << "failed to delete kvs related to tablets, instance_id=" << instance_id_
3781
0
                         << ", err=" << err;
3782
0
            return -1;
3783
0
        }
3784
47
        return ret;
3785
47
    };
3786
3787
56
    int ret = scan_and_recycle(tablet_key_begin, tablet_key_end, std::move(recycle_func),
3788
56
                               std::move(loop_done));
3789
56
    if (ret != 0) {
3790
5
        LOG(WARNING) << "failed to scan_and_recycle, instance_id=" << instance_id_;
3791
5
        return ret;
3792
5
    }
3793
3794
    // directly remove tablet stats and tablet jobs of these dropped index or partition
3795
51
    std::unique_ptr<Transaction> txn;
3796
51
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
3797
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_;
3798
0
        return -1;
3799
0
    }
3800
51
    txn->remove(stats_key_begin, stats_key_end);
3801
51
    LOG(WARNING) << "remove stats kv, begin=" << hex(stats_key_begin)
3802
51
                 << " end=" << hex(stats_key_end);
3803
51
    txn->remove(job_key_begin, job_key_end);
3804
51
    LOG(WARNING) << "remove job kv, begin=" << hex(job_key_begin) << " end=" << hex(job_key_end);
3805
51
    std::string schema_key_begin, schema_key_end;
3806
51
    std::string schema_dict_key;
3807
51
    std::string versioned_schema_key_begin, versioned_schema_key_end;
3808
51
    if (partition_id <= 0) {
3809
        // Delete schema kv of this index
3810
15
        meta_schema_key({instance_id_, index_id, 0}, &schema_key_begin);
3811
15
        meta_schema_key({instance_id_, index_id + 1, 0}, &schema_key_end);
3812
15
        txn->remove(schema_key_begin, schema_key_end);
3813
15
        LOG(WARNING) << "remove schema kv, begin=" << hex(schema_key_begin)
3814
15
                     << " end=" << hex(schema_key_end);
3815
15
        meta_schema_pb_dictionary_key({instance_id_, index_id}, &schema_dict_key);
3816
15
        txn->remove(schema_dict_key);
3817
15
        LOG(WARNING) << "remove schema dict kv, key=" << hex(schema_dict_key);
3818
15
        versioned::meta_schema_key({instance_id_, index_id, 0}, &versioned_schema_key_begin);
3819
15
        versioned::meta_schema_key({instance_id_, index_id + 1, 0}, &versioned_schema_key_end);
3820
15
        txn->remove(versioned_schema_key_begin, versioned_schema_key_end);
3821
15
        LOG(WARNING) << "remove versioned schema kv, begin=" << hex(versioned_schema_key_begin)
3822
15
                     << " end=" << hex(versioned_schema_key_end);
3823
15
    }
3824
3825
51
    TxnErrorCode err = txn->commit();
3826
51
    if (err != TxnErrorCode::TXN_OK) {
3827
0
        LOG(WARNING) << "failed to delete tablet job or stats key, instance_id=" << instance_id_
3828
0
                     << " err=" << err;
3829
0
        return -1;
3830
0
    }
3831
3832
51
    return ret;
3833
51
}
3834
3835
5.61k
int InstanceRecycler::delete_rowset_data(const RowsetMetaCloudPB& rs_meta_pb) {
3836
5.61k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("delete_rowset_data::bypass_check", true);
3837
5.61k
    int64_t num_segments = rs_meta_pb.num_segments();
3838
5.61k
    if (num_segments <= 0) return 0;
3839
3840
5.61k
    std::vector<std::string> file_paths;
3841
5.61k
    if (decrement_packed_file_ref_counts(rs_meta_pb) != 0) {
3842
0
        return -1;
3843
0
    }
3844
3845
    // Process inverted indexes
3846
5.61k
    std::vector<std::pair<int64_t, std::string>> index_ids;
3847
5.61k
    InvertedIndexStorageFormatPB index_format = rs_meta_pb.has_inverted_index_storage_format()
3848
5.61k
                                                        ? rs_meta_pb.inverted_index_storage_format()
3849
5.61k
                                                        : InvertedIndexStorageFormatPB::V1;
3850
5.61k
    bool delete_rowset_data_by_prefix = false;
3851
5.61k
    if (rs_meta_pb.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
3852
        // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
3853
        // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
3854
0
        delete_rowset_data_by_prefix = true;
3855
5.61k
    } else if (rs_meta_pb.has_tablet_schema()) {
3856
10.0k
        for (const auto& index : rs_meta_pb.tablet_schema().index()) {
3857
10.0k
            if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
3858
10.0k
                index_ids.emplace_back(index.index_id(), index.index_suffix_name());
3859
10.0k
            }
3860
10.0k
        }
3861
4.80k
        if (!rs_meta_pb.has_inverted_index_storage_format() &&
3862
4.80k
            rs_meta_pb.tablet_schema().has_inverted_index_storage_format()) {
3863
2.00k
            index_format = rs_meta_pb.tablet_schema().inverted_index_storage_format();
3864
2.00k
        }
3865
4.80k
    } else if (!rs_meta_pb.has_index_id() || !rs_meta_pb.has_schema_version()) {
3866
        // schema version and index id are not found, delete rowset data by prefix directly.
3867
0
        delete_rowset_data_by_prefix = true;
3868
809
    } else {
3869
        // otherwise, try to get schema kv
3870
809
        InvertedIndexInfo index_info;
3871
809
        int inverted_index_get_ret = inverted_index_id_cache_->get(
3872
809
                rs_meta_pb.index_id(), rs_meta_pb.schema_version(), index_info);
3873
809
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
3874
809
                                 &inverted_index_get_ret);
3875
809
        if (inverted_index_get_ret == 0) {
3876
809
            if (!rs_meta_pb.has_inverted_index_storage_format()) {
3877
809
                index_format = index_info.first;
3878
809
            }
3879
809
            index_ids = index_info.second;
3880
809
        } else if (inverted_index_get_ret == 1) {
3881
            // 1. Schema kv not found means tablet has been recycled
3882
            // Maybe some tablet recycle failed by some bugs
3883
            // We need to delete again to double check
3884
            // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
3885
            // because we are uncertain about the inverted index information.
3886
            // If there are inverted indexes, some data might not be deleted,
3887
            // but this is acceptable as we have made our best effort to delete the data.
3888
0
            LOG_INFO(
3889
0
                    "delete rowset data schema kv not found, need to delete again to double "
3890
0
                    "check")
3891
0
                    .tag("instance_id", instance_id_)
3892
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
3893
0
                    .tag("rowset", rs_meta_pb.ShortDebugString());
3894
            // Currently index_ids is guaranteed to be empty,
3895
            // but we clear it again here as a safeguard against future code changes
3896
            // that might cause index_ids to no longer be empty
3897
0
            index_format = InvertedIndexStorageFormatPB::V2;
3898
0
            index_ids.clear();
3899
0
        } else {
3900
            // failed to get schema kv, delete rowset data by prefix directly.
3901
0
            delete_rowset_data_by_prefix = true;
3902
0
        }
3903
809
    }
3904
3905
5.61k
    if (delete_rowset_data_by_prefix) {
3906
0
        return delete_rowset_data(rs_meta_pb.resource_id(), rs_meta_pb.tablet_id(),
3907
0
                                  rs_meta_pb.rowset_id_v2());
3908
0
    }
3909
3910
5.61k
    auto it = accessor_map_.find(rs_meta_pb.resource_id());
3911
5.61k
    if (it == accessor_map_.end()) {
3912
1.59k
        LOG_WARNING("instance has no such resource id")
3913
1.59k
                .tag("instance_id", instance_id_)
3914
1.59k
                .tag("resource_id", rs_meta_pb.resource_id());
3915
1.59k
        return -1;
3916
1.59k
    }
3917
4.01k
    auto& accessor = it->second;
3918
3919
4.01k
    int64_t tablet_id = rs_meta_pb.tablet_id();
3920
4.01k
    const auto& rowset_id = rs_meta_pb.rowset_id_v2();
3921
24.0k
    for (int64_t i = 0; i < num_segments; ++i) {
3922
20.0k
        auto segment_id = rowset_segment_id(rs_meta_pb, i);
3923
20.0k
        add_file_to_delete_if_not_packed(rs_meta_pb, segment_path(tablet_id, rowset_id, segment_id),
3924
20.0k
                                         &file_paths);
3925
20.0k
        if (index_format == InvertedIndexStorageFormatPB::V1) {
3926
40.0k
            for (const auto& index_id : index_ids) {
3927
40.0k
                add_file_to_delete_if_not_packed(
3928
40.0k
                        rs_meta_pb,
3929
40.0k
                        inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
3930
40.0k
                                               index_id.second),
3931
40.0k
                        &file_paths);
3932
40.0k
            }
3933
20.0k
        } else if (!index_ids.empty()) {
3934
2
            add_file_to_delete_if_not_packed(
3935
2
                    rs_meta_pb, inverted_index_path_v2(tablet_id, rowset_id, segment_id),
3936
2
                    &file_paths);
3937
2
        }
3938
20.0k
    }
3939
3940
    // Process delete bitmap - check where it's stored.
3941
4.01k
    DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
3942
4.01k
    if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rowset_id,
3943
4.01k
                                                       &delete_bitmap_storage_type) != 0) {
3944
0
        LOG_WARNING("failed to decrement delete bitmap packed file ref count")
3945
0
                .tag("instance_id", instance_id_)
3946
0
                .tag("tablet_id", tablet_id)
3947
0
                .tag("rowset_id", rowset_id);
3948
0
        return -1;
3949
0
    }
3950
4.01k
    if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
3951
2.00k
        file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
3952
2.00k
    }
3953
    // TODO(AlexYue): seems could do do batch
3954
4.01k
    return accessor->delete_files(file_paths);
3955
4.01k
}
3956
3957
62.6k
int InstanceRecycler::decrement_packed_file_ref_counts(const doris::RowsetMetaCloudPB& rs_meta_pb) {
3958
62.6k
    LOG_INFO("begin process_packed_file_location_index")
3959
62.6k
            .tag("instance_id", instance_id_)
3960
62.6k
            .tag("tablet_id", rs_meta_pb.tablet_id())
3961
62.6k
            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3962
62.6k
            .tag("index_map_size", rs_meta_pb.packed_slice_locations_size());
3963
62.6k
    const auto& index_map = rs_meta_pb.packed_slice_locations();
3964
62.6k
    if (index_map.empty()) {
3965
62.6k
        LOG_INFO("skip merge file update: empty merge_file_segment_index")
3966
62.6k
                .tag("instance_id", instance_id_)
3967
62.6k
                .tag("tablet_id", rs_meta_pb.tablet_id())
3968
62.6k
                .tag("rowset_id", rs_meta_pb.rowset_id_v2());
3969
62.6k
        return 0;
3970
62.6k
    }
3971
3972
15
    struct PackedSmallFileInfo {
3973
15
        std::string small_file_path;
3974
15
    };
3975
15
    std::unordered_map<std::string, std::vector<PackedSmallFileInfo>> packed_file_updates;
3976
15
    packed_file_updates.reserve(index_map.size());
3977
27
    for (const auto& [small_path, index_pb] : index_map) {
3978
27
        if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
3979
0
            continue;
3980
0
        }
3981
27
        packed_file_updates[index_pb.packed_file_path()].push_back(
3982
27
                PackedSmallFileInfo {small_path});
3983
27
    }
3984
15
    if (packed_file_updates.empty()) {
3985
0
        LOG_INFO("skip packed file update: no valid merge_file_path in merge_file_segment_index")
3986
0
                .tag("instance_id", instance_id_)
3987
0
                .tag("tablet_id", rs_meta_pb.tablet_id())
3988
0
                .tag("rowset_id", rs_meta_pb.rowset_id_v2())
3989
0
                .tag("index_map_size", index_map.size());
3990
0
        return 0;
3991
0
    }
3992
3993
15
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
3994
15
    int ret = 0;
3995
24
    for (auto& [packed_file_path, small_files] : packed_file_updates) {
3996
24
        if (small_files.empty()) {
3997
0
            continue;
3998
0
        }
3999
4000
24
        bool success = false;
4001
24
        for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4002
24
            std::unique_ptr<Transaction> txn;
4003
24
            TxnErrorCode err = txn_kv_->create_txn(&txn);
4004
24
            if (err != TxnErrorCode::TXN_OK) {
4005
0
                LOG_WARNING("failed to create txn when updating packed file ref count")
4006
0
                        .tag("instance_id", instance_id_)
4007
0
                        .tag("packed_file_path", packed_file_path)
4008
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4009
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4010
0
                        .tag("err", err);
4011
0
                ret = -1;
4012
0
                break;
4013
0
            }
4014
4015
24
            std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4016
24
            std::string packed_val;
4017
24
            err = txn->get(packed_key, &packed_val);
4018
24
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4019
0
                LOG_WARNING("packed file info not found when recycling rowset")
4020
0
                        .tag("instance_id", instance_id_)
4021
0
                        .tag("packed_file_path", packed_file_path)
4022
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4023
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4024
0
                        .tag("key", hex(packed_key))
4025
0
                        .tag("tablet id", rs_meta_pb.tablet_id());
4026
                // Skip this packed file entry and continue with others
4027
0
                success = true;
4028
0
                break;
4029
0
            }
4030
24
            if (err != TxnErrorCode::TXN_OK) {
4031
0
                LOG_WARNING("failed to get packed file info when recycling rowset")
4032
0
                        .tag("instance_id", instance_id_)
4033
0
                        .tag("packed_file_path", packed_file_path)
4034
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4035
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4036
0
                        .tag("err", err);
4037
0
                ret = -1;
4038
0
                break;
4039
0
            }
4040
4041
24
            cloud::PackedFileInfoPB packed_info;
4042
24
            if (!packed_info.ParseFromString(packed_val)) {
4043
0
                LOG_WARNING("failed to parse packed file info when recycling rowset")
4044
0
                        .tag("instance_id", instance_id_)
4045
0
                        .tag("packed_file_path", packed_file_path)
4046
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4047
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4048
0
                ret = -1;
4049
0
                break;
4050
0
            }
4051
4052
24
            LOG_INFO("packed file update check")
4053
24
                    .tag("instance_id", instance_id_)
4054
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4055
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4056
24
                    .tag("merged_file_path", packed_file_path)
4057
24
                    .tag("requested_small_files", small_files.size())
4058
24
                    .tag("merge_entries", packed_info.slices_size());
4059
4060
24
            auto* small_file_entries = packed_info.mutable_slices();
4061
24
            int64_t changed_files = 0;
4062
24
            int64_t missing_entries = 0;
4063
24
            int64_t already_deleted = 0;
4064
27
            for (const auto& small_file_info : small_files) {
4065
27
                bool found = false;
4066
87
                for (auto& small_file_entry : *small_file_entries) {
4067
87
                    if (small_file_entry.path() == small_file_info.small_file_path) {
4068
27
                        if (!small_file_entry.deleted()) {
4069
27
                            small_file_entry.set_deleted(true);
4070
27
                            if (!small_file_entry.corrected()) {
4071
27
                                small_file_entry.set_corrected(true);
4072
27
                            }
4073
27
                            ++changed_files;
4074
27
                        } else {
4075
0
                            ++already_deleted;
4076
0
                        }
4077
27
                        found = true;
4078
27
                        break;
4079
27
                    }
4080
87
                }
4081
27
                if (!found) {
4082
0
                    ++missing_entries;
4083
0
                    LOG_WARNING("packed file info missing small file entry")
4084
0
                            .tag("instance_id", instance_id_)
4085
0
                            .tag("packed_file_path", packed_file_path)
4086
0
                            .tag("small_file_path", small_file_info.small_file_path)
4087
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4088
0
                            .tag("tablet_id", rs_meta_pb.tablet_id());
4089
0
                }
4090
27
            }
4091
4092
24
            if (changed_files == 0) {
4093
0
                LOG_INFO("skip merge file update: no merge entries changed")
4094
0
                        .tag("instance_id", instance_id_)
4095
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4096
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4097
0
                        .tag("merged_file_path", packed_file_path)
4098
0
                        .tag("missing_entries", missing_entries)
4099
0
                        .tag("already_deleted", already_deleted)
4100
0
                        .tag("requested_small_files", small_files.size())
4101
0
                        .tag("merge_entries", packed_info.slices_size());
4102
0
                success = true;
4103
0
                break;
4104
0
            }
4105
4106
            // Calculate remaining files
4107
24
            int64_t left_file_count = 0;
4108
24
            int64_t left_file_bytes = 0;
4109
141
            for (const auto& small_file_entry : packed_info.slices()) {
4110
141
                if (!small_file_entry.deleted()) {
4111
57
                    ++left_file_count;
4112
57
                    left_file_bytes += small_file_entry.size();
4113
57
                }
4114
141
            }
4115
24
            packed_info.set_remaining_slice_bytes(left_file_bytes);
4116
24
            packed_info.set_ref_cnt(left_file_count);
4117
24
            LOG_INFO("updated packed file reference info")
4118
24
                    .tag("instance_id", instance_id_)
4119
24
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4120
24
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4121
24
                    .tag("packed_file_path", packed_file_path)
4122
24
                    .tag("ref_cnt", left_file_count)
4123
24
                    .tag("left_file_bytes", left_file_bytes);
4124
4125
24
            if (left_file_count == 0) {
4126
7
                packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4127
7
            }
4128
4129
24
            std::string updated_val;
4130
24
            if (!packed_info.SerializeToString(&updated_val)) {
4131
0
                LOG_WARNING("failed to serialize packed file info when recycling rowset")
4132
0
                        .tag("instance_id", instance_id_)
4133
0
                        .tag("packed_file_path", packed_file_path)
4134
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4135
0
                        .tag("tablet_id", rs_meta_pb.tablet_id());
4136
0
                ret = -1;
4137
0
                break;
4138
0
            }
4139
4140
24
            txn->put(packed_key, updated_val);
4141
24
            err = txn->commit();
4142
24
            if (err == TxnErrorCode::TXN_OK) {
4143
24
                success = true;
4144
24
                if (left_file_count == 0) {
4145
7
                    LOG_INFO("packed file ready to delete, deleting immediately")
4146
7
                            .tag("instance_id", instance_id_)
4147
7
                            .tag("packed_file_path", packed_file_path);
4148
7
                    if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4149
0
                        ret = -1;
4150
0
                    }
4151
7
                }
4152
24
                break;
4153
24
            }
4154
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
4155
0
                if (attempt >= max_retry_times) {
4156
0
                    LOG_WARNING("packed file info update conflict after max retry")
4157
0
                            .tag("instance_id", instance_id_)
4158
0
                            .tag("packed_file_path", packed_file_path)
4159
0
                            .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4160
0
                            .tag("tablet_id", rs_meta_pb.tablet_id())
4161
0
                            .tag("changed_files", changed_files)
4162
0
                            .tag("attempt", attempt);
4163
0
                    ret = -1;
4164
0
                    break;
4165
0
                }
4166
0
                LOG_WARNING("packed file info update conflict, retrying")
4167
0
                        .tag("instance_id", instance_id_)
4168
0
                        .tag("packed_file_path", packed_file_path)
4169
0
                        .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4170
0
                        .tag("tablet_id", rs_meta_pb.tablet_id())
4171
0
                        .tag("changed_files", changed_files)
4172
0
                        .tag("attempt", attempt);
4173
0
                sleep_for_packed_file_retry();
4174
0
                continue;
4175
0
            }
4176
4177
0
            LOG_WARNING("failed to commit packed file info update")
4178
0
                    .tag("instance_id", instance_id_)
4179
0
                    .tag("packed_file_path", packed_file_path)
4180
0
                    .tag("rowset_id", rs_meta_pb.rowset_id_v2())
4181
0
                    .tag("tablet_id", rs_meta_pb.tablet_id())
4182
0
                    .tag("err", err)
4183
0
                    .tag("changed_files", changed_files);
4184
0
            ret = -1;
4185
0
            break;
4186
0
        }
4187
4188
24
        if (!success) {
4189
0
            ret = -1;
4190
0
        }
4191
24
    }
4192
4193
15
    return ret;
4194
15
}
4195
4196
int InstanceRecycler::decrement_delete_bitmap_packed_file_ref_counts(
4197
        int64_t tablet_id, const std::string& rowset_id, DeleteBitmapStorageType* out_storage_type,
4198
61.0k
        std::vector<std::string>* keys) {
4199
61.0k
    if (out_storage_type) {
4200
58.4k
        *out_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4201
58.4k
    }
4202
4203
    // Get delete bitmap storage info from FDB
4204
61.0k
    std::string dbm_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4205
61.0k
    std::unique_ptr<Transaction> txn;
4206
61.0k
    TxnErrorCode err = txn_kv_->create_txn(&txn);
4207
61.0k
    if (err != TxnErrorCode::TXN_OK) {
4208
0
        LOG_WARNING("failed to create txn when getting delete bitmap storage")
4209
0
                .tag("instance_id", instance_id_)
4210
0
                .tag("tablet_id", tablet_id)
4211
0
                .tag("rowset_id", rowset_id)
4212
0
                .tag("err", err);
4213
0
        return -1;
4214
0
    }
4215
4216
61.0k
    ValueBuf dbm_val;
4217
61.0k
    err = cloud::blob_get(txn.get(), dbm_key, &dbm_val);
4218
61.0k
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4219
        // No delete bitmap for this rowset, nothing to do
4220
6.19k
        LOG_INFO("delete bitmap not found, skip packed file ref count decrement")
4221
6.19k
                .tag("instance_id", instance_id_)
4222
6.19k
                .tag("tablet_id", tablet_id)
4223
6.19k
                .tag("rowset_id", rowset_id);
4224
6.19k
        return 0;
4225
6.19k
    }
4226
54.8k
    if (err != TxnErrorCode::TXN_OK) {
4227
0
        LOG_WARNING("failed to get delete bitmap storage")
4228
0
                .tag("instance_id", instance_id_)
4229
0
                .tag("tablet_id", tablet_id)
4230
0
                .tag("rowset_id", rowset_id)
4231
0
                .tag("err", err);
4232
0
        return -1;
4233
0
    }
4234
4235
54.8k
    if (keys) {
4236
1.55k
        for (auto& key : dbm_val.keys()) {
4237
1.55k
            keys->push_back(std::move(key));
4238
1.55k
        }
4239
1.55k
    }
4240
4241
54.8k
    DeleteBitmapStoragePB storage;
4242
54.8k
    if (!dbm_val.to_pb(&storage)) {
4243
0
        LOG_WARNING("failed to parse delete bitmap storage")
4244
0
                .tag("instance_id", instance_id_)
4245
0
                .tag("tablet_id", tablet_id)
4246
0
                .tag("rowset_id", rowset_id);
4247
0
        return -1;
4248
0
    }
4249
4250
54.8k
    if (storage.store_in_fdb()) {
4251
1
        if (out_storage_type) {
4252
1
            *out_storage_type = DeleteBitmapStorageType::IN_FDB;
4253
1
        }
4254
1
        return 0;
4255
1
    }
4256
4257
    // Check if delete bitmap is stored in standalone file.
4258
54.8k
    if (!storage.has_packed_slice_location() ||
4259
54.8k
        storage.packed_slice_location().packed_file_path().empty()) {
4260
54.8k
        if (out_storage_type) {
4261
53.5k
            *out_storage_type = DeleteBitmapStorageType::STANDALONE_FILE;
4262
53.5k
        }
4263
54.8k
        return 0;
4264
54.8k
    }
4265
4266
18.4E
    if (out_storage_type) {
4267
0
        *out_storage_type = DeleteBitmapStorageType::PACKED_FILE;
4268
0
    }
4269
4270
18.4E
    const auto& packed_loc = storage.packed_slice_location();
4271
18.4E
    const std::string& packed_file_path = packed_loc.packed_file_path();
4272
4273
18.4E
    LOG_INFO("decrementing delete bitmap packed file ref count")
4274
18.4E
            .tag("instance_id", instance_id_)
4275
18.4E
            .tag("tablet_id", tablet_id)
4276
18.4E
            .tag("rowset_id", rowset_id)
4277
18.4E
            .tag("packed_file_path", packed_file_path);
4278
4279
18.4E
    const int max_retry_times = std::max(1, config::decrement_packed_file_ref_counts_retry_times);
4280
18.4E
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4281
1
        std::unique_ptr<Transaction> update_txn;
4282
1
        err = txn_kv_->create_txn(&update_txn);
4283
1
        if (err != TxnErrorCode::TXN_OK) {
4284
0
            LOG_WARNING("failed to create txn for delete bitmap packed file update")
4285
0
                    .tag("instance_id", instance_id_)
4286
0
                    .tag("tablet_id", tablet_id)
4287
0
                    .tag("rowset_id", rowset_id)
4288
0
                    .tag("err", err);
4289
0
            return -1;
4290
0
        }
4291
4292
1
        std::string packed_key = packed_file_key({instance_id_, packed_file_path});
4293
1
        std::string packed_val;
4294
1
        err = update_txn->get(packed_key, &packed_val);
4295
1
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4296
0
            LOG_WARNING("packed file info not found for delete bitmap")
4297
0
                    .tag("instance_id", instance_id_)
4298
0
                    .tag("tablet_id", tablet_id)
4299
0
                    .tag("rowset_id", rowset_id)
4300
0
                    .tag("packed_file_path", packed_file_path);
4301
0
            return 0;
4302
0
        }
4303
1
        if (err != TxnErrorCode::TXN_OK) {
4304
0
            LOG_WARNING("failed to get packed file info for delete bitmap")
4305
0
                    .tag("instance_id", instance_id_)
4306
0
                    .tag("tablet_id", tablet_id)
4307
0
                    .tag("rowset_id", rowset_id)
4308
0
                    .tag("packed_file_path", packed_file_path)
4309
0
                    .tag("err", err);
4310
0
            return -1;
4311
0
        }
4312
4313
1
        cloud::PackedFileInfoPB packed_info;
4314
1
        if (!packed_info.ParseFromString(packed_val)) {
4315
0
            LOG_WARNING("failed to parse packed file info for delete bitmap")
4316
0
                    .tag("instance_id", instance_id_)
4317
0
                    .tag("tablet_id", tablet_id)
4318
0
                    .tag("rowset_id", rowset_id)
4319
0
                    .tag("packed_file_path", packed_file_path);
4320
0
            return -1;
4321
0
        }
4322
4323
        // Find and mark the small file entry as deleted
4324
        // Use tablet_id and rowset_id to match entry instead of path,
4325
        // because path format may vary with path_version (with or without shard prefix)
4326
1
        auto* entries = packed_info.mutable_slices();
4327
1
        bool found = false;
4328
1
        bool already_deleted = false;
4329
1
        for (auto& entry : *entries) {
4330
1
            if (entry.tablet_id() == tablet_id && entry.rowset_id() == rowset_id) {
4331
1
                if (!entry.deleted()) {
4332
1
                    entry.set_deleted(true);
4333
1
                    if (!entry.corrected()) {
4334
1
                        entry.set_corrected(true);
4335
1
                    }
4336
1
                } else {
4337
0
                    already_deleted = true;
4338
0
                }
4339
1
                found = true;
4340
1
                break;
4341
1
            }
4342
1
        }
4343
4344
1
        if (!found) {
4345
0
            LOG_WARNING("delete bitmap entry not found in packed file")
4346
0
                    .tag("instance_id", instance_id_)
4347
0
                    .tag("tablet_id", tablet_id)
4348
0
                    .tag("rowset_id", rowset_id)
4349
0
                    .tag("packed_file_path", packed_file_path);
4350
0
            return 0;
4351
0
        }
4352
4353
1
        if (already_deleted) {
4354
0
            LOG_INFO("delete bitmap entry already deleted in packed file")
4355
0
                    .tag("instance_id", instance_id_)
4356
0
                    .tag("tablet_id", tablet_id)
4357
0
                    .tag("rowset_id", rowset_id)
4358
0
                    .tag("packed_file_path", packed_file_path);
4359
0
            return 0;
4360
0
        }
4361
4362
        // Calculate remaining files
4363
1
        int64_t left_file_count = 0;
4364
1
        int64_t left_file_bytes = 0;
4365
1
        for (const auto& entry : packed_info.slices()) {
4366
1
            if (!entry.deleted()) {
4367
0
                ++left_file_count;
4368
0
                left_file_bytes += entry.size();
4369
0
            }
4370
1
        }
4371
1
        packed_info.set_remaining_slice_bytes(left_file_bytes);
4372
1
        packed_info.set_ref_cnt(left_file_count);
4373
4374
1
        if (left_file_count == 0) {
4375
1
            packed_info.set_state(cloud::PackedFileInfoPB::RECYCLING);
4376
1
        }
4377
4378
1
        std::string updated_val;
4379
1
        if (!packed_info.SerializeToString(&updated_val)) {
4380
0
            LOG_WARNING("failed to serialize packed file info for delete bitmap")
4381
0
                    .tag("instance_id", instance_id_)
4382
0
                    .tag("tablet_id", tablet_id)
4383
0
                    .tag("rowset_id", rowset_id)
4384
0
                    .tag("packed_file_path", packed_file_path);
4385
0
            return -1;
4386
0
        }
4387
4388
1
        update_txn->put(packed_key, updated_val);
4389
1
        err = update_txn->commit();
4390
1
        if (err == TxnErrorCode::TXN_OK) {
4391
1
            LOG_INFO("delete bitmap packed file ref count decremented")
4392
1
                    .tag("instance_id", instance_id_)
4393
1
                    .tag("tablet_id", tablet_id)
4394
1
                    .tag("rowset_id", rowset_id)
4395
1
                    .tag("packed_file_path", packed_file_path)
4396
1
                    .tag("left_file_count", left_file_count);
4397
1
            if (left_file_count == 0) {
4398
1
                if (delete_packed_file_and_kv(packed_file_path, packed_key, packed_info) != 0) {
4399
0
                    return -1;
4400
0
                }
4401
1
            }
4402
1
            return 0;
4403
1
        }
4404
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4405
0
            if (attempt >= max_retry_times) {
4406
0
                LOG_WARNING("delete bitmap packed file update conflict after max retry")
4407
0
                        .tag("instance_id", instance_id_)
4408
0
                        .tag("tablet_id", tablet_id)
4409
0
                        .tag("rowset_id", rowset_id)
4410
0
                        .tag("packed_file_path", packed_file_path)
4411
0
                        .tag("attempt", attempt);
4412
0
                return -1;
4413
0
            }
4414
0
            sleep_for_packed_file_retry();
4415
0
            continue;
4416
0
        }
4417
4418
0
        LOG_WARNING("failed to commit delete bitmap packed file update")
4419
0
                .tag("instance_id", instance_id_)
4420
0
                .tag("tablet_id", tablet_id)
4421
0
                .tag("rowset_id", rowset_id)
4422
0
                .tag("packed_file_path", packed_file_path)
4423
0
                .tag("err", err);
4424
0
        return -1;
4425
0
    }
4426
4427
18.4E
    return -1;
4428
18.4E
}
4429
4430
int InstanceRecycler::delete_packed_file_and_kv(const std::string& packed_file_path,
4431
                                                const std::string& packed_key,
4432
8
                                                const cloud::PackedFileInfoPB& packed_info) {
4433
8
    if (!packed_info.has_resource_id() || packed_info.resource_id().empty()) {
4434
0
        LOG_WARNING("packed file missing resource id when recycling")
4435
0
                .tag("instance_id", instance_id_)
4436
0
                .tag("packed_file_path", packed_file_path);
4437
0
        return -1;
4438
0
    }
4439
4440
8
    auto [resource_id, accessor] = resolve_packed_file_accessor(packed_info.resource_id());
4441
8
    if (!accessor) {
4442
0
        LOG_WARNING("no accessor available to delete packed file")
4443
0
                .tag("instance_id", instance_id_)
4444
0
                .tag("packed_file_path", packed_file_path)
4445
0
                .tag("resource_id", packed_info.resource_id());
4446
0
        return -1;
4447
0
    }
4448
4449
8
    int del_ret = accessor->delete_file(packed_file_path);
4450
8
    if (del_ret != 0 && del_ret != 1) {
4451
0
        LOG_WARNING("failed to delete packed file")
4452
0
                .tag("instance_id", instance_id_)
4453
0
                .tag("packed_file_path", packed_file_path)
4454
0
                .tag("resource_id", resource_id)
4455
0
                .tag("ret", del_ret);
4456
0
        return -1;
4457
0
    }
4458
8
    if (del_ret == 1) {
4459
0
        LOG_INFO("packed file already removed")
4460
0
                .tag("instance_id", instance_id_)
4461
0
                .tag("packed_file_path", packed_file_path)
4462
0
                .tag("resource_id", resource_id);
4463
8
    } else {
4464
8
        LOG_INFO("deleted packed file")
4465
8
                .tag("instance_id", instance_id_)
4466
8
                .tag("packed_file_path", packed_file_path)
4467
8
                .tag("resource_id", resource_id);
4468
8
    }
4469
4470
8
    const int max_retry_times = std::max(1, config::packed_file_txn_retry_times);
4471
8
    for (int attempt = 1; attempt <= max_retry_times; ++attempt) {
4472
8
        std::unique_ptr<Transaction> del_txn;
4473
8
        TxnErrorCode err = txn_kv_->create_txn(&del_txn);
4474
8
        if (err != TxnErrorCode::TXN_OK) {
4475
0
            LOG_WARNING("failed to create txn when removing packed file kv")
4476
0
                    .tag("instance_id", instance_id_)
4477
0
                    .tag("packed_file_path", packed_file_path)
4478
0
                    .tag("attempt", attempt)
4479
0
                    .tag("err", err);
4480
0
            return -1;
4481
0
        }
4482
4483
8
        std::string latest_val;
4484
8
        err = del_txn->get(packed_key, &latest_val);
4485
8
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
4486
0
            return 0;
4487
0
        }
4488
8
        if (err != TxnErrorCode::TXN_OK) {
4489
0
            LOG_WARNING("failed to re-read packed file kv before removal")
4490
0
                    .tag("instance_id", instance_id_)
4491
0
                    .tag("packed_file_path", packed_file_path)
4492
0
                    .tag("attempt", attempt)
4493
0
                    .tag("err", err);
4494
0
            return -1;
4495
0
        }
4496
4497
8
        cloud::PackedFileInfoPB latest_info;
4498
8
        if (!latest_info.ParseFromString(latest_val)) {
4499
0
            LOG_WARNING("failed to parse packed file info before removal")
4500
0
                    .tag("instance_id", instance_id_)
4501
0
                    .tag("packed_file_path", packed_file_path)
4502
0
                    .tag("attempt", attempt);
4503
0
            return -1;
4504
0
        }
4505
4506
8
        if (!(latest_info.state() == cloud::PackedFileInfoPB::RECYCLING &&
4507
8
              latest_info.ref_cnt() == 0)) {
4508
0
            LOG_INFO("packed file state changed before removal, skip deleting kv")
4509
0
                    .tag("instance_id", instance_id_)
4510
0
                    .tag("packed_file_path", packed_file_path)
4511
0
                    .tag("attempt", attempt);
4512
0
            return 0;
4513
0
        }
4514
4515
8
        del_txn->remove(packed_key);
4516
8
        err = del_txn->commit();
4517
8
        if (err == TxnErrorCode::TXN_OK) {
4518
8
            LOG_INFO("removed packed file metadata")
4519
8
                    .tag("instance_id", instance_id_)
4520
8
                    .tag("packed_file_path", packed_file_path);
4521
8
            return 0;
4522
8
        }
4523
0
        if (err == TxnErrorCode::TXN_CONFLICT) {
4524
0
            if (attempt >= max_retry_times) {
4525
0
                LOG_WARNING("failed to remove packed file kv due to conflict after max retry")
4526
0
                        .tag("instance_id", instance_id_)
4527
0
                        .tag("packed_file_path", packed_file_path)
4528
0
                        .tag("attempt", attempt);
4529
0
                return -1;
4530
0
            }
4531
0
            LOG_WARNING("failed to remove packed file kv due to conflict, retrying")
4532
0
                    .tag("instance_id", instance_id_)
4533
0
                    .tag("packed_file_path", packed_file_path)
4534
0
                    .tag("attempt", attempt);
4535
0
            sleep_for_packed_file_retry();
4536
0
            continue;
4537
0
        }
4538
0
        LOG_WARNING("failed to remove packed file kv")
4539
0
                .tag("instance_id", instance_id_)
4540
0
                .tag("packed_file_path", packed_file_path)
4541
0
                .tag("attempt", attempt)
4542
0
                .tag("err", err);
4543
0
        return -1;
4544
0
    }
4545
0
    return -1;
4546
8
}
4547
4548
int InstanceRecycler::delete_rowset_data(
4549
        const std::map<std::string, doris::RowsetMetaCloudPB>& rowsets, RowsetRecyclingState type,
4550
        RecyclerMetricsContext& metrics_context,
4551
96
        std::vector<std::vector<std::string>>* delete_bitmap_key_groups) {
4552
96
    int ret = 0;
4553
    // resource_id -> file_paths
4554
96
    std::map<std::string, std::vector<std::string>> resource_file_paths;
4555
    // (resource_id, tablet_id, rowset_id)
4556
96
    std::vector<std::tuple<std::string, int64_t, std::string>> rowsets_delete_by_prefix;
4557
96
    bool is_formal_rowset = (type == RowsetRecyclingState::FORMAL_ROWSET);
4558
4559
56.4k
    for (const auto& [_, rs] : rowsets) {
4560
        // we have to treat tmp rowset as "orphans" that may not related to any existing tablets
4561
        // due to aborted schema change.
4562
56.4k
        if (is_formal_rowset) {
4563
3.16k
            if (is_tablet_recycled(rs.tablet_id()) && rs.packed_slice_locations_size() == 0) {
4564
                // Tablet has been recycled and this rowset has no packed slices, so file data
4565
                // should already be gone; skip to avoid redundant deletes. Rowsets with packed
4566
                // slice info must still run to decrement packed file ref counts.
4567
0
                continue;
4568
0
            }
4569
3.16k
        }
4570
4571
56.4k
        int64_t num_segments = rs.num_segments();
4572
        // Check num_segments before accessor lookup, because empty rowsets
4573
        // (e.g. base compaction output of empty rowsets) may have no resource_id
4574
        // set. Skipping them early avoids a spurious "no such resource id" error
4575
        // that marks the entire batch as failed and prevents txn_remove from
4576
        // cleaning up recycle KV keys.
4577
56.4k
        if (num_segments <= 0) {
4578
0
            metrics_context.kv_recycled_bytes += rs.total_disk_size();
4579
0
            continue;
4580
0
        }
4581
4582
56.4k
        auto it = accessor_map_.find(rs.resource_id());
4583
        // possible if the accessor is not initilized correctly
4584
56.4k
        if (it == accessor_map_.end()) [[unlikely]] {
4585
2.00k
            LOG_WARNING("instance has no such resource id")
4586
2.00k
                    .tag("instance_id", instance_id_)
4587
2.00k
                    .tag("resource_id", rs.resource_id());
4588
2.00k
            ret = -1;
4589
2.00k
            continue;
4590
2.00k
        }
4591
4592
54.4k
        auto& file_paths = resource_file_paths[rs.resource_id()];
4593
54.4k
        const auto& rowset_id = rs.rowset_id_v2();
4594
54.4k
        int64_t tablet_id = rs.tablet_id();
4595
54.4k
        LOG_INFO("recycle rowset merge index size")
4596
54.4k
                .tag("instance_id", instance_id_)
4597
54.4k
                .tag("tablet_id", tablet_id)
4598
54.4k
                .tag("rowset_id", rowset_id)
4599
54.4k
                .tag("merge_index_size", rs.packed_slice_locations_size());
4600
54.4k
        if (decrement_packed_file_ref_counts(rs) != 0) {
4601
0
            ret = -1;
4602
0
            continue;
4603
0
        }
4604
4605
54.4k
        DeleteBitmapStorageType delete_bitmap_storage_type = DeleteBitmapStorageType::NOT_FOUND;
4606
54.4k
        std::vector<std::string> rowset_dbm_keys;
4607
54.4k
        if (decrement_delete_bitmap_packed_file_ref_counts(
4608
54.4k
                    tablet_id, rowset_id, &delete_bitmap_storage_type,
4609
54.4k
                    delete_bitmap_key_groups ? &rowset_dbm_keys : nullptr) != 0) {
4610
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
4611
0
                    .tag("instance_id", instance_id_)
4612
0
                    .tag("tablet_id", tablet_id)
4613
0
                    .tag("rowset_id", rowset_id);
4614
0
            ret = -1;
4615
0
            continue;
4616
0
        }
4617
54.4k
        if (!rowset_dbm_keys.empty() && delete_bitmap_key_groups) {
4618
1.55k
            delete_bitmap_key_groups->emplace_back(std::move(rowset_dbm_keys));
4619
1.55k
        }
4620
54.4k
        if (delete_bitmap_storage_type == DeleteBitmapStorageType::STANDALONE_FILE) {
4621
51.5k
            file_paths.push_back(delete_bitmap_path(tablet_id, rowset_id));
4622
51.5k
        }
4623
4624
        // Process inverted indexes
4625
54.4k
        std::vector<std::pair<int64_t, std::string>> index_ids;
4626
        // default format as v1.
4627
54.4k
        InvertedIndexStorageFormatPB index_format = rs.has_inverted_index_storage_format()
4628
54.4k
                                                            ? rs.inverted_index_storage_format()
4629
54.4k
                                                            : InvertedIndexStorageFormatPB::V1;
4630
54.4k
        int inverted_index_get_ret = 0;
4631
54.4k
        if (rs.has_tablet_schema()) {
4632
53.5k
            for (const auto& index : rs.tablet_schema().index()) {
4633
53.5k
                if (index.has_index_type() && index.index_type() == IndexType::INVERTED) {
4634
53.5k
                    index_ids.emplace_back(index.index_id(), index.index_suffix_name());
4635
53.5k
                }
4636
53.5k
            }
4637
26.8k
            if (!rs.has_inverted_index_storage_format() &&
4638
26.8k
                rs.tablet_schema().has_inverted_index_storage_format()) {
4639
26.5k
                index_format = rs.tablet_schema().inverted_index_storage_format();
4640
26.5k
            }
4641
27.5k
        } else {
4642
27.6k
            if (!rs.has_index_id() || !rs.has_schema_version()) {
4643
0
                LOG(WARNING) << "rowset must have either schema or schema_version and index_id, "
4644
0
                                "instance_id="
4645
0
                             << instance_id_ << " tablet_id=" << tablet_id
4646
0
                             << " rowset_id=" << rowset_id;
4647
0
                ret = -1;
4648
0
                continue;
4649
0
            }
4650
27.5k
            InvertedIndexInfo index_info;
4651
27.5k
            inverted_index_get_ret =
4652
27.5k
                    inverted_index_id_cache_->get(rs.index_id(), rs.schema_version(), index_info);
4653
27.5k
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.tmp_rowset",
4654
27.5k
                                     &inverted_index_get_ret);
4655
27.5k
            if (inverted_index_get_ret == 0) {
4656
27.0k
                if (!rs.has_inverted_index_storage_format()) {
4657
27.0k
                    index_format = index_info.first;
4658
27.0k
                }
4659
27.0k
                index_ids = index_info.second;
4660
27.0k
            } else if (inverted_index_get_ret == 1) {
4661
                // 1. Schema kv not found means tablet has been recycled
4662
                // Maybe some tablet recycle failed by some bugs
4663
                // We need to delete again to double check
4664
                // 2. Ensure this operation only deletes tablets and does not perform any operations on indexes,
4665
                // because we are uncertain about the inverted index information.
4666
                // If there are inverted indexes, some data might not be deleted,
4667
                // but this is acceptable as we have made our best effort to delete the data.
4668
507
                LOG_INFO(
4669
507
                        "delete rowset data schema kv not found, need to delete again to "
4670
507
                        "double "
4671
507
                        "check")
4672
507
                        .tag("instance_id", instance_id_)
4673
507
                        .tag("tablet_id", tablet_id)
4674
507
                        .tag("rowset", rs.ShortDebugString());
4675
                // Currently index_ids is guaranteed to be empty,
4676
                // but we clear it again here as a safeguard against future code changes
4677
                // that might cause index_ids to no longer be empty
4678
507
                index_format = InvertedIndexStorageFormatPB::V2;
4679
507
                index_ids.clear();
4680
18.4E
            } else {
4681
18.4E
                LOG(WARNING) << "failed to get schema kv for rowset, instance_id=" << instance_id_
4682
18.4E
                             << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4683
18.4E
                ret = -1;
4684
18.4E
                continue;
4685
18.4E
            }
4686
27.5k
        }
4687
54.4k
        if (rs.rowset_state() == RowsetStatePB::BEGIN_PARTIAL_UPDATE) {
4688
            // if rowset state is RowsetStatePB::BEGIN_PARTIAL_UPDATE, the number of segments data
4689
            // may be larger than num_segments field in RowsetMeta, so we need to delete the rowset's data by prefix
4690
5
            rowsets_delete_by_prefix.emplace_back(rs.resource_id(), tablet_id, rs.rowset_id_v2());
4691
5
            continue;
4692
5
        }
4693
325k
        for (int64_t i = 0; i < num_segments; ++i) {
4694
270k
            auto segment_id = rowset_segment_id(rs, i);
4695
270k
            add_file_to_delete_if_not_packed(rs, segment_path(tablet_id, rowset_id, segment_id),
4696
270k
                                             &file_paths);
4697
270k
            if (index_format == InvertedIndexStorageFormatPB::V1) {
4698
537k
                for (const auto& index_id : index_ids) {
4699
537k
                    add_file_to_delete_if_not_packed(
4700
537k
                            rs,
4701
537k
                            inverted_index_path_v1(tablet_id, rowset_id, segment_id, index_id.first,
4702
537k
                                                   index_id.second),
4703
537k
                            &file_paths);
4704
537k
                }
4705
268k
            } else if (!index_ids.empty() || inverted_index_get_ret == 1) {
4706
                // try to recycle inverted index v2 when get_ret == 1
4707
                // we treat schema not found as if it has a v2 format inverted index
4708
                // to reduce chance of data leakage
4709
2.51k
                if (inverted_index_get_ret == 1) {
4710
2.50k
                    LOG_INFO("delete rowset data schema kv not found, try to delete index file")
4711
2.50k
                            .tag("instance_id", instance_id_)
4712
2.50k
                            .tag("inverted index v2 path",
4713
2.50k
                                 inverted_index_path_v2(tablet_id, rowset_id, segment_id));
4714
2.50k
                }
4715
2.51k
                add_file_to_delete_if_not_packed(
4716
2.51k
                        rs, inverted_index_path_v2(tablet_id, rowset_id, segment_id), &file_paths);
4717
2.51k
            }
4718
270k
        }
4719
54.4k
    }
4720
4721
96
    SyncExecutor<int> concurrent_delete_executor(_thread_pool_group.s3_producer_pool,
4722
96
                                                 "delete_rowset_data",
4723
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
4723
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
4723
56
                                                 [](const int& ret) { return ret != 0; });
4724
96
    for (auto& [resource_id, file_paths] : resource_file_paths) {
4725
57
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4726
57
            DCHECK(accessor_map_.count(*rid))
4727
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4728
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4729
57
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4730
57
                                     &accessor_map_);
4731
57
            if (!accessor_map_.contains(*rid)) {
4732
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4733
0
                        .tag("resource_id", resource_id)
4734
0
                        .tag("instance_id", instance_id_);
4735
0
                return -1;
4736
0
            }
4737
57
            auto& accessor = accessor_map_[*rid];
4738
57
            int ret = accessor->delete_files(*paths);
4739
57
            if (!ret) {
4740
                // deduplication of different files with the same rowset id
4741
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4742
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4743
57
                std::set<std::string> deleted_rowset_id;
4744
4745
57
                std::for_each(paths->begin(), paths->end(),
4746
57
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4747
863k
                               this](const std::string& path) {
4748
863k
                                  std::vector<std::string> str;
4749
863k
                                  butil::SplitString(path, '/', &str);
4750
863k
                                  std::string rowset_id;
4751
863k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4752
860k
                                      rowset_id = str.back().substr(0, pos);
4753
860k
                                  } else {
4754
3.07k
                                      if (path.find("packed_file/") != std::string::npos) {
4755
0
                                          return; // packed files do not have rowset_id encoded
4756
0
                                      }
4757
3.07k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4758
3.07k
                                      return;
4759
3.07k
                                  }
4760
860k
                                  auto rs_meta = rowsets.find(rowset_id);
4761
860k
                                  if (rs_meta != rowsets.end() &&
4762
860k
                                      !deleted_rowset_id.contains(rowset_id)) {
4763
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4764
54.4k
                                      metrics_context.kv_recycled_bytes +=
4765
54.4k
                                              rs_meta->second.total_disk_size();
4766
54.4k
                                      segment_metrics_context_.kv_recycled_num +=
4767
54.4k
                                              rs_meta->second.num_segments();
4768
54.4k
                                      segment_metrics_context_.kv_recycled_bytes +=
4769
54.4k
                                              rs_meta->second.total_disk_size();
4770
54.4k
                                  }
4771
860k
                              });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEvENKUlRSD_E_clEST_
Line
Count
Source
4747
7
                               this](const std::string& path) {
4748
7
                                  std::vector<std::string> str;
4749
7
                                  butil::SplitString(path, '/', &str);
4750
7
                                  std::string rowset_id;
4751
7
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4752
7
                                      rowset_id = str.back().substr(0, pos);
4753
7
                                  } else {
4754
0
                                      if (path.find("packed_file/") != std::string::npos) {
4755
0
                                          return; // packed files do not have rowset_id encoded
4756
0
                                      }
4757
0
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4758
0
                                      return;
4759
0
                                  }
4760
7
                                  auto rs_meta = rowsets.find(rowset_id);
4761
7
                                  if (rs_meta != rowsets.end() &&
4762
7
                                      !deleted_rowset_id.contains(rowset_id)) {
4763
7
                                      deleted_rowset_id.emplace(rowset_id);
4764
7
                                      metrics_context.kv_recycled_bytes +=
4765
7
                                              rs_meta->second.total_disk_size();
4766
7
                                      segment_metrics_context_.kv_recycled_num +=
4767
7
                                              rs_meta->second.num_segments();
4768
7
                                      segment_metrics_context_.kv_recycled_bytes +=
4769
7
                                              rs_meta->second.total_disk_size();
4770
7
                                  }
4771
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
4747
863k
                               this](const std::string& path) {
4748
863k
                                  std::vector<std::string> str;
4749
863k
                                  butil::SplitString(path, '/', &str);
4750
863k
                                  std::string rowset_id;
4751
863k
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4752
860k
                                      rowset_id = str.back().substr(0, pos);
4753
860k
                                  } else {
4754
3.07k
                                      if (path.find("packed_file/") != std::string::npos) {
4755
0
                                          return; // packed files do not have rowset_id encoded
4756
0
                                      }
4757
3.07k
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4758
3.07k
                                      return;
4759
3.07k
                                  }
4760
860k
                                  auto rs_meta = rowsets.find(rowset_id);
4761
860k
                                  if (rs_meta != rowsets.end() &&
4762
860k
                                      !deleted_rowset_id.contains(rowset_id)) {
4763
54.4k
                                      deleted_rowset_id.emplace(rowset_id);
4764
54.4k
                                      metrics_context.kv_recycled_bytes +=
4765
54.4k
                                              rs_meta->second.total_disk_size();
4766
54.4k
                                      segment_metrics_context_.kv_recycled_num +=
4767
54.4k
                                              rs_meta->second.num_segments();
4768
54.4k
                                      segment_metrics_context_.kv_recycled_bytes +=
4769
54.4k
                                              rs_meta->second.total_disk_size();
4770
54.4k
                                  }
4771
860k
                              });
4772
57
            }
4773
57
            return ret;
4774
57
        });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4725
6
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4726
6
            DCHECK(accessor_map_.count(*rid))
4727
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4728
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4729
6
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4730
6
                                     &accessor_map_);
4731
6
            if (!accessor_map_.contains(*rid)) {
4732
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4733
0
                        .tag("resource_id", resource_id)
4734
0
                        .tag("instance_id", instance_id_);
4735
0
                return -1;
4736
0
            }
4737
6
            auto& accessor = accessor_map_[*rid];
4738
6
            int ret = accessor->delete_files(*paths);
4739
6
            if (!ret) {
4740
                // deduplication of different files with the same rowset id
4741
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4742
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4743
6
                std::set<std::string> deleted_rowset_id;
4744
4745
6
                std::for_each(paths->begin(), paths->end(),
4746
6
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4747
6
                               this](const std::string& path) {
4748
6
                                  std::vector<std::string> str;
4749
6
                                  butil::SplitString(path, '/', &str);
4750
6
                                  std::string rowset_id;
4751
6
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4752
6
                                      rowset_id = str.back().substr(0, pos);
4753
6
                                  } else {
4754
6
                                      if (path.find("packed_file/") != std::string::npos) {
4755
6
                                          return; // packed files do not have rowset_id encoded
4756
6
                                      }
4757
6
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4758
6
                                      return;
4759
6
                                  }
4760
6
                                  auto rs_meta = rowsets.find(rowset_id);
4761
6
                                  if (rs_meta != rowsets.end() &&
4762
6
                                      !deleted_rowset_id.contains(rowset_id)) {
4763
6
                                      deleted_rowset_id.emplace(rowset_id);
4764
6
                                      metrics_context.kv_recycled_bytes +=
4765
6
                                              rs_meta->second.total_disk_size();
4766
6
                                      segment_metrics_context_.kv_recycled_num +=
4767
6
                                              rs_meta->second.num_segments();
4768
6
                                      segment_metrics_context_.kv_recycled_bytes +=
4769
6
                                              rs_meta->second.total_disk_size();
4770
6
                                  }
4771
6
                              });
4772
6
            }
4773
6
            return ret;
4774
6
        });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler18delete_rowset_dataERKSt3mapINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_17RowsetMetaCloudPBESt4lessIS8_ESaISt4pairIKS8_S9_EEENS0_20RowsetRecyclingStateERNS0_22RecyclerMetricsContextEPSt6vectorISM_IS8_SaIS8_EESaISO_EEENK3$_1clEv
Line
Count
Source
4725
51
        concurrent_delete_executor.add([&, rid = &resource_id, paths = &file_paths]() -> int {
4726
51
            DCHECK(accessor_map_.count(*rid))
4727
0
                    << "uninitilized accessor, instance_id=" << instance_id_
4728
0
                    << " resource_id=" << resource_id << " path[0]=" << (*paths)[0];
4729
51
            TEST_SYNC_POINT_CALLBACK("InstanceRecycler::delete_rowset_data.no_resource_id",
4730
51
                                     &accessor_map_);
4731
51
            if (!accessor_map_.contains(*rid)) {
4732
0
                LOG_WARNING("delete rowset data accessor_map_ does not contains resouce id")
4733
0
                        .tag("resource_id", resource_id)
4734
0
                        .tag("instance_id", instance_id_);
4735
0
                return -1;
4736
0
            }
4737
51
            auto& accessor = accessor_map_[*rid];
4738
51
            int ret = accessor->delete_files(*paths);
4739
51
            if (!ret) {
4740
                // deduplication of different files with the same rowset id
4741
                // 020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.dat
4742
                //020000000000007fd045a62bc87a6587dd7ac274aa36e5a9_0.idx
4743
51
                std::set<std::string> deleted_rowset_id;
4744
4745
51
                std::for_each(paths->begin(), paths->end(),
4746
51
                              [&metrics_context, &rowsets, &deleted_rowset_id,
4747
51
                               this](const std::string& path) {
4748
51
                                  std::vector<std::string> str;
4749
51
                                  butil::SplitString(path, '/', &str);
4750
51
                                  std::string rowset_id;
4751
51
                                  if (auto pos = str.back().find('_'); pos != std::string::npos) {
4752
51
                                      rowset_id = str.back().substr(0, pos);
4753
51
                                  } else {
4754
51
                                      if (path.find("packed_file/") != std::string::npos) {
4755
51
                                          return; // packed files do not have rowset_id encoded
4756
51
                                      }
4757
51
                                      LOG(WARNING) << "failed to parse rowset_id, path=" << path;
4758
51
                                      return;
4759
51
                                  }
4760
51
                                  auto rs_meta = rowsets.find(rowset_id);
4761
51
                                  if (rs_meta != rowsets.end() &&
4762
51
                                      !deleted_rowset_id.contains(rowset_id)) {
4763
51
                                      deleted_rowset_id.emplace(rowset_id);
4764
51
                                      metrics_context.kv_recycled_bytes +=
4765
51
                                              rs_meta->second.total_disk_size();
4766
51
                                      segment_metrics_context_.kv_recycled_num +=
4767
51
                                              rs_meta->second.num_segments();
4768
51
                                      segment_metrics_context_.kv_recycled_bytes +=
4769
51
                                              rs_meta->second.total_disk_size();
4770
51
                                  }
4771
51
                              });
4772
51
            }
4773
51
            return ret;
4774
51
        });
4775
57
    }
4776
96
    for (const auto& [resource_id, tablet_id, rowset_id] : rowsets_delete_by_prefix) {
4777
5
        LOG_INFO(
4778
5
                "delete rowset {} by prefix because it's in BEGIN_PARTIAL_UPDATE state, "
4779
5
                "resource_id={}, tablet_id={}, instance_id={}, task_type={}",
4780
5
                rowset_id, resource_id, tablet_id, instance_id_, metrics_context.operation_type);
4781
5
        concurrent_delete_executor.add([&]() -> int {
4782
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4783
5
            if (!ret) {
4784
5
                auto rs = rowsets.at(rowset_id);
4785
5
                metrics_context.kv_recycled_bytes += rs.total_disk_size();
4786
5
                segment_metrics_context_.kv_recycled_bytes += rs.total_disk_size();
4787
5
                segment_metrics_context_.kv_recycled_num += rs.num_segments();
4788
5
            }
4789
5
            return ret;
4790
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
4781
5
        concurrent_delete_executor.add([&]() -> int {
4782
5
            int ret = delete_rowset_data(resource_id, tablet_id, rowset_id);
4783
5
            if (!ret) {
4784
5
                auto rs = rowsets.at(rowset_id);
4785
5
                metrics_context.kv_recycled_bytes += rs.total_disk_size();
4786
5
                segment_metrics_context_.kv_recycled_bytes += rs.total_disk_size();
4787
5
                segment_metrics_context_.kv_recycled_num += rs.num_segments();
4788
5
            }
4789
5
            return ret;
4790
5
        });
4791
5
    }
4792
4793
96
    bool finished = true;
4794
96
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
4795
96
    for (int r : rets) {
4796
62
        if (r != 0) {
4797
0
            ret = -1;
4798
0
            break;
4799
0
        }
4800
62
    }
4801
96
    ret = finished ? ret : -1;
4802
96
    return ret;
4803
96
}
4804
4805
int InstanceRecycler::delete_rowset_data(const std::string& resource_id, int64_t tablet_id,
4806
3.57k
                                         const std::string& rowset_id) {
4807
3.57k
    auto it = accessor_map_.find(resource_id);
4808
3.57k
    if (it == accessor_map_.end()) {
4809
400
        LOG_WARNING("instance has no such resource id")
4810
400
                .tag("instance_id", instance_id_)
4811
400
                .tag("resource_id", resource_id)
4812
400
                .tag("tablet_id", tablet_id)
4813
400
                .tag("rowset_id", rowset_id);
4814
400
        return -1;
4815
400
    }
4816
3.17k
    auto& accessor = it->second;
4817
3.17k
    return accessor->delete_prefix(rowset_path_prefix(tablet_id, rowset_id));
4818
3.57k
}
4819
4820
55.6k
bool InstanceRecycler::is_tablet_recycled(int64_t tablet_id) {
4821
55.6k
    std::lock_guard lock(recycled_tablets_mtx_);
4822
55.6k
    return recycled_tablets_.contains(tablet_id);
4823
55.6k
}
4824
4825
int InstanceRecycler::should_delete_versioned_delete_bitmap_kvs(int64_t partition_id,
4826
52.4k
                                                                int64_t tablet_id) {
4827
52.4k
    bool is_mow = true;
4828
52.4k
    if (partition_id != -1) {
4829
52.2k
        std::lock_guard lock(partition_mow_cache_mutex);
4830
52.2k
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4831
            // cache hit
4832
1
            is_mow = it->second;
4833
1
            return is_mow ? 1 : 0;
4834
1
        }
4835
52.2k
    }
4836
4837
52.4k
    TabletIndexPB tablet_index;
4838
52.4k
    int ret = get_tablet_idx(txn_kv_.get(), instance_id_, tablet_id, tablet_index);
4839
52.4k
    if (ret == 1) {
4840
        // maybe recycled
4841
52.4k
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4842
52.4k
    }
4843
23
    if (ret != 0) {
4844
0
        LOG(WARNING) << "failed to get tablet index, instance_id=" << instance_id_
4845
0
                     << ", tablet_id=" << tablet_id;
4846
0
        return ret;
4847
0
    }
4848
4849
    // Legacy RecycleRowsetPB without type does not carry a partition ID. Check the cache after
4850
    // obtaining its partition ID from the tablet index.
4851
23
    if (partition_id == -1) {
4852
0
        partition_id = tablet_index.partition_id();
4853
0
        std::lock_guard lock(partition_mow_cache_mutex);
4854
0
        if (auto it = partition_mow_cache.find(partition_id); it != partition_mow_cache.end()) {
4855
0
            is_mow = it->second;
4856
0
            return is_mow ? 1 : 0;
4857
0
        }
4858
0
    }
4859
4860
23
    std::string tablet_meta_key =
4861
23
            meta_tablet_key({instance_id_, tablet_index.table_id(), tablet_index.index_id(),
4862
23
                             partition_id, tablet_id});
4863
23
    std::string tablet_meta_value;
4864
23
    ret = txn_get(txn_kv_.get(), tablet_meta_key, tablet_meta_value);
4865
23
    if (ret == 1) {
4866
        // maybe recycled
4867
10
        return is_tablet_recycled(tablet_id) ? 0 : 1;
4868
10
    }
4869
13
    if (ret != 0) {
4870
0
        LOG(WARNING) << "failed to get tablet meta, instance_id=" << instance_id_
4871
0
                     << ", tablet_id=" << tablet_id;
4872
0
        return ret;
4873
0
    }
4874
4875
13
    TabletMetaCloudPB tablet_meta;
4876
13
    if (!tablet_meta.ParseFromString(tablet_meta_value)) {
4877
0
        LOG(WARNING) << "failed to parse tablet meta, instance_id=" << instance_id_
4878
0
                     << ", tablet_id=" << tablet_id;
4879
0
        return -1;
4880
0
    }
4881
    // The row-binlog companion of a MoW data tablet stores versioned delete bitmaps copied from
4882
    // that tablet, but its own MoW flag is deliberately false. Clean its DBMs without caching that
4883
    // false value as the MoW state of the whole partition.
4884
    // Rule: boolean enableUniqueKeyMergeOnWrite = !isRowBinlogIndex && tbl.getEnableUniqueKeyMergeOnWrite();
4885
13
    if (tablet_meta.tablet_role() == TabletRolePB::TABLET_ROLE_ROW_BINLOG) {
4886
1
        return 1;
4887
1
    }
4888
12
    bool tablet_is_mow = tablet_meta.enable_unique_key_merge_on_write();
4889
12
    std::lock_guard lock(partition_mow_cache_mutex);
4890
12
    auto [it, _] = partition_mow_cache.emplace(partition_id, tablet_is_mow);
4891
12
    return it->second ? 1 : 0;
4892
13
}
4893
4894
int InstanceRecycler::delete_versioned_delete_bitmap_kvs(int64_t partition_id, int64_t tablet_id,
4895
52.4k
                                                         const std::string& rowset_id) {
4896
52.4k
    int ret = should_delete_versioned_delete_bitmap_kvs(partition_id, tablet_id);
4897
52.4k
    if (ret <= 0) {
4898
1.00k
        return ret;
4899
1.00k
    }
4900
4901
51.4k
    std::string dbm_start_key =
4902
51.4k
            versioned::meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id});
4903
51.4k
    std::string dbm_end_key = dbm_start_key;
4904
51.4k
    encode_int64(INT64_MAX, &dbm_end_key);
4905
51.4k
    ret = txn_remove(txn_kv_.get(), dbm_start_key, dbm_end_key);
4906
51.4k
    if (ret != 0) {
4907
0
        LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id=" << instance_id_
4908
0
                     << " partition_id=" << partition_id << " tablet_id=" << tablet_id
4909
0
                     << " rowset_id=" << rowset_id;
4910
0
    }
4911
51.4k
    return ret;
4912
52.4k
}
4913
4914
51.2k
int InstanceRecycler::delete_delete_bitmap_kvs(int64_t tablet_id, const std::string& rowset_id) {
4915
51.2k
    std::string delete_bitmap_start =
4916
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
4917
51.2k
    std::string delete_bitmap_end =
4918
51.2k
            meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, INT64_MAX, INT64_MAX});
4919
51.2k
    int ret = txn_remove(txn_kv_.get(), delete_bitmap_start, delete_bitmap_end);
4920
51.2k
    if (ret != 0) {
4921
0
        LOG(WARNING) << "failed to delete delete bitmap kv, instance_id=" << instance_id_
4922
0
                     << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id;
4923
0
    }
4924
51.2k
    return ret;
4925
51.2k
}
4926
4927
4
bool InstanceRecycler::decode_packed_file_key(std::string_view key, std::string* packed_path) {
4928
4
    if (key.empty()) {
4929
0
        return false;
4930
0
    }
4931
4
    std::string_view key_view = key;
4932
4
    key_view.remove_prefix(1); // remove keyspace prefix
4933
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> decoded;
4934
4
    if (decode_key(&key_view, &decoded) != 0) {
4935
0
        return false;
4936
0
    }
4937
4
    if (decoded.size() < 4) {
4938
0
        return false;
4939
0
    }
4940
4
    try {
4941
4
        *packed_path = std::get<std::string>(std::get<0>(decoded.back()));
4942
4
    } catch (const std::bad_variant_access&) {
4943
0
        return false;
4944
0
    }
4945
4
    return true;
4946
4
}
4947
4948
14
int InstanceRecycler::recycle_packed_files() {
4949
14
    const std::string task_name = "recycle_packed_files";
4950
14
    auto start_tp = steady_clock::now();
4951
14
    int64_t start_time = duration_cast<seconds>(start_tp.time_since_epoch()).count();
4952
14
    int ret = 0;
4953
14
    PackedFileRecycleStats stats;
4954
4955
14
    register_recycle_task(task_name, start_time);
4956
14
    DORIS_CLOUD_DEFER {
4957
14
        unregister_recycle_task(task_name);
4958
14
        int64_t cost =
4959
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4960
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4961
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4962
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4963
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4964
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4965
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4966
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4967
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4968
14
                                                             stats.bytes_object_deleted);
4969
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4970
14
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4971
14
                .tag("instance_id", instance_id_)
4972
14
                .tag("num_scanned", stats.num_scanned)
4973
14
                .tag("num_corrected", stats.num_corrected)
4974
14
                .tag("num_deleted", stats.num_deleted)
4975
14
                .tag("num_failed", stats.num_failed)
4976
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4977
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4978
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4979
14
                .tag("bytes_deleted", stats.bytes_deleted)
4980
14
                .tag("ret", ret);
4981
14
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_packed_filesEvENK3$_0clEv
Line
Count
Source
4956
14
    DORIS_CLOUD_DEFER {
4957
14
        unregister_recycle_task(task_name);
4958
14
        int64_t cost =
4959
14
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
4960
14
        int64_t cost_ms = duration_cast<milliseconds>(steady_clock::now() - start_tp).count();
4961
14
        g_bvar_recycler_packed_file_recycled_kv_num.put(instance_id_, stats.num_deleted);
4962
14
        g_bvar_recycler_packed_file_recycled_kv_bytes.put(instance_id_, stats.bytes_deleted);
4963
14
        g_bvar_recycler_packed_file_recycle_cost_ms.put(instance_id_, cost_ms);
4964
14
        g_bvar_recycler_packed_file_scanned_kv_num.put(instance_id_, stats.num_scanned);
4965
14
        g_bvar_recycler_packed_file_corrected_kv_num.put(instance_id_, stats.num_corrected);
4966
14
        g_bvar_recycler_packed_file_recycled_object_num.put(instance_id_, stats.num_object_deleted);
4967
14
        g_bvar_recycler_packed_file_bytes_object_deleted.put(instance_id_,
4968
14
                                                             stats.bytes_object_deleted);
4969
14
        g_bvar_recycler_packed_file_rowset_scanned_num.put(instance_id_, stats.rowset_scan_count);
4970
        LOG_INFO("recycle packed files finished, cost={}s", cost)
4971
14
                .tag("instance_id", instance_id_)
4972
14
                .tag("num_scanned", stats.num_scanned)
4973
14
                .tag("num_corrected", stats.num_corrected)
4974
14
                .tag("num_deleted", stats.num_deleted)
4975
14
                .tag("num_failed", stats.num_failed)
4976
14
                .tag("num_objects_deleted", stats.num_object_deleted)
4977
14
                .tag("bytes_object_deleted", stats.bytes_object_deleted)
4978
14
                .tag("rowset_scan_count", stats.rowset_scan_count)
4979
14
                .tag("bytes_deleted", stats.bytes_deleted)
4980
14
                .tag("ret", ret);
4981
14
    };
4982
4983
14
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4984
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4985
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4986
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
4983
4
    auto recycle_func = [this, &stats, &ret](auto&& key, auto&& value) {
4984
4
        return handle_packed_file_kv(std::forward<decltype(key)>(key),
4985
4
                                     std::forward<decltype(value)>(value), &stats, &ret);
4986
4
    };
4987
4988
14
    LOG_INFO("begin to recycle packed file").tag("instance_id", instance_id_);
4989
4990
14
    std::string begin = packed_file_key({instance_id_, ""});
4991
14
    std::string end = packed_file_key({instance_id_, "\xff"});
4992
14
    if (scan_and_recycle(begin, end, recycle_func) != 0) {
4993
0
        ret = -1;
4994
0
    }
4995
4996
14
    return ret;
4997
14
}
4998
4999
4.26k
int InstanceRecycler::recycle_tablet(int64_t tablet_id, RecyclerMetricsContext& metrics_context) {
5000
4.26k
    LOG_INFO("begin to recycle rowsets in a dropped tablet")
5001
4.26k
            .tag("instance_id", instance_id_)
5002
4.26k
            .tag("tablet_id", tablet_id);
5003
5004
4.26k
    if (should_recycle_versioned_keys()) {
5005
14
        int ret = recycle_versioned_tablet(tablet_id, metrics_context);
5006
14
        if (ret != 0) {
5007
0
            return ret;
5008
0
        }
5009
        // Continue to recycle non-versioned rowsets, if multi-version is set to DISABLED
5010
        // during the recycle_versioned_tablet process.
5011
        //
5012
        // .. And remove restore job rowsets of this tablet too
5013
14
    }
5014
5015
4.26k
    int ret = 0;
5016
4.26k
    auto start_time = steady_clock::now();
5017
5018
4.26k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5019
5020
    // collect resource ids
5021
260
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5022
260
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5023
260
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5024
260
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5025
260
    std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
5026
260
    std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
5027
5028
260
    std::set<std::string> resource_ids;
5029
260
    int64_t recycle_rowsets_number = 0;
5030
260
    int64_t recycle_segments_number = 0;
5031
260
    int64_t recycle_rowsets_data_size = 0;
5032
260
    int64_t recycle_rowsets_index_size = 0;
5033
260
    int64_t recycle_restore_job_rowsets_number = 0;
5034
260
    int64_t recycle_restore_job_segments_number = 0;
5035
260
    int64_t recycle_restore_job_rowsets_data_size = 0;
5036
260
    int64_t recycle_restore_job_rowsets_index_size = 0;
5037
260
    int64_t max_rowset_version = 0;
5038
260
    int64_t min_rowset_creation_time = INT64_MAX;
5039
260
    int64_t max_rowset_creation_time = 0;
5040
260
    int64_t min_rowset_expiration_time = INT64_MAX;
5041
260
    int64_t max_rowset_expiration_time = 0;
5042
5043
260
    DORIS_CLOUD_DEFER {
5044
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5045
260
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5046
260
                .tag("instance_id", instance_id_)
5047
260
                .tag("tablet_id", tablet_id)
5048
260
                .tag("recycle rowsets number", recycle_rowsets_number)
5049
260
                .tag("recycle segments number", recycle_segments_number)
5050
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5051
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5052
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5053
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5054
260
                .tag("all restore job rowsets recycle data size",
5055
260
                     recycle_restore_job_rowsets_data_size)
5056
260
                .tag("all restore job rowsets recycle index size",
5057
260
                     recycle_restore_job_rowsets_index_size)
5058
260
                .tag("max rowset version", max_rowset_version)
5059
260
                .tag("min rowset creation time", min_rowset_creation_time)
5060
260
                .tag("max rowset creation time", max_rowset_creation_time)
5061
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5062
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5063
260
                .tag("task type", metrics_context.operation_type)
5064
260
                .tag("ret", ret);
5065
260
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5043
260
    DORIS_CLOUD_DEFER {
5044
260
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5045
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5046
260
                .tag("instance_id", instance_id_)
5047
260
                .tag("tablet_id", tablet_id)
5048
260
                .tag("recycle rowsets number", recycle_rowsets_number)
5049
260
                .tag("recycle segments number", recycle_segments_number)
5050
260
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5051
260
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5052
260
                .tag("recycle restore job rowsets number", recycle_restore_job_rowsets_number)
5053
260
                .tag("recycle restore job segments number", recycle_restore_job_segments_number)
5054
260
                .tag("all restore job rowsets recycle data size",
5055
260
                     recycle_restore_job_rowsets_data_size)
5056
260
                .tag("all restore job rowsets recycle index size",
5057
260
                     recycle_restore_job_rowsets_index_size)
5058
260
                .tag("max rowset version", max_rowset_version)
5059
260
                .tag("min rowset creation time", min_rowset_creation_time)
5060
260
                .tag("max rowset creation time", max_rowset_creation_time)
5061
260
                .tag("min rowset expiration time", min_rowset_expiration_time)
5062
260
                .tag("max rowset expiration time", max_rowset_expiration_time)
5063
260
                .tag("task type", metrics_context.operation_type)
5064
260
                .tag("ret", ret);
5065
260
    };
5066
5067
260
    std::unique_ptr<Transaction> txn;
5068
260
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5069
0
        LOG_WARNING("failed to recycle tablet ")
5070
0
                .tag("tablet id", tablet_id)
5071
0
                .tag("instance_id", instance_id_)
5072
0
                .tag("reason", "failed to create txn");
5073
0
        ret = -1;
5074
0
    }
5075
260
    GetRowsetResponse resp;
5076
260
    std::string msg;
5077
260
    MetaServiceCode code = MetaServiceCode::OK;
5078
    // get rowsets in tablet
5079
260
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
5080
260
                        tablet_id, code, msg, &resp);
5081
260
    if (code != MetaServiceCode::OK) {
5082
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5083
0
                .tag("tablet id", tablet_id)
5084
0
                .tag("msg", msg)
5085
0
                .tag("code", code)
5086
0
                .tag("instance id", instance_id_);
5087
0
        ret = -1;
5088
0
    }
5089
260
    TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_tablet.create_rowset_meta", &resp);
5090
5091
2.55k
    for (const auto& rs_meta : resp.rowset_meta()) {
5092
2.55k
        if (!rs_meta.has_resource_id() || rs_meta.resource_id().empty()) {
5093
3
            if (rs_meta.num_segments() <= 0) {
5094
2
                LOG_INFO("rowset meta has no segments and no resource id, skip this rowset")
5095
2
                        .tag("rs_meta", rs_meta.ShortDebugString())
5096
2
                        .tag("instance_id", instance_id_)
5097
2
                        .tag("tablet_id", tablet_id);
5098
2
                recycle_rowsets_number += 1;
5099
2
                continue;
5100
2
            }
5101
1
            LOG_WARNING("rowset meta has a missing or empty resource id, impossible!")
5102
1
                    .tag("rs_meta", rs_meta.ShortDebugString())
5103
1
                    .tag("instance_id", instance_id_)
5104
1
                    .tag("tablet_id", tablet_id);
5105
1
            return -1;
5106
3
        }
5107
2.55k
        DCHECK(rs_meta.has_resource_id() && !rs_meta.resource_id().empty())
5108
0
                << "rs_meta" << rs_meta.ShortDebugString();
5109
2.55k
        auto it = accessor_map_.find(rs_meta.resource_id());
5110
        // possible if the accessor is not initilized correctly
5111
2.55k
        if (it == accessor_map_.end()) [[unlikely]] {
5112
1
            LOG_WARNING(
5113
1
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5114
1
                    "recycle process")
5115
1
                    .tag("tablet id", tablet_id)
5116
1
                    .tag("instance_id", instance_id_)
5117
1
                    .tag("resource_id", rs_meta.resource_id())
5118
1
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5119
1
            return -1;
5120
1
        }
5121
2.54k
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5122
0
            LOG_WARNING("failed to update packed file info when recycling tablet")
5123
0
                    .tag("instance_id", instance_id_)
5124
0
                    .tag("tablet_id", tablet_id)
5125
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5126
0
            return -1;
5127
0
        }
5128
2.54k
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5129
2.54k
                                                           nullptr) != 0) {
5130
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5131
0
                    .tag("instance_id", instance_id_)
5132
0
                    .tag("tablet_id", tablet_id)
5133
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5134
0
            return -1;
5135
0
        }
5136
2.54k
        recycle_rowsets_number += 1;
5137
2.54k
        recycle_segments_number += rs_meta.num_segments();
5138
2.54k
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5139
2.54k
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5140
2.54k
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5141
2.54k
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5142
2.54k
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5143
2.54k
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5144
2.54k
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5145
2.54k
        resource_ids.emplace(rs_meta.resource_id());
5146
2.54k
    }
5147
5148
    // get restore job rowset in tablet
5149
258
    std::vector<std::pair<std::string, doris::RowsetMetaCloudPB>> restore_job_rs_metas;
5150
258
    scan_restore_job_rowset(txn.get(), instance_id_, tablet_id, code, msg, &restore_job_rs_metas);
5151
258
    if (code != MetaServiceCode::OK) {
5152
0
        LOG_WARNING("scan restore job rowsets failed when recycle tablet")
5153
0
                .tag("tablet id", tablet_id)
5154
0
                .tag("msg", msg)
5155
0
                .tag("code", code)
5156
0
                .tag("instance id", instance_id_);
5157
0
        return -1;
5158
0
    }
5159
5160
258
    for (auto& [_, rs_meta] : restore_job_rs_metas) {
5161
0
        if (!rs_meta.has_resource_id()) {
5162
0
            LOG_WARNING("rowset meta does not have a resource id, impossible!")
5163
0
                    .tag("rs_meta", rs_meta.ShortDebugString())
5164
0
                    .tag("instance_id", instance_id_)
5165
0
                    .tag("tablet_id", tablet_id);
5166
0
            return -1;
5167
0
        }
5168
5169
0
        auto it = accessor_map_.find(rs_meta.resource_id());
5170
        // possible if the accessor is not initilized correctly
5171
0
        if (it == accessor_map_.end()) [[unlikely]] {
5172
0
            LOG_WARNING(
5173
0
                    "failed to find resource id when recycle tablet, skip this vault accessor "
5174
0
                    "recycle process")
5175
0
                    .tag("tablet id", tablet_id)
5176
0
                    .tag("instance_id", instance_id_)
5177
0
                    .tag("resource_id", rs_meta.resource_id())
5178
0
                    .tag("rowset meta pb", rs_meta.ShortDebugString());
5179
0
            return -1;
5180
0
        }
5181
0
        if (decrement_packed_file_ref_counts(rs_meta) != 0) {
5182
0
            LOG_WARNING("failed to update packed file info when recycling restore job rowset")
5183
0
                    .tag("instance_id", instance_id_)
5184
0
                    .tag("tablet_id", tablet_id)
5185
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5186
0
            return -1;
5187
0
        }
5188
0
        if (decrement_delete_bitmap_packed_file_ref_counts(tablet_id, rs_meta.rowset_id_v2(),
5189
0
                                                           nullptr) != 0) {
5190
0
            LOG_WARNING("failed to decrement delete bitmap packed file ref count")
5191
0
                    .tag("instance_id", instance_id_)
5192
0
                    .tag("tablet_id", tablet_id)
5193
0
                    .tag("rowset_id", rs_meta.rowset_id_v2());
5194
0
            return -1;
5195
0
        }
5196
0
        recycle_restore_job_rowsets_number += 1;
5197
0
        recycle_restore_job_segments_number += rs_meta.num_segments();
5198
0
        recycle_restore_job_rowsets_data_size += rs_meta.data_disk_size();
5199
0
        recycle_restore_job_rowsets_index_size += rs_meta.index_disk_size();
5200
0
        resource_ids.emplace(rs_meta.resource_id());
5201
0
    }
5202
5203
258
    LOG_INFO("recycle tablet start to delete object")
5204
258
            .tag("instance id", instance_id_)
5205
258
            .tag("tablet id", tablet_id)
5206
258
            .tag("recycle tablet resource ids are",
5207
258
                 std::accumulate(resource_ids.begin(), resource_ids.end(), std::string(),
5208
258
                                 [](std::string rs_id, const auto& it) {
5209
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5210
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
5208
217
                                 [](std::string rs_id, const auto& it) {
5209
217
                                     return rs_id.empty() ? it : rs_id + ", " + it;
5210
217
                                 }));
5211
5212
258
    SyncExecutor<std::pair<int, std::string>> concurrent_delete_executor(
5213
258
            _thread_pool_group.s3_producer_pool,
5214
258
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5215
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
5215
208
            [](const std::pair<int, std::string>& ret) { return ret.first != 0; });
5216
5217
    // delete all rowset data in this tablet
5218
    // ATTN: there may be data leak if not all accessor initilized successfully
5219
    //       partial data deleted if the tablet is stored cross-storage vault
5220
    //       vault id is not attached to TabletMeta...
5221
258
    for (const auto& resource_id : resource_ids) {
5222
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, resource_id, "submitted"}, 1);
5223
217
        concurrent_delete_executor.add(
5224
217
                [&, rs_id = resource_id,
5225
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5226
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5227
217
                    if (res != 0) {
5228
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5229
3
                                     << " path=" << accessor_ptr->uri()
5230
3
                                     << " task type=" << metrics_context.operation_type;
5231
3
                        return std::make_pair(-1, rs_id);
5232
3
                    }
5233
214
                    return std::make_pair(0, rs_id);
5234
217
                });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler14recycle_tabletElRNS0_22RecyclerMetricsContextEENK3$_3clB5cxx11Ev
Line
Count
Source
5225
217
                 accessor_ptr = accessor_map_[resource_id]]() -> decltype(auto) {
5226
217
                    int res = accessor_ptr->delete_directory(tablet_path_prefix(tablet_id));
5227
217
                    if (res != 0) {
5228
3
                        LOG(WARNING) << "failed to delete rowset data of tablet " << tablet_id
5229
3
                                     << " path=" << accessor_ptr->uri()
5230
3
                                     << " task type=" << metrics_context.operation_type;
5231
3
                        return std::make_pair(-1, rs_id);
5232
3
                    }
5233
214
                    return std::make_pair(0, rs_id);
5234
217
                });
5235
217
    }
5236
5237
258
    bool finished = true;
5238
258
    std::vector<std::pair<int, std::string>> rets = concurrent_delete_executor.when_all(&finished);
5239
258
    for (auto& r : rets) {
5240
217
        if (r.first != 0) {
5241
3
            g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "error"}, 1);
5242
3
            ret = -1;
5243
3
        }
5244
217
        g_bvar_recycler_vault_recycle_task_status.put({instance_id_, r.second, "completed"}, 1);
5245
217
    }
5246
258
    ret = finished ? ret : -1;
5247
5248
258
    if (ret != 0) { // failed recycle tablet data
5249
3
        LOG_WARNING("ret!=0")
5250
3
                .tag("finished", finished)
5251
3
                .tag("ret", ret)
5252
3
                .tag("instance_id", instance_id_)
5253
3
                .tag("tablet_id", tablet_id);
5254
3
        return ret;
5255
3
    }
5256
5257
255
    tablet_metrics_context_.kv_recycled_bytes +=
5258
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5259
255
    segment_metrics_context_.kv_recycled_bytes +=
5260
255
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5261
255
    metrics_context.kv_recycled_bytes += recycle_rowsets_data_size + recycle_rowsets_index_size;
5262
5263
255
    txn.reset();
5264
255
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5265
0
        LOG_WARNING("failed to recycle tablet ")
5266
0
                .tag("tablet id", tablet_id)
5267
0
                .tag("instance_id", instance_id_)
5268
0
                .tag("reason", "failed to create txn");
5269
0
        ret = -1;
5270
0
    }
5271
    // delete all rowset kv in this tablet
5272
255
    txn->remove(rs_key0, rs_key1);
5273
255
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5274
255
    txn->remove(restore_job_rs_key0, restore_job_rs_key1);
5275
5276
    // remove delete bitmap for MoW table
5277
255
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5278
255
    txn->remove(pending_key);
5279
255
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5280
255
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5281
255
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5282
5283
255
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5284
255
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5285
255
    txn->remove(dbm_start_key, dbm_end_key);
5286
255
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5287
255
              << " end=" << hex(dbm_end_key);
5288
5289
255
    TxnErrorCode err = txn->commit();
5290
255
    if (err != TxnErrorCode::TXN_OK) {
5291
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5292
0
        ret = -1;
5293
0
    }
5294
5295
255
    if (ret == 0) {
5296
        // All object files under tablet have been deleted
5297
255
        tablet_metrics_context_.kv_recycled_num += 1;
5298
255
        segment_metrics_context_.kv_recycled_num += recycle_segments_number;
5299
255
        std::lock_guard lock(recycled_tablets_mtx_);
5300
255
        recycled_tablets_.insert(tablet_id);
5301
255
    }
5302
5303
255
    return ret;
5304
258
}
5305
5306
int InstanceRecycler::recycle_versioned_tablet(int64_t tablet_id,
5307
14
                                               RecyclerMetricsContext& metrics_context) {
5308
14
    int ret = 0;
5309
14
    auto start_time = steady_clock::now();
5310
5311
14
    TEST_SYNC_POINT_RETURN_WITH_VALUE("recycle_tablet::begin", (int)0);
5312
5313
    // collect resource ids
5314
11
    std::string rs_key0 = meta_rowset_key({instance_id_, tablet_id, 0});
5315
11
    std::string rs_key1 = meta_rowset_key({instance_id_, tablet_id + 1, 0});
5316
11
    std::string recyc_rs_key0 = recycle_rowset_key({instance_id_, tablet_id, ""});
5317
11
    std::string recyc_rs_key1 = recycle_rowset_key({instance_id_, tablet_id + 1, ""});
5318
5319
11
    int64_t recycle_rowsets_number = 0;
5320
11
    int64_t recycle_segments_number = 0;
5321
11
    int64_t recycle_rowsets_data_size = 0;
5322
11
    int64_t recycle_rowsets_index_size = 0;
5323
11
    int64_t max_rowset_version = 0;
5324
11
    int64_t min_rowset_creation_time = INT64_MAX;
5325
11
    int64_t max_rowset_creation_time = 0;
5326
11
    int64_t min_rowset_expiration_time = INT64_MAX;
5327
11
    int64_t max_rowset_expiration_time = 0;
5328
5329
11
    DORIS_CLOUD_DEFER {
5330
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5331
11
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5332
11
                .tag("instance_id", instance_id_)
5333
11
                .tag("tablet_id", tablet_id)
5334
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5335
11
                .tag("recycle segments number", recycle_segments_number)
5336
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5337
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5338
11
                .tag("max rowset version", max_rowset_version)
5339
11
                .tag("min rowset creation time", min_rowset_creation_time)
5340
11
                .tag("max rowset creation time", max_rowset_creation_time)
5341
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5342
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5343
11
                .tag("ret", ret);
5344
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_0clEv
Line
Count
Source
5329
11
    DORIS_CLOUD_DEFER {
5330
11
        auto cost = duration<float>(steady_clock::now() - start_time).count();
5331
        LOG_INFO("recycle the rowsets of dropped tablet finished, cost={}s", cost)
5332
11
                .tag("instance_id", instance_id_)
5333
11
                .tag("tablet_id", tablet_id)
5334
11
                .tag("recycle rowsets number", recycle_rowsets_number)
5335
11
                .tag("recycle segments number", recycle_segments_number)
5336
11
                .tag("all rowsets recycle data size", recycle_rowsets_data_size)
5337
11
                .tag("all rowsets recycle index size", recycle_rowsets_index_size)
5338
11
                .tag("max rowset version", max_rowset_version)
5339
11
                .tag("min rowset creation time", min_rowset_creation_time)
5340
11
                .tag("max rowset creation time", max_rowset_creation_time)
5341
11
                .tag("min rowset expiration time", min_rowset_expiration_time)
5342
11
                .tag("max rowset expiration time", max_rowset_expiration_time)
5343
11
                .tag("ret", ret);
5344
11
    };
5345
5346
11
    std::unique_ptr<Transaction> txn;
5347
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5348
0
        LOG_WARNING("failed to recycle tablet ")
5349
0
                .tag("tablet id", tablet_id)
5350
0
                .tag("instance_id", instance_id_)
5351
0
                .tag("reason", "failed to create txn");
5352
0
        ret = -1;
5353
0
    }
5354
5355
    // Read the last version of load and compact rowsets, the previous rowsets will be recycled
5356
    // by the related operation logs.
5357
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> load_rowset_metas;
5358
11
    std::vector<std::pair<RowsetMetaCloudPB, Versionstamp>> compact_rowset_metas;
5359
11
    MetaReader meta_reader(instance_id_);
5360
11
    TxnErrorCode err = meta_reader.get_load_rowset_metas(txn.get(), tablet_id, &load_rowset_metas);
5361
11
    if (err == TxnErrorCode::TXN_OK) {
5362
11
        err = meta_reader.get_compact_rowset_metas(txn.get(), tablet_id, &compact_rowset_metas);
5363
11
    }
5364
11
    if (err != TxnErrorCode::TXN_OK) {
5365
0
        LOG_WARNING("failed to get rowsets of tablet when recycle tablet")
5366
0
                .tag("tablet id", tablet_id)
5367
0
                .tag("err", err)
5368
0
                .tag("instance id", instance_id_);
5369
0
        ret = -1;
5370
0
    }
5371
5372
11
    LOG_INFO("recycle versioned tablet get {} load rowsets and {} compact rowsets",
5373
11
             load_rowset_metas.size(), compact_rowset_metas.size())
5374
11
            .tag("instance_id", instance_id_)
5375
11
            .tag("tablet_id", tablet_id);
5376
5377
11
    SyncExecutor<int> concurrent_delete_executor(
5378
11
            _thread_pool_group.s3_producer_pool,
5379
11
            fmt::format("delete tablet {} s3 rowset", tablet_id),
5380
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
5381
5382
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5383
60
        recycle_rowsets_number += 1;
5384
60
        recycle_segments_number += rs_meta.num_segments();
5385
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5386
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5387
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5388
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5389
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5390
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5391
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5392
60
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEENK3$_4clERKNS_17RowsetMetaCloudPBE
Line
Count
Source
5382
60
    auto update_rowset_stats = [&](const RowsetMetaCloudPB& rs_meta) {
5383
60
        recycle_rowsets_number += 1;
5384
60
        recycle_segments_number += rs_meta.num_segments();
5385
60
        recycle_rowsets_data_size += rs_meta.data_disk_size();
5386
60
        recycle_rowsets_index_size += rs_meta.index_disk_size();
5387
60
        max_rowset_version = std::max(max_rowset_version, rs_meta.end_version());
5388
60
        min_rowset_creation_time = std::min(min_rowset_creation_time, rs_meta.creation_time());
5389
60
        max_rowset_creation_time = std::max(max_rowset_creation_time, rs_meta.creation_time());
5390
60
        min_rowset_expiration_time = std::min(min_rowset_expiration_time, rs_meta.txn_expiration());
5391
60
        max_rowset_expiration_time = std::max(max_rowset_expiration_time, rs_meta.txn_expiration());
5392
60
    };
5393
5394
11
    std::vector<RowsetDeleteTask> all_tasks;
5395
60
    for (const auto& [rs_meta, versionstamp] : load_rowset_metas) {
5396
60
        update_rowset_stats(rs_meta);
5397
        // Version 0-1 rowset has no resource_id and no actual data files,
5398
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5399
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5400
60
        RowsetDeleteTask task;
5401
60
        task.rowset_meta = rs_meta;
5402
60
        task.versioned_rowset_key =
5403
60
                versioned::meta_rowset_load_key({instance_id_, tablet_id, rs_meta.end_version()});
5404
60
        task.non_versioned_rowset_key =
5405
60
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5406
60
        task.versionstamp = versionstamp;
5407
60
        all_tasks.push_back(std::move(task));
5408
60
    }
5409
5410
11
    for (const auto& [rs_meta, versionstamp] : compact_rowset_metas) {
5411
0
        update_rowset_stats(rs_meta);
5412
        // Version 0-1 rowset has no resource_id and no actual data files,
5413
        // but still needs ref_count key cleanup, so we add it to all_tasks.
5414
        // It will be filtered out in Phase 2 when building rowsets_to_delete.
5415
0
        RowsetDeleteTask task;
5416
0
        task.rowset_meta = rs_meta;
5417
0
        task.versioned_rowset_key = versioned::meta_rowset_compact_key(
5418
0
                {instance_id_, tablet_id, rs_meta.end_version()});
5419
0
        task.non_versioned_rowset_key =
5420
0
                meta_rowset_key({instance_id_, tablet_id, rs_meta.end_version()});
5421
0
        task.versionstamp = versionstamp;
5422
0
        all_tasks.push_back(std::move(task));
5423
0
    }
5424
5425
11
    auto handle_recycle_rowset_kv = [&](std::string_view k, std::string_view v) {
5426
0
        RecycleRowsetPB recycle_rowset;
5427
0
        if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
5428
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5429
0
            return -1;
5430
0
        }
5431
0
        if (!recycle_rowset.has_type()) { // compatible with old version `RecycleRowsetPB`
5432
0
            if (!recycle_rowset.has_resource_id()) [[unlikely]] { // impossible
5433
                // in old version, keep this key-value pair and it needs to be checked manually
5434
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5435
0
                return -1;
5436
0
            }
5437
0
            if (recycle_rowset.resource_id().empty()) [[unlikely]] {
5438
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5439
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5440
0
                          << hex(k) << " value=" << proto_to_json(recycle_rowset);
5441
0
                return -1;
5442
0
            }
5443
            // decode rowset_id
5444
0
            auto k1 = k;
5445
0
            k1.remove_prefix(1);
5446
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5447
0
            decode_key(&k1, &out);
5448
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5449
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5450
0
            LOG_INFO("delete old-version rowset data")
5451
0
                    .tag("instance_id", instance_id_)
5452
0
                    .tag("tablet_id", tablet_id)
5453
0
                    .tag("rowset_id", rowset_id);
5454
5455
            // Old version RecycleRowsetPB lacks full rowset_meta info (num_segments, schema, etc.),
5456
            // so we must use prefix deletion directly instead of batch delete.
5457
0
            concurrent_delete_executor.add(
5458
0
                    [tablet_id, resource_id = recycle_rowset.resource_id(), rowset_id, this]() {
5459
                        // delete by prefix, the recycle rowset key will be deleted by range later.
5460
0
                        return delete_rowset_data(resource_id, tablet_id, rowset_id);
5461
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
5462
0
        } else {
5463
0
            const auto& rowset_meta = recycle_rowset.rowset_meta();
5464
            // Version 0-1 rowset has no resource_id and no actual data files,
5465
            // but still needs ref_count key cleanup, so we add it to all_tasks.
5466
            // It will be filtered out in Phase 2 when building rowsets_to_delete.
5467
0
            RowsetDeleteTask task;
5468
0
            task.rowset_meta = rowset_meta;
5469
0
            task.recycle_rowset_key = k;
5470
0
            all_tasks.push_back(std::move(task));
5471
0
        }
5472
0
        return 0;
5473
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_
5474
5475
11
    if (scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_recycle_rowset_kv))) {
5476
0
        LOG_WARNING("failed to recycle rowset kv of tablet")
5477
0
                .tag("tablet id", tablet_id)
5478
0
                .tag("instance_id", instance_id_)
5479
0
                .tag("reason", "failed to scan and recycle RecycleRowsetPB");
5480
0
        ret = -1;
5481
0
    }
5482
5483
    // Phase 1: Classify tasks by ref_count
5484
11
    std::vector<RowsetDeleteTask> batch_delete_tasks;
5485
    // Fallback path counts bytes via a separate context; the recycled bytes of all
5486
    // load/compact rowsets are published once below from the pre-aggregated totals.
5487
60
    for (auto& task : all_tasks) {
5488
60
        int classify_ret = classify_rowset_task_by_ref_count(task, batch_delete_tasks);
5489
60
        if (classify_ret < 0) {
5490
0
            LOG_WARNING("failed to classify rowset task, fallback to old logic")
5491
0
                    .tag("instance_id", instance_id_)
5492
0
                    .tag("tablet_id", tablet_id)
5493
0
                    .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5494
0
            concurrent_delete_executor.add([this, t = std::move(task), &metrics_context]() mutable {
5495
0
                return recycle_rowset_meta_and_data(t, metrics_context);
5496
0
            });
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler24recycle_versioned_tabletElRNS0_22RecyclerMetricsContextEEN3$_3clEv
5497
0
        }
5498
60
    }
5499
5500
11
    g_bvar_recycler_batch_delete_rowset_plan_count.put(instance_id_, batch_delete_tasks.size());
5501
5502
11
    LOG_INFO("batch delete plan created")
5503
11
            .tag("instance_id", instance_id_)
5504
11
            .tag("tablet_id", tablet_id)
5505
11
            .tag("plan_count", batch_delete_tasks.size());
5506
5507
    // Phase 2: Execute batch delete using existing delete_rowset_data
5508
11
    if (!batch_delete_tasks.empty()) {
5509
10
        std::map<std::string, RowsetMetaCloudPB> rowsets_to_delete;
5510
49
        for (const auto& task : batch_delete_tasks) {
5511
            // Version 0-1 rowset has no resource_id and no actual data files, skip it
5512
49
            if (task.rowset_meta.resource_id().empty()) {
5513
10
                LOG_INFO("skip rowset with empty resource_id in batch delete")
5514
10
                        .tag("instance_id", instance_id_)
5515
10
                        .tag("tablet_id", tablet_id)
5516
10
                        .tag("rowset_id", task.rowset_meta.rowset_id_v2());
5517
10
                continue;
5518
10
            }
5519
39
            rowsets_to_delete[task.rowset_meta.rowset_id_v2()] = task.rowset_meta;
5520
39
        }
5521
5522
        // Only call delete_rowset_data if there are rowsets with actual data to delete
5523
10
        bool delete_success = true;
5524
10
        if (!rowsets_to_delete.empty()) {
5525
9
            int delete_ret = delete_rowset_data(
5526
9
                    rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET, metrics_context);
5527
9
            if (delete_ret != 0) {
5528
0
                LOG_WARNING("batch delete execution failed")
5529
0
                        .tag("instance_id", instance_id_)
5530
0
                        .tag("tablet_id", tablet_id);
5531
0
                g_bvar_recycler_batch_delete_failures.put(instance_id_, 1);
5532
0
                ret = -1;
5533
0
                delete_success = false;
5534
0
            }
5535
9
        }
5536
5537
        // Phase 3: Only cleanup metadata if data deletion succeeded.
5538
        // If deletion failed, keep recycle_rowset_key so next round will retry.
5539
10
        if (delete_success) {
5540
10
            int cleanup_ret = cleanup_rowset_metadata(batch_delete_tasks);
5541
10
            if (cleanup_ret != 0) {
5542
0
                LOG_WARNING("batch delete cleanup failed")
5543
0
                        .tag("instance_id", instance_id_)
5544
0
                        .tag("tablet_id", tablet_id);
5545
0
                ret = -1;
5546
0
            }
5547
10
        }
5548
10
    }
5549
5550
    // Always wait for fallback tasks to complete before returning
5551
11
    bool finished = true;
5552
11
    std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
5553
11
    for (int r : rets) {
5554
0
        if (r != 0) {
5555
0
            ret = -1;
5556
0
        }
5557
0
    }
5558
5559
11
    ret = finished ? ret : -1;
5560
5561
11
    if (ret != 0) { // failed recycle tablet data
5562
0
        LOG_WARNING("recycle versioned tablet failed")
5563
0
                .tag("finished", finished)
5564
0
                .tag("ret", ret)
5565
0
                .tag("instance_id", instance_id_)
5566
0
                .tag("tablet_id", tablet_id);
5567
0
        return ret;
5568
0
    }
5569
5570
11
    tablet_metrics_context_.kv_recycled_bytes +=
5571
11
            recycle_rowsets_data_size + recycle_rowsets_index_size;
5572
5573
11
    txn.reset();
5574
11
    if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
5575
0
        LOG_WARNING("failed to recycle tablet ")
5576
0
                .tag("tablet id", tablet_id)
5577
0
                .tag("instance_id", instance_id_)
5578
0
                .tag("reason", "failed to create txn");
5579
0
        ret = -1;
5580
0
    }
5581
    // delete all rowset kv in this tablet
5582
11
    txn->remove(rs_key0, rs_key1);
5583
11
    txn->remove(recyc_rs_key0, recyc_rs_key1);
5584
5585
    // remove delete bitmap for MoW table
5586
11
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
5587
11
    txn->remove(pending_key);
5588
11
    std::string delete_bitmap_start = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
5589
11
    std::string delete_bitmap_end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
5590
11
    txn->remove(delete_bitmap_start, delete_bitmap_end);
5591
5592
11
    std::string dbm_start_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id, ""});
5593
11
    std::string dbm_end_key = versioned::meta_delete_bitmap_key({instance_id_, tablet_id + 1, ""});
5594
11
    txn->remove(dbm_start_key, dbm_end_key);
5595
11
    LOG(INFO) << "remove delete bitmap kv, tablet=" << tablet_id << ", begin=" << hex(dbm_start_key)
5596
11
              << " end=" << hex(dbm_end_key);
5597
5598
11
    std::string versioned_idx_key = versioned::tablet_index_key({instance_id_, tablet_id});
5599
11
    std::string tablet_index_val;
5600
11
    err = txn->get(versioned_idx_key, &tablet_index_val);
5601
11
    if (err != TxnErrorCode::TXN_KEY_NOT_FOUND && err != TxnErrorCode::TXN_OK) {
5602
0
        LOG_WARNING("failed to get tablet index kv")
5603
0
                .tag("instance_id", instance_id_)
5604
0
                .tag("tablet_id", tablet_id)
5605
0
                .tag("err", err);
5606
0
        ret = -1;
5607
11
    } else if (err == TxnErrorCode::TXN_OK) {
5608
        // If the tablet index kv exists, we need to delete it
5609
10
        TabletIndexPB tablet_index_pb;
5610
10
        if (!tablet_index_pb.ParseFromString(tablet_index_val)) {
5611
0
            LOG_WARNING("failed to parse tablet index pb")
5612
0
                    .tag("instance_id", instance_id_)
5613
0
                    .tag("tablet_id", tablet_id);
5614
0
            ret = -1;
5615
10
        } else {
5616
10
            std::string versioned_inverted_idx_key = versioned::tablet_inverted_index_key(
5617
10
                    {instance_id_, tablet_index_pb.db_id(), tablet_index_pb.table_id(),
5618
10
                     tablet_index_pb.index_id(), tablet_index_pb.partition_id(), tablet_id});
5619
10
            txn->remove(versioned_inverted_idx_key);
5620
10
            txn->remove(versioned_idx_key);
5621
10
        }
5622
10
    }
5623
5624
11
    err = txn->commit();
5625
11
    if (err != TxnErrorCode::TXN_OK) {
5626
0
        LOG(WARNING) << "failed to delete rowset kv of tablet " << tablet_id << ", err=" << err;
5627
0
        ret = -1;
5628
0
    }
5629
5630
11
    if (ret == 0) {
5631
        // All object files under tablet have been deleted, and all KV keys have been deleted
5632
11
        tablet_metrics_context_.kv_recycled_num += 1;
5633
11
        segment_metrics_context_.kv_recycled_num += recycle_segments_number;
5634
11
        std::lock_guard lock(recycled_tablets_mtx_);
5635
11
        recycled_tablets_.insert(tablet_id);
5636
11
    }
5637
5638
11
    return ret;
5639
11
}
5640
5641
47
int InstanceRecycler::recycle_rowsets() {
5642
47
    if (should_recycle_versioned_keys()) {
5643
5
        return recycle_versioned_rowsets();
5644
5
    }
5645
5646
42
    const std::string task_name = "recycle_rowsets";
5647
42
    int64_t num_scanned = 0;
5648
42
    int64_t num_expired = 0;
5649
42
    int64_t num_prepare = 0;
5650
42
    int64_t num_compacted = 0;
5651
42
    int64_t num_empty_rowset = 0;
5652
42
    size_t total_rowset_key_size = 0;
5653
42
    size_t total_rowset_value_size = 0;
5654
42
    size_t expired_rowset_size = 0;
5655
42
    std::atomic_long num_recycled = 0;
5656
42
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5657
5658
42
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
5659
42
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
5660
42
    std::string recyc_rs_key0;
5661
42
    std::string recyc_rs_key1;
5662
42
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
5663
42
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
5664
5665
42
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
5666
5667
42
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5668
42
    register_recycle_task(task_name, start_time);
5669
5670
42
    DORIS_CLOUD_DEFER {
5671
42
        metrics_context.kv_scanned_num.set(num_scanned);
5672
42
        metrics_context.kv_expired_num.set(num_expired);
5673
42
        metrics_context.kv_recycled_num.set(num_recycled);
5674
42
        unregister_recycle_task(task_name);
5675
42
        int64_t cost =
5676
42
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5677
42
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5678
42
                .tag("instance_id", instance_id_)
5679
42
                .tag("num_scanned", num_scanned)
5680
42
                .tag("num_expired", num_expired)
5681
42
                .tag("num_recycled", num_recycled)
5682
42
                .tag("num_recycled.prepare", num_prepare)
5683
42
                .tag("num_recycled.compacted", num_compacted)
5684
42
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5685
42
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5686
42
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5687
42
                .tag("expired_rowset_meta_size", expired_rowset_size);
5688
42
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5670
7
    DORIS_CLOUD_DEFER {
5671
7
        metrics_context.kv_scanned_num.set(num_scanned);
5672
7
        metrics_context.kv_expired_num.set(num_expired);
5673
7
        metrics_context.kv_recycled_num.set(num_recycled);
5674
7
        unregister_recycle_task(task_name);
5675
7
        int64_t cost =
5676
7
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5677
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5678
7
                .tag("instance_id", instance_id_)
5679
7
                .tag("num_scanned", num_scanned)
5680
7
                .tag("num_expired", num_expired)
5681
7
                .tag("num_recycled", num_recycled)
5682
7
                .tag("num_recycled.prepare", num_prepare)
5683
7
                .tag("num_recycled.compacted", num_compacted)
5684
7
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5685
7
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5686
7
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5687
7
                .tag("expired_rowset_meta_size", expired_rowset_size);
5688
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_0clEv
Line
Count
Source
5670
35
    DORIS_CLOUD_DEFER {
5671
35
        metrics_context.kv_scanned_num.set(num_scanned);
5672
35
        metrics_context.kv_expired_num.set(num_expired);
5673
35
        metrics_context.kv_recycled_num.set(num_recycled);
5674
35
        unregister_recycle_task(task_name);
5675
35
        int64_t cost =
5676
35
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5677
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
5678
35
                .tag("instance_id", instance_id_)
5679
35
                .tag("num_scanned", num_scanned)
5680
35
                .tag("num_expired", num_expired)
5681
35
                .tag("num_recycled", num_recycled)
5682
35
                .tag("num_recycled.prepare", num_prepare)
5683
35
                .tag("num_recycled.compacted", num_compacted)
5684
35
                .tag("num_recycled.empty_rowset", num_empty_rowset)
5685
35
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
5686
35
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
5687
35
                .tag("expired_rowset_meta_size", expired_rowset_size);
5688
35
    };
5689
5690
42
    std::vector<std::string> rowset_keys;
5691
42
    std::vector<std::string> rowset_keys_to_mark_recycled;
5692
42
    std::vector<std::string> rowset_keys_to_abort_job;
5693
    // rowset_id -> rowset_meta
5694
    // store rowset id and meta for statistics rs size when delete
5695
42
    std::map<std::string, doris::RowsetMetaCloudPB> rowsets;
5696
5697
42
    std::mutex async_recycled_rowset_keys_mutex;
5698
42
    std::vector<std::string> async_recycled_rowset_keys;
5699
42
    auto worker_pool = std::make_unique<SimpleThreadPool>(
5700
42
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
5701
42
    worker_pool->start();
5702
42
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
5703
42
                                            int64_t partition_id, int64_t tablet_id,
5704
903
                                            const std::string& rowset_id) {
5705
        // Try to delete rowset data in background thread
5706
903
        int ret = worker_pool->submit_with_timeout(
5707
903
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5708
726
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5709
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5710
0
                        return;
5711
0
                    }
5712
726
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5713
726
                        0) {
5714
0
                        return;
5715
0
                    }
5716
726
                    std::vector<std::string> keys;
5717
726
                    {
5718
726
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5719
726
                        async_recycled_rowset_keys.push_back(std::move(key));
5720
726
                        if (async_recycled_rowset_keys.size() > 100) {
5721
7
                            keys.swap(async_recycled_rowset_keys);
5722
7
                        }
5723
726
                    }
5724
726
                    if (keys.empty()) return;
5725
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5726
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5727
0
                                     << instance_id_;
5728
7
                    } else {
5729
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5730
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5731
7
                                           num_recycled, start_time);
5732
7
                    }
5733
7
                },
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5707
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5708
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5709
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5710
0
                        return;
5711
0
                    }
5712
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5713
1
                        0) {
5714
0
                        return;
5715
0
                    }
5716
1
                    std::vector<std::string> keys;
5717
1
                    {
5718
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5719
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5720
1
                        if (async_recycled_rowset_keys.size() > 100) {
5721
0
                            keys.swap(async_recycled_rowset_keys);
5722
0
                        }
5723
1
                    }
5724
1
                    if (keys.empty()) return;
5725
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5726
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5727
0
                                     << instance_id_;
5728
0
                    } else {
5729
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5730
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5731
0
                                           num_recycled, start_time);
5732
0
                    }
5733
0
                },
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_ENUlvE_clEv
Line
Count
Source
5707
725
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5708
725
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5709
0
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5710
0
                        return;
5711
0
                    }
5712
725
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5713
725
                        0) {
5714
0
                        return;
5715
0
                    }
5716
725
                    std::vector<std::string> keys;
5717
725
                    {
5718
725
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5719
725
                        async_recycled_rowset_keys.push_back(std::move(key));
5720
725
                        if (async_recycled_rowset_keys.size() > 100) {
5721
7
                            keys.swap(async_recycled_rowset_keys);
5722
7
                        }
5723
725
                    }
5724
725
                    if (keys.empty()) return;
5725
7
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5726
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5727
0
                                     << instance_id_;
5728
7
                    } else {
5729
7
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5730
7
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5731
7
                                           num_recycled, start_time);
5732
7
                    }
5733
7
                },
5734
903
                0);
5735
903
        if (ret == 0) return 0;
5736
        // Submit task failed, delete rowset data in current thread
5737
177
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5738
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5739
0
            return -1;
5740
0
        }
5741
177
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5742
0
            return -1;
5743
0
        }
5744
177
        rowset_keys.push_back(std::move(key));
5745
177
        return 0;
5746
177
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5704
1
                                            const std::string& rowset_id) {
5705
        // Try to delete rowset data in background thread
5706
1
        int ret = worker_pool->submit_with_timeout(
5707
1
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5708
1
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5709
1
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5710
1
                        return;
5711
1
                    }
5712
1
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5713
1
                        0) {
5714
1
                        return;
5715
1
                    }
5716
1
                    std::vector<std::string> keys;
5717
1
                    {
5718
1
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5719
1
                        async_recycled_rowset_keys.push_back(std::move(key));
5720
1
                        if (async_recycled_rowset_keys.size() > 100) {
5721
1
                            keys.swap(async_recycled_rowset_keys);
5722
1
                        }
5723
1
                    }
5724
1
                    if (keys.empty()) return;
5725
1
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5726
1
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5727
1
                                     << instance_id_;
5728
1
                    } else {
5729
1
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5730
1
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5731
1
                                           num_recycled, start_time);
5732
1
                    }
5733
1
                },
5734
1
                0);
5735
1
        if (ret == 0) return 0;
5736
        // Submit task failed, delete rowset data in current thread
5737
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5738
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5739
0
            return -1;
5740
0
        }
5741
0
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5742
0
            return -1;
5743
0
        }
5744
0
        rowset_keys.push_back(std::move(key));
5745
0
        return 0;
5746
0
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_1clENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKS8_llSA_
Line
Count
Source
5704
902
                                            const std::string& rowset_id) {
5705
        // Try to delete rowset data in background thread
5706
902
        int ret = worker_pool->submit_with_timeout(
5707
902
                [&, resource_id, partition_id, tablet_id, rowset_id, key]() mutable {
5708
902
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5709
902
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5710
902
                        return;
5711
902
                    }
5712
902
                    if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) !=
5713
902
                        0) {
5714
902
                        return;
5715
902
                    }
5716
902
                    std::vector<std::string> keys;
5717
902
                    {
5718
902
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
5719
902
                        async_recycled_rowset_keys.push_back(std::move(key));
5720
902
                        if (async_recycled_rowset_keys.size() > 100) {
5721
902
                            keys.swap(async_recycled_rowset_keys);
5722
902
                        }
5723
902
                    }
5724
902
                    if (keys.empty()) return;
5725
902
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
5726
902
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
5727
902
                                     << instance_id_;
5728
902
                    } else {
5729
902
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
5730
902
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
5731
902
                                           num_recycled, start_time);
5732
902
                    }
5733
902
                },
5734
902
                0);
5735
902
        if (ret == 0) return 0;
5736
        // Submit task failed, delete rowset data in current thread
5737
177
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
5738
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
5739
0
            return -1;
5740
0
        }
5741
177
        if (delete_versioned_delete_bitmap_kvs(partition_id, tablet_id, rowset_id) != 0) {
5742
0
            return -1;
5743
0
        }
5744
177
        rowset_keys.push_back(std::move(key));
5745
177
        return 0;
5746
177
    };
5747
5748
42
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5749
5750
4.28k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5751
4.28k
        ++num_scanned;
5752
4.28k
        total_rowset_key_size += k.size();
5753
4.28k
        total_rowset_value_size += v.size();
5754
4.28k
        RecycleRowsetPB rowset;
5755
4.28k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5756
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5757
0
            return -1;
5758
0
        }
5759
5760
4.28k
        int64_t current_time = ::time(nullptr);
5761
4.28k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5762
5763
4.28k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5764
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5765
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5766
4.28k
        if (current_time < expiration) { // not expired
5767
0
            return 0;
5768
0
        }
5769
4.28k
        ++num_expired;
5770
4.28k
        expired_rowset_size += v.size();
5771
5772
4.28k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5773
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5774
                // in old version, keep this key-value pair and it needs to be checked manually
5775
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5776
0
                return -1;
5777
0
            }
5778
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5779
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5780
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5781
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5782
0
                rowset_keys.emplace_back(k);
5783
0
                return -1;
5784
0
            }
5785
            // decode rowset_id
5786
250
            auto k1 = k;
5787
250
            k1.remove_prefix(1);
5788
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5789
250
            decode_key(&k1, &out);
5790
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5791
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5792
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5793
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5794
250
                      << " task_type=" << metrics_context.operation_type;
5795
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5796
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5797
0
                return -1;
5798
0
            }
5799
250
            metrics_context.kv_recycled_bytes += rowset.rowset_meta().total_disk_size();
5800
250
            segment_metrics_context_.kv_recycled_bytes += rowset.rowset_meta().total_disk_size();
5801
250
            segment_metrics_context_.kv_recycled_num += rowset.rowset_meta().num_segments();
5802
250
            return 0;
5803
250
        }
5804
4.03k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5805
5806
        // TODO(plat1ko): check rowset not referenced
5807
4.03k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5808
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5809
0
                LOG_INFO("recycle rowset that has empty resource id");
5810
0
            } else {
5811
                // other situations, keep this key-value pair and it needs to be checked manually
5812
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5813
0
                return -1;
5814
0
            }
5815
0
        }
5816
4.03k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5817
4.03k
                  << " tablet_id=" << rowset_meta->tablet_id()
5818
4.03k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5819
4.03k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5820
4.03k
                  << "] txn_id=" << rowset_meta->txn_id()
5821
4.03k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5822
4.03k
                  << " rowset_meta_size=" << v.size()
5823
4.03k
                  << " creation_time=" << rowset_meta->creation_time()
5824
4.03k
                  << " task_type=" << metrics_context.operation_type;
5825
4.03k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5826
938
            if (config::enable_mark_delete_rowset_before_recycle) {
5827
23
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5828
13
                    rowset_keys_to_mark_recycled.emplace_back(k);
5829
13
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5830
13
                                 "kv "
5831
13
                                 "at next turn, instance_id="
5832
13
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5833
13
                              << " version=[" << rowset_meta->start_version() << '-'
5834
13
                              << rowset_meta->end_version() << "]";
5835
13
                    return 0;
5836
13
                }
5837
23
            }
5838
5839
925
            num_prepare += 1;
5840
925
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5841
925
                rowset_meta->end_version() != 1) {
5842
273
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5843
272
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5844
272
                                 "instance_id="
5845
272
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5846
272
                              << " version=[" << rowset_meta->start_version() << '-'
5847
272
                              << rowset_meta->end_version() << "]";
5848
272
                    rowset_keys_to_abort_job.emplace_back(k);
5849
272
                    return 0;
5850
272
                }
5851
273
            }
5852
653
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5853
653
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5854
653
                                             rowset_meta->rowset_id_v2()) != 0) {
5855
0
                return -1;
5856
0
            }
5857
3.10k
        } else {
5858
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5859
3.10k
            rowset_keys.emplace_back(k);
5860
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5861
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5862
3.10k
                ++num_empty_rowset;
5863
3.10k
            }
5864
3.10k
        }
5865
3.75k
        return 0;
5866
4.03k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5750
7
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5751
7
        ++num_scanned;
5752
7
        total_rowset_key_size += k.size();
5753
7
        total_rowset_value_size += v.size();
5754
7
        RecycleRowsetPB rowset;
5755
7
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5756
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5757
0
            return -1;
5758
0
        }
5759
5760
7
        int64_t current_time = ::time(nullptr);
5761
7
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5762
5763
7
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5764
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5765
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5766
7
        if (current_time < expiration) { // not expired
5767
0
            return 0;
5768
0
        }
5769
7
        ++num_expired;
5770
7
        expired_rowset_size += v.size();
5771
5772
7
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5773
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5774
                // in old version, keep this key-value pair and it needs to be checked manually
5775
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5776
0
                return -1;
5777
0
            }
5778
0
            if (rowset.resource_id().empty()) [[unlikely]] {
5779
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5780
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5781
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5782
0
                rowset_keys.emplace_back(k);
5783
0
                return -1;
5784
0
            }
5785
            // decode rowset_id
5786
0
            auto k1 = k;
5787
0
            k1.remove_prefix(1);
5788
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5789
0
            decode_key(&k1, &out);
5790
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5791
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5792
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5793
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5794
0
                      << " task_type=" << metrics_context.operation_type;
5795
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5796
0
                                             rowset.tablet_id(), rowset_id) != 0) {
5797
0
                return -1;
5798
0
            }
5799
0
            metrics_context.kv_recycled_bytes += rowset.rowset_meta().total_disk_size();
5800
0
            segment_metrics_context_.kv_recycled_bytes += rowset.rowset_meta().total_disk_size();
5801
0
            segment_metrics_context_.kv_recycled_num += rowset.rowset_meta().num_segments();
5802
0
            return 0;
5803
0
        }
5804
7
        auto* rowset_meta = rowset.mutable_rowset_meta();
5805
5806
        // TODO(plat1ko): check rowset not referenced
5807
7
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5808
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5809
0
                LOG_INFO("recycle rowset that has empty resource id");
5810
0
            } else {
5811
                // other situations, keep this key-value pair and it needs to be checked manually
5812
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5813
0
                return -1;
5814
0
            }
5815
0
        }
5816
7
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5817
7
                  << " tablet_id=" << rowset_meta->tablet_id()
5818
7
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5819
7
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5820
7
                  << "] txn_id=" << rowset_meta->txn_id()
5821
7
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5822
7
                  << " rowset_meta_size=" << v.size()
5823
7
                  << " creation_time=" << rowset_meta->creation_time()
5824
7
                  << " task_type=" << metrics_context.operation_type;
5825
7
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5826
7
            if (config::enable_mark_delete_rowset_before_recycle) {
5827
6
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5828
4
                    rowset_keys_to_mark_recycled.emplace_back(k);
5829
4
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5830
4
                                 "kv "
5831
4
                                 "at next turn, instance_id="
5832
4
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5833
4
                              << " version=[" << rowset_meta->start_version() << '-'
5834
4
                              << rowset_meta->end_version() << "]";
5835
4
                    return 0;
5836
4
                }
5837
6
            }
5838
5839
3
            num_prepare += 1;
5840
3
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5841
3
                rowset_meta->end_version() != 1) {
5842
2
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5843
2
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5844
2
                                 "instance_id="
5845
2
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5846
2
                              << " version=[" << rowset_meta->start_version() << '-'
5847
2
                              << rowset_meta->end_version() << "]";
5848
2
                    rowset_keys_to_abort_job.emplace_back(k);
5849
2
                    return 0;
5850
2
                }
5851
2
            }
5852
1
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5853
1
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5854
1
                                             rowset_meta->rowset_id_v2()) != 0) {
5855
0
                return -1;
5856
0
            }
5857
1
        } else {
5858
0
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5859
0
            rowset_keys.emplace_back(k);
5860
0
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5861
0
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5862
0
                ++num_empty_rowset;
5863
0
            }
5864
0
        }
5865
1
        return 0;
5866
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
5750
4.28k
    auto handle_rowset_kv = [&](std::string_view k, std::string_view v) -> int {
5751
4.28k
        ++num_scanned;
5752
4.28k
        total_rowset_key_size += k.size();
5753
4.28k
        total_rowset_value_size += v.size();
5754
4.28k
        RecycleRowsetPB rowset;
5755
4.28k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
5756
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
5757
0
            return -1;
5758
0
        }
5759
5760
4.28k
        int64_t current_time = ::time(nullptr);
5761
4.28k
        int64_t expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
5762
5763
4.28k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
5764
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
5765
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
5766
4.28k
        if (current_time < expiration) { // not expired
5767
0
            return 0;
5768
0
        }
5769
4.28k
        ++num_expired;
5770
4.28k
        expired_rowset_size += v.size();
5771
5772
4.28k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
5773
250
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
5774
                // in old version, keep this key-value pair and it needs to be checked manually
5775
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5776
0
                return -1;
5777
0
            }
5778
250
            if (rowset.resource_id().empty()) [[unlikely]] {
5779
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
5780
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
5781
0
                          << hex(k) << " value=" << proto_to_json(rowset);
5782
0
                rowset_keys.emplace_back(k);
5783
0
                return -1;
5784
0
            }
5785
            // decode rowset_id
5786
250
            auto k1 = k;
5787
250
            k1.remove_prefix(1);
5788
250
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
5789
250
            decode_key(&k1, &out);
5790
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
5791
250
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
5792
250
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5793
250
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id
5794
250
                      << " task_type=" << metrics_context.operation_type;
5795
250
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(), -1,
5796
250
                                             rowset.tablet_id(), rowset_id) != 0) {
5797
0
                return -1;
5798
0
            }
5799
250
            metrics_context.kv_recycled_bytes += rowset.rowset_meta().total_disk_size();
5800
250
            segment_metrics_context_.kv_recycled_bytes += rowset.rowset_meta().total_disk_size();
5801
250
            segment_metrics_context_.kv_recycled_num += rowset.rowset_meta().num_segments();
5802
250
            return 0;
5803
250
        }
5804
4.03k
        auto* rowset_meta = rowset.mutable_rowset_meta();
5805
5806
        // TODO(plat1ko): check rowset not referenced
5807
4.03k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
5808
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
5809
0
                LOG_INFO("recycle rowset that has empty resource id");
5810
0
            } else {
5811
                // other situations, keep this key-value pair and it needs to be checked manually
5812
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
5813
0
                return -1;
5814
0
            }
5815
0
        }
5816
4.03k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
5817
4.03k
                  << " tablet_id=" << rowset_meta->tablet_id()
5818
4.03k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
5819
4.03k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
5820
4.03k
                  << "] txn_id=" << rowset_meta->txn_id()
5821
4.03k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
5822
4.03k
                  << " rowset_meta_size=" << v.size()
5823
4.03k
                  << " creation_time=" << rowset_meta->creation_time()
5824
4.03k
                  << " task_type=" << metrics_context.operation_type;
5825
4.03k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
5826
931
            if (config::enable_mark_delete_rowset_before_recycle) {
5827
17
                if (need_mark_rowset_as_recycled(rowset.rowset_meta())) {
5828
9
                    rowset_keys_to_mark_recycled.emplace_back(k);
5829
9
                    LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and "
5830
9
                                 "kv "
5831
9
                                 "at next turn, instance_id="
5832
9
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5833
9
                              << " version=[" << rowset_meta->start_version() << '-'
5834
9
                              << rowset_meta->end_version() << "]";
5835
9
                    return 0;
5836
9
                }
5837
17
            }
5838
5839
922
            num_prepare += 1;
5840
922
            if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle &&
5841
922
                rowset_meta->end_version() != 1) {
5842
271
                if (make_related_txn_or_job_abort_task(rowset).has_value()) {
5843
270
                    LOG(INFO) << "rowset queued to abort related txn or job before recycling, "
5844
270
                                 "instance_id="
5845
270
                              << instance_id_ << " tablet_id=" << rowset_meta->tablet_id()
5846
270
                              << " version=[" << rowset_meta->start_version() << '-'
5847
270
                              << rowset_meta->end_version() << "]";
5848
270
                    rowset_keys_to_abort_job.emplace_back(k);
5849
270
                    return 0;
5850
270
                }
5851
271
            }
5852
652
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
5853
652
                                             rowset_meta->partition_id(), rowset_meta->tablet_id(),
5854
652
                                             rowset_meta->rowset_id_v2()) != 0) {
5855
0
                return -1;
5856
0
            }
5857
3.10k
        } else {
5858
3.10k
            num_compacted += rowset.type() == RecycleRowsetPB::COMPACT;
5859
3.10k
            rowset_keys.emplace_back(k);
5860
3.10k
            rowsets.emplace(rowset_meta->rowset_id_v2(), std::move(*rowset_meta));
5861
3.10k
            if (rowset_meta->num_segments() <= 0) { // Skip empty rowset
5862
3.10k
                ++num_empty_rowset;
5863
3.10k
            }
5864
3.10k
        }
5865
3.75k
        return 0;
5866
4.03k
    };
5867
5868
48
    auto loop_done = [&]() -> int {
5869
48
        DORIS_CLOUD_DEFER {
5870
48
            metrics_context.kv_scanned_num.set(num_scanned);
5871
48
            metrics_context.kv_expired_num.set(num_expired);
5872
48
            metrics_context.kv_recycled_num.set(num_recycled);
5873
48
            metrics_context.update_metrics();
5874
48
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
5869
7
        DORIS_CLOUD_DEFER {
5870
7
            metrics_context.kv_scanned_num.set(num_scanned);
5871
7
            metrics_context.kv_expired_num.set(num_expired);
5872
7
            metrics_context.kv_recycled_num.set(num_recycled);
5873
7
            metrics_context.update_metrics();
5874
7
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
5869
41
        DORIS_CLOUD_DEFER {
5870
41
            metrics_context.kv_scanned_num.set(num_scanned);
5871
41
            metrics_context.kv_expired_num.set(num_expired);
5872
41
            metrics_context.kv_recycled_num.set(num_recycled);
5873
41
            metrics_context.update_metrics();
5874
41
        };
5875
48
        std::vector<std::string> rowset_keys_to_delete;
5876
        // rowset_id -> rowset_meta
5877
        // store rowset id and meta for statistics rs size when delete
5878
48
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5879
48
        std::vector<std::string> mark_keys_to_process;
5880
48
        std::vector<std::string> abort_job_keys_to_process;
5881
48
        rowset_keys_to_delete.swap(rowset_keys);
5882
48
        rowsets_to_delete.swap(rowsets);
5883
48
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5884
48
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5885
48
        if (!mark_keys_to_process.empty()) {
5886
11
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5887
11
                    *worker_pool, std::move(mark_keys_to_process));
5888
11
        }
5889
48
        if (!abort_job_keys_to_process.empty()) {
5890
15
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5891
15
                                               &num_recycled, &metrics_context);
5892
15
        }
5893
48
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5894
48
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5895
48
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5896
48
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5897
48
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5898
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5899
0
                return;
5900
0
            }
5901
48
            if (!versioned_delete_bitmap_key_groups.empty() &&
5902
48
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5903
11
                                                         versioned_delete_bitmap_key_groups) != 0) {
5904
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5905
0
                             << instance_id_;
5906
0
                return;
5907
0
            }
5908
48
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5909
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5910
0
                return;
5911
0
            }
5912
48
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5913
48
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE0_clEv
Line
Count
Source
5894
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5895
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5896
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5897
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5898
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5899
0
                return;
5900
0
            }
5901
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5902
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5903
0
                                                         versioned_delete_bitmap_key_groups) != 0) {
5904
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5905
0
                             << instance_id_;
5906
0
                return;
5907
0
            }
5908
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5909
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5910
0
                return;
5911
0
            }
5912
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5913
7
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEvENUlvE0_clEv
Line
Count
Source
5894
41
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5895
41
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5896
41
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5897
41
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5898
0
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5899
0
                return;
5900
0
            }
5901
41
            if (!versioned_delete_bitmap_key_groups.empty() &&
5902
41
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5903
11
                                                         versioned_delete_bitmap_key_groups) != 0) {
5904
0
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5905
0
                             << instance_id_;
5906
0
                return;
5907
0
            }
5908
41
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5909
0
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5910
0
                return;
5911
0
            }
5912
41
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5913
41
        });
5914
48
        return 0;
5915
48
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5868
7
    auto loop_done = [&]() -> int {
5869
7
        DORIS_CLOUD_DEFER {
5870
7
            metrics_context.kv_scanned_num.set(num_scanned);
5871
7
            metrics_context.kv_expired_num.set(num_expired);
5872
7
            metrics_context.kv_recycled_num.set(num_recycled);
5873
7
            metrics_context.update_metrics();
5874
7
        };
5875
7
        std::vector<std::string> rowset_keys_to_delete;
5876
        // rowset_id -> rowset_meta
5877
        // store rowset id and meta for statistics rs size when delete
5878
7
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5879
7
        std::vector<std::string> mark_keys_to_process;
5880
7
        std::vector<std::string> abort_job_keys_to_process;
5881
7
        rowset_keys_to_delete.swap(rowset_keys);
5882
7
        rowsets_to_delete.swap(rowsets);
5883
7
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5884
7
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5885
7
        if (!mark_keys_to_process.empty()) {
5886
4
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5887
4
                    *worker_pool, std::move(mark_keys_to_process));
5888
4
        }
5889
7
        if (!abort_job_keys_to_process.empty()) {
5890
2
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5891
2
                                               &num_recycled, &metrics_context);
5892
2
        }
5893
7
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5894
7
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5895
7
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5896
7
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5897
7
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5898
7
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5899
7
                return;
5900
7
            }
5901
7
            if (!versioned_delete_bitmap_key_groups.empty() &&
5902
7
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5903
7
                                                         versioned_delete_bitmap_key_groups) != 0) {
5904
7
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5905
7
                             << instance_id_;
5906
7
                return;
5907
7
            }
5908
7
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5909
7
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5910
7
                return;
5911
7
            }
5912
7
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5913
7
        });
5914
7
        return 0;
5915
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler15recycle_rowsetsEvENK3$_2clEv
Line
Count
Source
5868
41
    auto loop_done = [&]() -> int {
5869
41
        DORIS_CLOUD_DEFER {
5870
41
            metrics_context.kv_scanned_num.set(num_scanned);
5871
41
            metrics_context.kv_expired_num.set(num_expired);
5872
41
            metrics_context.kv_recycled_num.set(num_recycled);
5873
41
            metrics_context.update_metrics();
5874
41
        };
5875
41
        std::vector<std::string> rowset_keys_to_delete;
5876
        // rowset_id -> rowset_meta
5877
        // store rowset id and meta for statistics rs size when delete
5878
41
        std::map<std::string, doris::RowsetMetaCloudPB> rowsets_to_delete;
5879
41
        std::vector<std::string> mark_keys_to_process;
5880
41
        std::vector<std::string> abort_job_keys_to_process;
5881
41
        rowset_keys_to_delete.swap(rowset_keys);
5882
41
        rowsets_to_delete.swap(rowsets);
5883
41
        mark_keys_to_process.swap(rowset_keys_to_mark_recycled);
5884
41
        abort_job_keys_to_process.swap(rowset_keys_to_abort_job);
5885
41
        if (!mark_keys_to_process.empty()) {
5886
7
            submit_batch_mark_rowsets_as_recycled_job<RecycleRowsetPB>(
5887
7
                    *worker_pool, std::move(mark_keys_to_process));
5888
7
        }
5889
41
        if (!abort_job_keys_to_process.empty()) {
5890
13
            submit_recycle_prepare_rowsets_job(*worker_pool, std::move(abort_job_keys_to_process),
5891
13
                                               &num_recycled, &metrics_context);
5892
13
        }
5893
41
        worker_pool->submit([&, rowset_keys_to_delete = std::move(rowset_keys_to_delete),
5894
41
                             rowsets_to_delete = std::move(rowsets_to_delete)]() mutable {
5895
41
            std::vector<std::vector<std::string>> versioned_delete_bitmap_key_groups;
5896
41
            if (delete_rowset_data(rowsets_to_delete, RowsetRecyclingState::FORMAL_ROWSET,
5897
41
                                   metrics_context, &versioned_delete_bitmap_key_groups) != 0) {
5898
41
                LOG(WARNING) << "failed to delete rowset data, instance_id=" << instance_id_;
5899
41
                return;
5900
41
            }
5901
41
            if (!versioned_delete_bitmap_key_groups.empty() &&
5902
41
                delete_versioned_delete_bitmap_by_rowset(txn_kv_.get(),
5903
41
                                                         versioned_delete_bitmap_key_groups) != 0) {
5904
41
                LOG(WARNING) << "failed to delete versioned delete bitmap kv, instance_id="
5905
41
                             << instance_id_;
5906
41
                return;
5907
41
            }
5908
41
            if (txn_remove(txn_kv_.get(), rowset_keys_to_delete) != 0) {
5909
41
                LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5910
41
                return;
5911
41
            }
5912
41
            num_recycled.fetch_add(rowset_keys_to_delete.size(), std::memory_order_relaxed);
5913
41
        });
5914
41
        return 0;
5915
41
    };
5916
5917
    // recycle_func and loop_done for scan and recycle
5918
42
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
5919
42
                               std::move(loop_done));
5920
5921
42
    worker_pool->stop();
5922
5923
42
    if (!async_recycled_rowset_keys.empty()) {
5924
4
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
5925
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
5926
0
            return -1;
5927
4
        } else {
5928
4
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
5929
4
        }
5930
4
    }
5931
42
    return ret;
5932
42
}
5933
5934
int InstanceRecycler::next_recycle_rowset_tablet_key(const std::string& instance_id,
5935
0
                                                     int64_t tablet_id, std::string* next_key) {
5936
0
    DCHECK(next_key != nullptr);
5937
0
    if (tablet_id == std::numeric_limits<int64_t>::max()) {
5938
0
        return -1;
5939
0
    }
5940
0
    *next_key = recycle_rowset_key({instance_id, tablet_id + 1, ""});
5941
0
    return 0;
5942
0
}
5943
5944
13
int InstanceRecycler::recycle_restore_jobs() {
5945
13
    const std::string task_name = "recycle_restore_jobs";
5946
13
    int64_t num_scanned = 0;
5947
13
    int64_t num_expired = 0;
5948
13
    int64_t num_recycled = 0;
5949
13
    int64_t num_aborted = 0;
5950
5951
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
5952
5953
13
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
5954
13
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
5955
13
    std::string restore_job_key0;
5956
13
    std::string restore_job_key1;
5957
13
    job_restore_tablet_key(restore_job_key_info0, &restore_job_key0);
5958
13
    job_restore_tablet_key(restore_job_key_info1, &restore_job_key1);
5959
5960
13
    LOG_INFO("begin to recycle restore jobs").tag("instance_id", instance_id_);
5961
5962
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
5963
13
    register_recycle_task(task_name, start_time);
5964
5965
13
    DORIS_CLOUD_DEFER {
5966
13
        metrics_context.kv_scanned_num.set(num_scanned);
5967
13
        metrics_context.kv_expired_num.set(num_expired);
5968
13
        metrics_context.kv_recycled_num.set(num_recycled);
5969
13
        unregister_recycle_task(task_name);
5970
13
        int64_t cost =
5971
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5972
13
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5973
13
                .tag("instance_id", instance_id_)
5974
13
                .tag("num_scanned", num_scanned)
5975
13
                .tag("num_expired", num_expired)
5976
13
                .tag("num_recycled", num_recycled)
5977
13
                .tag("num_aborted", num_aborted);
5978
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_0clEv
Line
Count
Source
5965
13
    DORIS_CLOUD_DEFER {
5966
13
        metrics_context.kv_scanned_num.set(num_scanned);
5967
13
        metrics_context.kv_expired_num.set(num_expired);
5968
13
        metrics_context.kv_recycled_num.set(num_recycled);
5969
13
        unregister_recycle_task(task_name);
5970
13
        int64_t cost =
5971
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
5972
        LOG_INFO("recycle restore jobs finished, cost={}s", cost)
5973
13
                .tag("instance_id", instance_id_)
5974
13
                .tag("num_scanned", num_scanned)
5975
13
                .tag("num_expired", num_expired)
5976
13
                .tag("num_recycled", num_recycled)
5977
13
                .tag("num_aborted", num_aborted);
5978
13
    };
5979
5980
13
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
5981
5982
13
    std::vector<std::string_view> restore_job_keys;
5983
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5984
41
        ++num_scanned;
5985
41
        RestoreJobCloudPB restore_job_pb;
5986
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5987
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5988
0
            return -1;
5989
0
        }
5990
41
        int64_t expiration =
5991
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5992
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5993
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5994
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5995
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5996
0
                   << " state=" << restore_job_pb.state();
5997
41
        int64_t current_time = ::time(nullptr);
5998
41
        if (current_time < expiration) { // not expired
5999
0
            return 0;
6000
0
        }
6001
41
        ++num_expired;
6002
6003
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6004
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6005
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6006
6007
41
        std::unique_ptr<Transaction> txn;
6008
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6009
41
        if (err != TxnErrorCode::TXN_OK) {
6010
0
            LOG_WARNING("failed to recycle restore job")
6011
0
                    .tag("err", err)
6012
0
                    .tag("tablet id", tablet_id)
6013
0
                    .tag("instance_id", instance_id_)
6014
0
                    .tag("reason", "failed to create txn");
6015
0
            return -1;
6016
0
        }
6017
6018
41
        std::string val;
6019
41
        err = txn->get(k, &val);
6020
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6021
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6022
0
            return 0;
6023
0
        }
6024
41
        if (err != TxnErrorCode::TXN_OK) {
6025
0
            LOG_WARNING("failed to get kv");
6026
0
            return -1;
6027
0
        }
6028
41
        restore_job_pb.Clear();
6029
41
        if (!restore_job_pb.ParseFromString(val)) {
6030
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6031
0
            return -1;
6032
0
        }
6033
6034
        // PREPARED or COMMITTED, change state to DROPPED and return
6035
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6036
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6037
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6038
0
            restore_job_pb.set_need_recycle_data(true);
6039
0
            txn->put(k, restore_job_pb.SerializeAsString());
6040
0
            err = txn->commit();
6041
0
            if (err != TxnErrorCode::TXN_OK) {
6042
0
                LOG_WARNING("failed to commit txn: {}", err);
6043
0
                return -1;
6044
0
            }
6045
0
            num_aborted++;
6046
0
            return 0;
6047
0
        }
6048
6049
        // Change state to RECYCLING
6050
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6051
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6052
21
            txn->put(k, restore_job_pb.SerializeAsString());
6053
21
            err = txn->commit();
6054
21
            if (err != TxnErrorCode::TXN_OK) {
6055
0
                LOG_WARNING("failed to commit txn: {}", err);
6056
0
                return -1;
6057
0
            }
6058
21
            return 0;
6059
21
        }
6060
6061
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6062
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6063
6064
        // Recycle all data associated with the restore job.
6065
        // This includes rowsets, segments, and related resources.
6066
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6067
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6068
0
            LOG_WARNING("failed to recycle tablet")
6069
0
                    .tag("tablet_id", tablet_id)
6070
0
                    .tag("instance_id", instance_id_);
6071
0
            return -1;
6072
0
        }
6073
6074
        // delete all restore job rowset kv
6075
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6076
6077
20
        err = txn->commit();
6078
20
        if (err != TxnErrorCode::TXN_OK) {
6079
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6080
0
                    .tag("err", err)
6081
0
                    .tag("tablet id", tablet_id)
6082
0
                    .tag("instance_id", instance_id_)
6083
0
                    .tag("reason", "failed to commit txn");
6084
0
            return -1;
6085
0
        }
6086
6087
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6088
20
        restore_job_keys.push_back(k);
6089
6090
20
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6091
20
                  << " tablet_id=" << tablet_id;
6092
20
        return 0;
6093
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
5983
41
    auto recycle_func = [&, this](std::string_view k, std::string_view v) -> int {
5984
41
        ++num_scanned;
5985
41
        RestoreJobCloudPB restore_job_pb;
5986
41
        if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
5987
0
            LOG_WARNING("malformed recycle partition value").tag("key", hex(k));
5988
0
            return -1;
5989
0
        }
5990
41
        int64_t expiration =
5991
41
                calculate_restore_job_expired_time(instance_id_, restore_job_pb, &earlest_ts);
5992
41
        VLOG_DEBUG << "recycle restore job scan, key=" << hex(k) << " num_scanned=" << num_scanned
5993
0
                   << " num_expired=" << num_expired << " expiration time=" << expiration
5994
0
                   << " job expiration=" << restore_job_pb.expired_at_s()
5995
0
                   << " ctime=" << restore_job_pb.ctime_s() << " mtime=" << restore_job_pb.mtime_s()
5996
0
                   << " state=" << restore_job_pb.state();
5997
41
        int64_t current_time = ::time(nullptr);
5998
41
        if (current_time < expiration) { // not expired
5999
0
            return 0;
6000
0
        }
6001
41
        ++num_expired;
6002
6003
41
        int64_t tablet_id = restore_job_pb.tablet_id();
6004
41
        LOG(INFO) << "begin to recycle expired restore jobs, instance_id=" << instance_id_
6005
41
                  << " restore_job_pb=" << restore_job_pb.DebugString();
6006
6007
41
        std::unique_ptr<Transaction> txn;
6008
41
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6009
41
        if (err != TxnErrorCode::TXN_OK) {
6010
0
            LOG_WARNING("failed to recycle restore job")
6011
0
                    .tag("err", err)
6012
0
                    .tag("tablet id", tablet_id)
6013
0
                    .tag("instance_id", instance_id_)
6014
0
                    .tag("reason", "failed to create txn");
6015
0
            return -1;
6016
0
        }
6017
6018
41
        std::string val;
6019
41
        err = txn->get(k, &val);
6020
41
        if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) { // maybe recycled, skip it
6021
0
            LOG_INFO("restore job {} has been recycled", tablet_id);
6022
0
            return 0;
6023
0
        }
6024
41
        if (err != TxnErrorCode::TXN_OK) {
6025
0
            LOG_WARNING("failed to get kv");
6026
0
            return -1;
6027
0
        }
6028
41
        restore_job_pb.Clear();
6029
41
        if (!restore_job_pb.ParseFromString(val)) {
6030
0
            LOG_WARNING("malformed recycle restore job value").tag("key", hex(k));
6031
0
            return -1;
6032
0
        }
6033
6034
        // PREPARED or COMMITTED, change state to DROPPED and return
6035
41
        if (restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
6036
41
            restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) {
6037
0
            restore_job_pb.set_state(RestoreJobCloudPB::DROPPED);
6038
0
            restore_job_pb.set_need_recycle_data(true);
6039
0
            txn->put(k, restore_job_pb.SerializeAsString());
6040
0
            err = txn->commit();
6041
0
            if (err != TxnErrorCode::TXN_OK) {
6042
0
                LOG_WARNING("failed to commit txn: {}", err);
6043
0
                return -1;
6044
0
            }
6045
0
            num_aborted++;
6046
0
            return 0;
6047
0
        }
6048
6049
        // Change state to RECYCLING
6050
41
        if (restore_job_pb.state() != RestoreJobCloudPB::RECYCLING) {
6051
21
            restore_job_pb.set_state(RestoreJobCloudPB::RECYCLING);
6052
21
            txn->put(k, restore_job_pb.SerializeAsString());
6053
21
            err = txn->commit();
6054
21
            if (err != TxnErrorCode::TXN_OK) {
6055
0
                LOG_WARNING("failed to commit txn: {}", err);
6056
0
                return -1;
6057
0
            }
6058
21
            return 0;
6059
21
        }
6060
6061
20
        std::string restore_job_rs_key0 = job_restore_rowset_key({instance_id_, tablet_id, 0});
6062
20
        std::string restore_job_rs_key1 = job_restore_rowset_key({instance_id_, tablet_id + 1, 0});
6063
6064
        // Recycle all data associated with the restore job.
6065
        // This includes rowsets, segments, and related resources.
6066
20
        bool need_recycle_data = restore_job_pb.need_recycle_data();
6067
20
        if (need_recycle_data && recycle_tablet(tablet_id, metrics_context) != 0) {
6068
0
            LOG_WARNING("failed to recycle tablet")
6069
0
                    .tag("tablet_id", tablet_id)
6070
0
                    .tag("instance_id", instance_id_);
6071
0
            return -1;
6072
0
        }
6073
6074
        // delete all restore job rowset kv
6075
20
        txn->remove(restore_job_rs_key0, restore_job_rs_key1);
6076
6077
20
        err = txn->commit();
6078
20
        if (err != TxnErrorCode::TXN_OK) {
6079
0
            LOG_WARNING("failed to recycle tablet restore job rowset kv")
6080
0
                    .tag("err", err)
6081
0
                    .tag("tablet id", tablet_id)
6082
0
                    .tag("instance_id", instance_id_)
6083
0
                    .tag("reason", "failed to commit txn");
6084
0
            return -1;
6085
0
        }
6086
6087
20
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
6088
20
        restore_job_keys.push_back(k);
6089
6090
        LOG(INFO) << "finish to recycle expired restore job, key=" << hex(k)
6091
20
                  << " tablet_id=" << tablet_id;
6092
20
        return 0;
6093
20
    };
6094
6095
13
    auto loop_done = [&restore_job_keys, &metrics_context, &num_scanned, &num_expired,
6096
13
                      &num_recycled, this]() -> int {
6097
3
        DORIS_CLOUD_DEFER {
6098
3
            metrics_context.kv_scanned_num.set(num_scanned);
6099
3
            metrics_context.kv_expired_num.set(num_expired);
6100
3
            metrics_context.kv_recycled_num.set(num_recycled);
6101
3
            metrics_context.update_metrics();
6102
3
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6097
3
        DORIS_CLOUD_DEFER {
6098
3
            metrics_context.kv_scanned_num.set(num_scanned);
6099
3
            metrics_context.kv_expired_num.set(num_expired);
6100
3
            metrics_context.kv_recycled_num.set(num_recycled);
6101
3
            metrics_context.update_metrics();
6102
3
        };
6103
3
        if (restore_job_keys.empty()) return 0;
6104
1
        DORIS_CLOUD_DEFER {
6105
1
            restore_job_keys.clear();
6106
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE0_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
6104
1
        DORIS_CLOUD_DEFER {
6105
1
            restore_job_keys.clear();
6106
1
        };
6107
6108
1
        std::unique_ptr<Transaction> txn;
6109
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6110
1
        if (err != TxnErrorCode::TXN_OK) {
6111
0
            LOG_WARNING("failed to recycle restore job")
6112
0
                    .tag("err", err)
6113
0
                    .tag("instance_id", instance_id_)
6114
0
                    .tag("reason", "failed to create txn");
6115
0
            return -1;
6116
0
        }
6117
20
        for (auto& k : restore_job_keys) {
6118
20
            txn->remove(k);
6119
20
        }
6120
1
        err = txn->commit();
6121
1
        if (err != TxnErrorCode::TXN_OK) {
6122
0
            LOG_WARNING("failed to recycle restore job")
6123
0
                    .tag("err", err)
6124
0
                    .tag("instance_id", instance_id_)
6125
0
                    .tag("reason", "failed to commit txn");
6126
0
            return -1;
6127
0
        }
6128
        // Count after the restore job KV keys are successfully deleted.
6129
1
        num_recycled += restore_job_keys.size();
6130
1
        return 0;
6131
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler20recycle_restore_jobsEvENK3$_1clEv
Line
Count
Source
6096
3
                      &num_recycled, this]() -> int {
6097
3
        DORIS_CLOUD_DEFER {
6098
3
            metrics_context.kv_scanned_num.set(num_scanned);
6099
3
            metrics_context.kv_expired_num.set(num_expired);
6100
3
            metrics_context.kv_recycled_num.set(num_recycled);
6101
3
            metrics_context.update_metrics();
6102
3
        };
6103
3
        if (restore_job_keys.empty()) return 0;
6104
1
        DORIS_CLOUD_DEFER {
6105
1
            restore_job_keys.clear();
6106
1
        };
6107
6108
1
        std::unique_ptr<Transaction> txn;
6109
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6110
1
        if (err != TxnErrorCode::TXN_OK) {
6111
0
            LOG_WARNING("failed to recycle restore job")
6112
0
                    .tag("err", err)
6113
0
                    .tag("instance_id", instance_id_)
6114
0
                    .tag("reason", "failed to create txn");
6115
0
            return -1;
6116
0
        }
6117
20
        for (auto& k : restore_job_keys) {
6118
20
            txn->remove(k);
6119
20
        }
6120
1
        err = txn->commit();
6121
1
        if (err != TxnErrorCode::TXN_OK) {
6122
0
            LOG_WARNING("failed to recycle restore job")
6123
0
                    .tag("err", err)
6124
0
                    .tag("instance_id", instance_id_)
6125
0
                    .tag("reason", "failed to commit txn");
6126
0
            return -1;
6127
0
        }
6128
        // Count after the restore job KV keys are successfully deleted.
6129
1
        num_recycled += restore_job_keys.size();
6130
1
        return 0;
6131
1
    };
6132
6133
13
    return scan_and_recycle(restore_job_key0, restore_job_key1, std::move(recycle_func),
6134
13
                            std::move(loop_done));
6135
13
}
6136
6137
11
int InstanceRecycler::recycle_versioned_rowsets() {
6138
11
    const std::string task_name = "recycle_rowsets";
6139
11
    int64_t num_scanned = 0;
6140
11
    int64_t num_expired = 0;
6141
11
    int64_t num_prepare = 0;
6142
11
    int64_t num_compacted = 0;
6143
11
    int64_t num_empty_rowset = 0;
6144
11
    size_t total_rowset_key_size = 0;
6145
11
    size_t total_rowset_value_size = 0;
6146
11
    size_t expired_rowset_size = 0;
6147
11
    std::atomic_long num_recycled = 0;
6148
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6149
6150
11
    RecycleRowsetKeyInfo recyc_rs_key_info0 {instance_id_, 0, ""};
6151
11
    RecycleRowsetKeyInfo recyc_rs_key_info1 {instance_id_, INT64_MAX, ""};
6152
11
    std::string recyc_rs_key0;
6153
11
    std::string recyc_rs_key1;
6154
11
    recycle_rowset_key(recyc_rs_key_info0, &recyc_rs_key0);
6155
11
    recycle_rowset_key(recyc_rs_key_info1, &recyc_rs_key1);
6156
6157
11
    LOG_WARNING("begin to recycle rowsets").tag("instance_id", instance_id_);
6158
6159
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6160
11
    register_recycle_task(task_name, start_time);
6161
6162
11
    DORIS_CLOUD_DEFER {
6163
11
        metrics_context.kv_scanned_num.set(num_scanned);
6164
11
        metrics_context.kv_expired_num.set(num_expired);
6165
11
        metrics_context.kv_recycled_num.set(num_recycled);
6166
11
        unregister_recycle_task(task_name);
6167
11
        int64_t cost =
6168
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6169
11
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6170
11
                .tag("instance_id", instance_id_)
6171
11
                .tag("num_scanned", num_scanned)
6172
11
                .tag("num_expired", num_expired)
6173
11
                .tag("num_recycled", num_recycled)
6174
11
                .tag("num_recycled.prepare", num_prepare)
6175
11
                .tag("num_recycled.compacted", num_compacted)
6176
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6177
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6178
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6179
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6180
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_0clEv
Line
Count
Source
6162
11
    DORIS_CLOUD_DEFER {
6163
11
        metrics_context.kv_scanned_num.set(num_scanned);
6164
11
        metrics_context.kv_expired_num.set(num_expired);
6165
11
        metrics_context.kv_recycled_num.set(num_recycled);
6166
11
        unregister_recycle_task(task_name);
6167
11
        int64_t cost =
6168
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6169
        LOG_WARNING("recycle rowsets finished, cost={}s", cost)
6170
11
                .tag("instance_id", instance_id_)
6171
11
                .tag("num_scanned", num_scanned)
6172
11
                .tag("num_expired", num_expired)
6173
11
                .tag("num_recycled", num_recycled)
6174
11
                .tag("num_recycled.prepare", num_prepare)
6175
11
                .tag("num_recycled.compacted", num_compacted)
6176
11
                .tag("num_recycled.empty_rowset", num_empty_rowset)
6177
11
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6178
11
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6179
11
                .tag("expired_rowset_meta_size", expired_rowset_size);
6180
11
    };
6181
6182
11
    std::vector<std::string> orphan_rowset_keys;
6183
6184
    // Store keys of rowset recycled by background workers
6185
11
    std::mutex async_recycled_rowset_keys_mutex;
6186
11
    std::vector<std::string> async_recycled_rowset_keys;
6187
11
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6188
11
            config::instance_recycler_worker_pool_size, "recycle_rowsets");
6189
11
    worker_pool->start();
6190
11
    auto delete_rowset_data_by_prefix = [&](std::string key, const std::string& resource_id,
6191
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6192
        // Try to delete rowset data in background thread
6193
400
        int ret = worker_pool->submit_with_timeout(
6194
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6195
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6196
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6197
400
                        return;
6198
400
                    }
6199
                    // The async recycled rowsets are staled format or has not been used,
6200
                    // so we don't need to check the rowset ref count key.
6201
0
                    std::vector<std::string> keys;
6202
0
                    {
6203
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6204
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6205
0
                        if (async_recycled_rowset_keys.size() > 100) {
6206
0
                            keys.swap(async_recycled_rowset_keys);
6207
0
                        }
6208
0
                    }
6209
0
                    if (keys.empty()) return;
6210
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6211
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6212
0
                                     << instance_id_;
6213
0
                    } else {
6214
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6215
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6216
0
                                           num_recycled, start_time);
6217
0
                    }
6218
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
6194
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6195
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6196
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6197
400
                        return;
6198
400
                    }
6199
                    // The async recycled rowsets are staled format or has not been used,
6200
                    // so we don't need to check the rowset ref count key.
6201
0
                    std::vector<std::string> keys;
6202
0
                    {
6203
0
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6204
0
                        async_recycled_rowset_keys.push_back(std::move(key));
6205
0
                        if (async_recycled_rowset_keys.size() > 100) {
6206
0
                            keys.swap(async_recycled_rowset_keys);
6207
0
                        }
6208
0
                    }
6209
0
                    if (keys.empty()) return;
6210
0
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6211
0
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6212
0
                                     << instance_id_;
6213
0
                    } else {
6214
0
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6215
0
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6216
0
                                           num_recycled, start_time);
6217
0
                    }
6218
0
                },
6219
400
                0);
6220
400
        if (ret == 0) return 0;
6221
        // Submit task failed, delete rowset data in current thread
6222
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6223
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6224
0
            return -1;
6225
0
        }
6226
0
        orphan_rowset_keys.push_back(std::move(key));
6227
0
        return 0;
6228
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
6191
400
                                            int64_t tablet_id, const std::string& rowset_id) {
6192
        // Try to delete rowset data in background thread
6193
400
        int ret = worker_pool->submit_with_timeout(
6194
400
                [&, resource_id, tablet_id, rowset_id, key]() mutable {
6195
400
                    if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6196
400
                        LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6197
400
                        return;
6198
400
                    }
6199
                    // The async recycled rowsets are staled format or has not been used,
6200
                    // so we don't need to check the rowset ref count key.
6201
400
                    std::vector<std::string> keys;
6202
400
                    {
6203
400
                        std::lock_guard lock(async_recycled_rowset_keys_mutex);
6204
400
                        async_recycled_rowset_keys.push_back(std::move(key));
6205
400
                        if (async_recycled_rowset_keys.size() > 100) {
6206
400
                            keys.swap(async_recycled_rowset_keys);
6207
400
                        }
6208
400
                    }
6209
400
                    if (keys.empty()) return;
6210
400
                    if (txn_remove(txn_kv_.get(), keys) != 0) {
6211
400
                        LOG(WARNING) << "failed to delete recycle rowset kv, instance_id="
6212
400
                                     << instance_id_;
6213
400
                    } else {
6214
400
                        num_recycled.fetch_add(keys.size(), std::memory_order_relaxed);
6215
400
                        check_recycle_task(instance_id_, "recycle_rowsets", num_scanned,
6216
400
                                           num_recycled, start_time);
6217
400
                    }
6218
400
                },
6219
400
                0);
6220
400
        if (ret == 0) return 0;
6221
        // Submit task failed, delete rowset data in current thread
6222
0
        if (delete_rowset_data(resource_id, tablet_id, rowset_id) != 0) {
6223
0
            LOG(WARNING) << "failed to delete rowset data, key=" << hex(key);
6224
0
            return -1;
6225
0
        }
6226
0
        orphan_rowset_keys.push_back(std::move(key));
6227
0
        return 0;
6228
0
    };
6229
6230
11
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6231
6232
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6233
2.01k
        ++num_scanned;
6234
2.01k
        total_rowset_key_size += k.size();
6235
2.01k
        total_rowset_value_size += v.size();
6236
2.01k
        RecycleRowsetPB rowset;
6237
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6238
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6239
0
            return -1;
6240
0
        }
6241
6242
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6243
6244
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6245
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6246
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6247
2.01k
        int64_t current_time = ::time(nullptr);
6248
2.01k
        if (current_time < final_expiration) { // not expired
6249
0
            return 0;
6250
0
        }
6251
2.01k
        ++num_expired;
6252
2.01k
        expired_rowset_size += v.size();
6253
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6254
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6255
                // in old version, keep this key-value pair and it needs to be checked manually
6256
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6257
0
                return -1;
6258
0
            }
6259
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6260
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6261
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6262
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6263
0
                orphan_rowset_keys.emplace_back(k);
6264
0
                return -1;
6265
0
            }
6266
            // decode rowset_id
6267
0
            auto k1 = k;
6268
0
            k1.remove_prefix(1);
6269
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6270
0
            decode_key(&k1, &out);
6271
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6272
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6273
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6274
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6275
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6276
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6277
0
                return -1;
6278
0
            }
6279
0
            return 0;
6280
0
        }
6281
        // TODO(plat1ko): check rowset not referenced
6282
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6283
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6284
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6285
0
                LOG_INFO("recycle rowset that has empty resource id");
6286
0
            } else {
6287
                // other situations, keep this key-value pair and it needs to be checked manually
6288
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6289
0
                return -1;
6290
0
            }
6291
0
        }
6292
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6293
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6294
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6295
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6296
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6297
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6298
2.01k
                  << " rowset_meta_size=" << v.size()
6299
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6300
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6301
            // unable to calculate file path, can only be deleted by rowset id prefix
6302
400
            num_prepare += 1;
6303
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6304
400
                                             rowset_meta->tablet_id(),
6305
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6306
0
                return -1;
6307
0
            }
6308
1.61k
        } else {
6309
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6310
1.61k
            worker_pool->submit(
6311
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6312
                        // The load & compact rowset keys are recycled during recycling operation logs.
6313
1.61k
                        RowsetDeleteTask task;
6314
1.61k
                        task.rowset_meta = rowset_meta;
6315
1.61k
                        task.recycle_rowset_key = k;
6316
1.61k
                        if (recycle_rowset_meta_and_data(task, metrics_context) != 0) {
6317
1.60k
                            return;
6318
1.60k
                        }
6319
13
                        num_compacted += is_compacted;
6320
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6321
13
                        if (rowset_meta.num_segments() == 0) {
6322
0
                            ++num_empty_rowset;
6323
0
                        }
6324
13
                    });
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
6311
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6312
                        // The load & compact rowset keys are recycled during recycling operation logs.
6313
1.61k
                        RowsetDeleteTask task;
6314
1.61k
                        task.rowset_meta = rowset_meta;
6315
1.61k
                        task.recycle_rowset_key = k;
6316
1.61k
                        if (recycle_rowset_meta_and_data(task, metrics_context) != 0) {
6317
1.60k
                            return;
6318
1.60k
                        }
6319
13
                        num_compacted += is_compacted;
6320
13
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6321
13
                        if (rowset_meta.num_segments() == 0) {
6322
0
                            ++num_empty_rowset;
6323
0
                        }
6324
13
                    });
6325
1.61k
        }
6326
2.01k
        return 0;
6327
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
6232
2.01k
    auto handle_rowset_kv = [&, this](std::string_view k, std::string_view v) -> int {
6233
2.01k
        ++num_scanned;
6234
2.01k
        total_rowset_key_size += k.size();
6235
2.01k
        total_rowset_value_size += v.size();
6236
2.01k
        RecycleRowsetPB rowset;
6237
2.01k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6238
0
            LOG_WARNING("malformed recycle rowset").tag("key", hex(k));
6239
0
            return -1;
6240
0
        }
6241
6242
2.01k
        int final_expiration = calculate_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6243
6244
2.01k
        VLOG_DEBUG << "recycle rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6245
0
                   << " num_expired=" << num_expired << " expiration=" << final_expiration
6246
0
                   << " RecycleRowsetPB=" << rowset.ShortDebugString();
6247
2.01k
        int64_t current_time = ::time(nullptr);
6248
2.01k
        if (current_time < final_expiration) { // not expired
6249
0
            return 0;
6250
0
        }
6251
2.01k
        ++num_expired;
6252
2.01k
        expired_rowset_size += v.size();
6253
2.01k
        if (!rowset.has_type()) {                         // old version `RecycleRowsetPB`
6254
0
            if (!rowset.has_resource_id()) [[unlikely]] { // impossible
6255
                // in old version, keep this key-value pair and it needs to be checked manually
6256
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6257
0
                return -1;
6258
0
            }
6259
0
            if (rowset.resource_id().empty()) [[unlikely]] {
6260
                // old version `RecycleRowsetPB` may has empty resource_id, just remove the kv.
6261
0
                LOG(INFO) << "delete the recycle rowset kv that has empty resource_id, key="
6262
0
                          << hex(k) << " value=" << proto_to_json(rowset);
6263
0
                orphan_rowset_keys.emplace_back(k);
6264
0
                return -1;
6265
0
            }
6266
            // decode rowset_id
6267
0
            auto k1 = k;
6268
0
            k1.remove_prefix(1);
6269
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6270
0
            decode_key(&k1, &out);
6271
            // 0x01 "recycle" ${instance_id} "rowset" ${tablet_id} ${rowset_id} -> RecycleRowsetPB
6272
0
            const auto& rowset_id = std::get<std::string>(std::get<0>(out[4]));
6273
0
            LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6274
0
                      << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset_id;
6275
0
            if (delete_rowset_data_by_prefix(std::string(k), rowset.resource_id(),
6276
0
                                             rowset.tablet_id(), rowset_id) != 0) {
6277
0
                return -1;
6278
0
            }
6279
0
            return 0;
6280
0
        }
6281
        // TODO(plat1ko): check rowset not referenced
6282
2.01k
        auto rowset_meta = rowset.mutable_rowset_meta();
6283
2.01k
        if (!rowset_meta->has_resource_id()) [[unlikely]] { // impossible
6284
0
            if (rowset.type() != RecycleRowsetPB::PREPARE && rowset_meta->num_segments() == 0) {
6285
0
                LOG_INFO("recycle rowset that has empty resource id");
6286
0
            } else {
6287
                // other situations, keep this key-value pair and it needs to be checked manually
6288
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", hex(k));
6289
0
                return -1;
6290
0
            }
6291
0
        }
6292
2.01k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6293
2.01k
                  << " tablet_id=" << rowset_meta->tablet_id()
6294
2.01k
                  << " rowset_id=" << rowset_meta->rowset_id_v2() << " version=["
6295
2.01k
                  << rowset_meta->start_version() << '-' << rowset_meta->end_version()
6296
2.01k
                  << "] txn_id=" << rowset_meta->txn_id()
6297
2.01k
                  << " type=" << RecycleRowsetPB_Type_Name(rowset.type())
6298
2.01k
                  << " rowset_meta_size=" << v.size()
6299
2.01k
                  << " creation_time=" << rowset_meta->creation_time();
6300
2.01k
        if (rowset.type() == RecycleRowsetPB::PREPARE) {
6301
            // unable to calculate file path, can only be deleted by rowset id prefix
6302
400
            num_prepare += 1;
6303
400
            if (delete_rowset_data_by_prefix(std::string(k), rowset_meta->resource_id(),
6304
400
                                             rowset_meta->tablet_id(),
6305
400
                                             rowset_meta->rowset_id_v2()) != 0) {
6306
0
                return -1;
6307
0
            }
6308
1.61k
        } else {
6309
1.61k
            bool is_compacted = rowset.type() == RecycleRowsetPB::COMPACT;
6310
1.61k
            worker_pool->submit(
6311
1.61k
                    [&, is_compacted, k = std::string(k), rowset_meta = std::move(*rowset_meta)]() {
6312
                        // The load & compact rowset keys are recycled during recycling operation logs.
6313
1.61k
                        RowsetDeleteTask task;
6314
1.61k
                        task.rowset_meta = rowset_meta;
6315
1.61k
                        task.recycle_rowset_key = k;
6316
1.61k
                        if (recycle_rowset_meta_and_data(task, metrics_context) != 0) {
6317
1.61k
                            return;
6318
1.61k
                        }
6319
1.61k
                        num_compacted += is_compacted;
6320
1.61k
                        num_recycled.fetch_add(1, std::memory_order_relaxed);
6321
1.61k
                        if (rowset_meta.num_segments() == 0) {
6322
1.61k
                            ++num_empty_rowset;
6323
1.61k
                        }
6324
1.61k
                    });
6325
1.61k
        }
6326
2.01k
        return 0;
6327
2.01k
    };
6328
6329
11
    auto loop_done = [&]() -> int {
6330
6
        DORIS_CLOUD_DEFER {
6331
6
            metrics_context.kv_scanned_num.set(num_scanned);
6332
6
            metrics_context.kv_expired_num.set(num_expired);
6333
6
            metrics_context.kv_recycled_num.set(num_recycled);
6334
6
            metrics_context.update_metrics();
6335
6
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEvENKUlvE_clEv
Line
Count
Source
6330
6
        DORIS_CLOUD_DEFER {
6331
6
            metrics_context.kv_scanned_num.set(num_scanned);
6332
6
            metrics_context.kv_expired_num.set(num_expired);
6333
6
            metrics_context.kv_recycled_num.set(num_recycled);
6334
6
            metrics_context.update_metrics();
6335
6
        };
6336
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6337
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6338
6
        } else {
6339
6
            num_recycled.fetch_add(orphan_rowset_keys.size(), std::memory_order_relaxed);
6340
6
        }
6341
6
        orphan_rowset_keys.clear();
6342
6
        return 0;
6343
6
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_versioned_rowsetsEvENK3$_3clEv
Line
Count
Source
6329
6
    auto loop_done = [&]() -> int {
6330
6
        DORIS_CLOUD_DEFER {
6331
6
            metrics_context.kv_scanned_num.set(num_scanned);
6332
6
            metrics_context.kv_expired_num.set(num_expired);
6333
6
            metrics_context.kv_recycled_num.set(num_recycled);
6334
6
            metrics_context.update_metrics();
6335
6
        };
6336
6
        if (txn_remove(txn_kv_.get(), orphan_rowset_keys)) {
6337
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6338
6
        } else {
6339
6
            num_recycled.fetch_add(orphan_rowset_keys.size(), std::memory_order_relaxed);
6340
6
        }
6341
6
        orphan_rowset_keys.clear();
6342
6
        return 0;
6343
6
    };
6344
6345
    // recycle_func and loop_done for scan and recycle
6346
11
    int ret = scan_and_recycle(recyc_rs_key0, recyc_rs_key1, std::move(handle_rowset_kv),
6347
11
                               std::move(loop_done));
6348
6349
11
    worker_pool->stop();
6350
6351
11
    if (!async_recycled_rowset_keys.empty()) {
6352
0
        if (txn_remove(txn_kv_.get(), async_recycled_rowset_keys) != 0) {
6353
0
            LOG(WARNING) << "failed to delete recycle rowset kv, instance_id=" << instance_id_;
6354
0
            return -1;
6355
0
        } else {
6356
0
            num_recycled.fetch_add(async_recycled_rowset_keys.size(), std::memory_order_relaxed);
6357
0
        }
6358
0
    }
6359
6360
11
    return ret;
6361
11
}
6362
6363
int InstanceRecycler::recycle_rowset_meta_and_data(const RowsetDeleteTask& task,
6364
1.61k
                                                   RecyclerMetricsContext& metrics_context) {
6365
1.61k
    constexpr int MAX_RETRY = 10;
6366
1.61k
    const RowsetMetaCloudPB& rowset_meta = task.rowset_meta;
6367
1.61k
    int64_t tablet_id = rowset_meta.tablet_id();
6368
1.61k
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
6369
1.61k
    std::string_view reference_instance_id = instance_id_;
6370
1.61k
    if (rowset_meta.has_reference_instance_id()) {
6371
8
        reference_instance_id = rowset_meta.reference_instance_id();
6372
8
    }
6373
6374
1.61k
    AnnotateTag tablet_id_tag("tablet_id", tablet_id);
6375
1.61k
    AnnotateTag rowset_id_tag("rowset_id", rowset_id);
6376
1.61k
    AnnotateTag rowset_key_tag("recycle_rowset_key", hex(task.recycle_rowset_key));
6377
1.61k
    AnnotateTag instance_id_tag("instance_id", instance_id_);
6378
1.61k
    AnnotateTag ref_instance_id_tag("ref_instance_id", reference_instance_id);
6379
1.61k
    for (int i = 0; i < MAX_RETRY; ++i) {
6380
1.61k
        std::unique_ptr<Transaction> txn;
6381
1.61k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6382
1.61k
        if (err != TxnErrorCode::TXN_OK) {
6383
0
            LOG_WARNING("failed to create txn").tag("err", err);
6384
0
            return -1;
6385
0
        }
6386
6387
1.61k
        std::string rowset_ref_count_key =
6388
1.61k
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
6389
1.61k
        int64_t ref_count = 0;
6390
1.61k
        {
6391
1.61k
            std::string value;
6392
1.61k
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
6393
1.61k
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
6394
                // This is the old version rowset, we could recycle it directly.
6395
1.60k
                ref_count = 1;
6396
1.60k
            } else if (err != TxnErrorCode::TXN_OK) {
6397
0
                LOG_WARNING("failed to get rowset ref count key").tag("err", err);
6398
0
                return -1;
6399
11
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
6400
0
                LOG_WARNING("failed to decode rowset data ref count").tag("value", hex(value));
6401
0
                return -1;
6402
0
            }
6403
1.61k
        }
6404
6405
1.61k
        int64_t recycled_bytes = 0;
6406
1.61k
        if (ref_count == 1) {
6407
            // It would not be added since it is recycling.
6408
1.61k
            if (delete_rowset_data(rowset_meta) != 0) {
6409
1.60k
                LOG_WARNING("failed to delete rowset data");
6410
1.60k
                return -1;
6411
1.60k
            }
6412
6413
10
            recycled_bytes = rowset_meta.total_disk_size();
6414
6415
            // Reset the transaction to avoid timeout.
6416
10
            err = txn_kv_->create_txn(&txn);
6417
10
            if (err != TxnErrorCode::TXN_OK) {
6418
0
                LOG_WARNING("failed to create txn").tag("err", err);
6419
0
                return -1;
6420
0
            }
6421
10
            txn->remove(rowset_ref_count_key);
6422
10
            LOG_INFO("delete rowset data ref count key")
6423
10
                    .tag("txn_id", rowset_meta.txn_id())
6424
10
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6425
6426
10
            std::string dbm_start_key =
6427
10
                    meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
6428
10
            std::string dbm_end_key = meta_delete_bitmap_key(
6429
10
                    {reference_instance_id, tablet_id, rowset_id,
6430
10
                     std::numeric_limits<int64_t>::max(), std::numeric_limits<int64_t>::max()});
6431
10
            txn->remove(dbm_start_key, dbm_end_key);
6432
10
            LOG_INFO("remove delete bitmap kv")
6433
10
                    .tag("begin", hex(dbm_start_key))
6434
10
                    .tag("end", hex(dbm_end_key));
6435
6436
10
            std::string versioned_dbm_start_key = versioned::meta_delete_bitmap_key(
6437
10
                    {reference_instance_id, tablet_id, rowset_id});
6438
10
            std::string versioned_dbm_end_key = versioned_dbm_start_key;
6439
10
            encode_int64(INT64_MAX, &versioned_dbm_end_key);
6440
10
            txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
6441
10
            LOG_INFO("remove versioned delete bitmap kv")
6442
10
                    .tag("begin", hex(versioned_dbm_start_key))
6443
10
                    .tag("end", hex(versioned_dbm_end_key));
6444
10
        } else {
6445
            // Decrease the rowset ref count.
6446
            //
6447
            // The read conflict range will protect the rowset ref count key, if any conflict happens,
6448
            // we will retry and check whether the rowset ref count is 1 and the data need to be deleted.
6449
3
            txn->atomic_add(rowset_ref_count_key, -1);
6450
3
            LOG_INFO("decrease rowset data ref count")
6451
3
                    .tag("txn_id", rowset_meta.txn_id())
6452
3
                    .tag("ref_count", ref_count - 1)
6453
3
                    .tag("ref_count_key", hex(rowset_ref_count_key));
6454
3
        }
6455
6456
13
        if (!task.versioned_rowset_key.empty()) {
6457
0
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
6458
0
                                                          task.versionstamp);
6459
0
            LOG_INFO("remove versioned meta rowset key").tag("key", hex(task.versioned_rowset_key));
6460
0
        }
6461
6462
13
        if (!task.non_versioned_rowset_key.empty()) {
6463
0
            txn->remove(task.non_versioned_rowset_key);
6464
0
            LOG_INFO("remove non versioned rowset key")
6465
0
                    .tag("key", hex(task.non_versioned_rowset_key));
6466
0
        }
6467
6468
        // empty when recycle ref rowsets for deleted instance
6469
13
        if (!task.recycle_rowset_key.empty()) {
6470
13
            txn->remove(task.recycle_rowset_key);
6471
13
            LOG_INFO("remove recycle rowset key").tag("key", hex(task.recycle_rowset_key));
6472
13
        }
6473
6474
13
        err = txn->commit();
6475
13
        if (err == TxnErrorCode::TXN_CONFLICT) { // unlikely
6476
            // The rowset ref count key has been changed, we need to retry.
6477
0
            VLOG_DEBUG << "decrease rowset ref count but txn conflict, retry"
6478
0
                       << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
6479
0
                       << ", ref_count=" << ref_count << ", retry=" << i;
6480
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6481
0
            continue;
6482
13
        } else if (err != TxnErrorCode::TXN_OK) {
6483
0
            LOG_WARNING("failed to recycle rowset meta and data").tag("err", err);
6484
0
            return -1;
6485
0
        }
6486
13
        metrics_context.kv_recycled_bytes += recycled_bytes;
6487
13
        LOG_INFO("recycle rowset meta and data success");
6488
13
        return 0;
6489
13
    }
6490
0
    LOG_WARNING("failed to recycle rowset meta and data after retry")
6491
0
            .tag("tablet_id", tablet_id)
6492
0
            .tag("rowset_id", rowset_id)
6493
0
            .tag("retry", MAX_RETRY);
6494
0
    return -1;
6495
1.61k
}
6496
6497
37
int InstanceRecycler::recycle_tmp_rowsets() {
6498
37
    const std::string task_name = "recycle_tmp_rowsets";
6499
37
    int64_t num_scanned = 0;
6500
37
    int64_t num_expired = 0;
6501
37
    std::atomic_long num_recycled = 0;
6502
37
    size_t expired_rowset_size = 0;
6503
37
    size_t total_rowset_key_size = 0;
6504
37
    size_t total_rowset_value_size = 0;
6505
37
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6506
6507
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info0 {instance_id_, 0, 0};
6508
37
    MetaRowsetTmpKeyInfo tmp_rs_key_info1 {instance_id_, INT64_MAX, 0};
6509
37
    std::string tmp_rs_key0;
6510
37
    std::string tmp_rs_key1;
6511
37
    meta_rowset_tmp_key(tmp_rs_key_info0, &tmp_rs_key0);
6512
37
    meta_rowset_tmp_key(tmp_rs_key_info1, &tmp_rs_key1);
6513
6514
37
    LOG_WARNING("begin to recycle tmp rowsets").tag("instance_id", instance_id_);
6515
6516
37
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6517
37
    register_recycle_task(task_name, start_time);
6518
6519
37
    DORIS_CLOUD_DEFER {
6520
37
        metrics_context.kv_scanned_num.set(num_scanned);
6521
37
        metrics_context.kv_expired_num.set(num_expired);
6522
37
        metrics_context.kv_recycled_num.set(num_recycled);
6523
37
        unregister_recycle_task(task_name);
6524
37
        int64_t cost =
6525
37
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6526
37
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6527
37
                .tag("instance_id", instance_id_)
6528
37
                .tag("num_scanned", num_scanned)
6529
37
                .tag("num_expired", num_expired)
6530
37
                .tag("num_recycled", num_recycled)
6531
37
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6532
37
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6533
37
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6534
37
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6519
12
    DORIS_CLOUD_DEFER {
6520
12
        metrics_context.kv_scanned_num.set(num_scanned);
6521
12
        metrics_context.kv_expired_num.set(num_expired);
6522
12
        metrics_context.kv_recycled_num.set(num_recycled);
6523
12
        unregister_recycle_task(task_name);
6524
12
        int64_t cost =
6525
12
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6526
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6527
12
                .tag("instance_id", instance_id_)
6528
12
                .tag("num_scanned", num_scanned)
6529
12
                .tag("num_expired", num_expired)
6530
12
                .tag("num_recycled", num_recycled)
6531
12
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6532
12
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6533
12
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6534
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_0clEv
Line
Count
Source
6519
25
    DORIS_CLOUD_DEFER {
6520
25
        metrics_context.kv_scanned_num.set(num_scanned);
6521
25
        metrics_context.kv_expired_num.set(num_expired);
6522
25
        metrics_context.kv_recycled_num.set(num_recycled);
6523
25
        unregister_recycle_task(task_name);
6524
25
        int64_t cost =
6525
25
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6526
        LOG_WARNING("recycle tmp rowsets finished, cost={}s", cost)
6527
25
                .tag("instance_id", instance_id_)
6528
25
                .tag("num_scanned", num_scanned)
6529
25
                .tag("num_expired", num_expired)
6530
25
                .tag("num_recycled", num_recycled)
6531
25
                .tag("total_rowset_meta_key_size_scanned", total_rowset_key_size)
6532
25
                .tag("total_rowset_meta_value_size_scanned", total_rowset_value_size)
6533
25
                .tag("expired_rowset_meta_size_recycled", expired_rowset_size);
6534
25
    };
6535
6536
    // Store direct-delete keys separately from keys whose related txn or job must be aborted.
6537
37
    std::vector<std::string> tmp_rowset_keys;
6538
37
    std::vector<std::string> tmp_rowset_ref_count_keys;
6539
37
    std::vector<std::string> tmp_rowset_keys_to_mark_recycled;
6540
37
    std::vector<std::string> tmp_rowset_keys_to_abort;
6541
6542
    // rowset_id -> rowset_meta
6543
    // store tmp_rowset id and meta for statistics rs size when delete
6544
37
    std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets;
6545
37
    auto worker_pool = std::make_unique<SimpleThreadPool>(
6546
37
            config::instance_recycler_worker_pool_size, "recycle_tmp_rowsets");
6547
37
    worker_pool->start();
6548
6549
37
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6550
6551
37
    auto handle_rowset_kv = [&num_scanned, &num_expired, &tmp_rowset_keys, &expired_rowset_size,
6552
37
                             &total_rowset_key_size, &total_rowset_value_size, &earlest_ts,
6553
37
                             &tmp_rowset_keys_to_mark_recycled, &tmp_rowset_keys_to_abort, this,
6554
37
                             &metrics_context, &tmp_rowsets, &tmp_rowset_ref_count_keys](
6555
53.2k
                                    std::string_view k, std::string_view v) -> int {
6556
53.2k
        ++num_scanned;
6557
53.2k
        total_rowset_key_size += k.size();
6558
53.2k
        total_rowset_value_size += v.size();
6559
53.2k
        doris::RowsetMetaCloudPB rowset;
6560
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6561
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6562
0
            return -1;
6563
0
        }
6564
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6565
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6566
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6567
0
                   << " txn_expiration=" << rowset.txn_expiration()
6568
0
                   << " rowset_creation_time=" << rowset.creation_time();
6569
53.2k
        int64_t current_time = ::time(nullptr);
6570
53.2k
        if (current_time < expiration) { // not expired
6571
0
            return 0;
6572
0
        }
6573
53.2k
        ++num_expired;
6574
53.2k
        expired_rowset_size += v.size();
6575
53.2k
        if (!rowset.has_resource_id()) {
6576
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6577
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6578
0
                return -1;
6579
0
            }
6580
            // might be a delete pred rowset
6581
0
            tmp_rowset_keys.emplace_back(k);
6582
0
            return 0;
6583
0
        }
6584
6585
        // TODO(plat1ko): check rowset not referenced
6586
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6587
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6588
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6589
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6590
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6591
53.2k
                  << " num_expired=" << num_expired
6592
53.2k
                  << " task_type=" << metrics_context.operation_type;
6593
6594
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6595
16
            if (need_mark_rowset_as_recycled(rowset)) {
6596
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6597
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6598
9
                             "at next turn, instance_id="
6599
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6600
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6601
9
                return 0;
6602
9
            }
6603
16
        }
6604
6605
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6606
265
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6607
261
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6608
261
                             "instance_id="
6609
261
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6610
261
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6611
261
                tmp_rowset_keys_to_abort.emplace_back(k);
6612
261
                return 0;
6613
261
            }
6614
265
        }
6615
6616
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6617
        // Remove the rowset ref count key directly since it has not been used.
6618
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6619
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6620
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6621
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6622
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6623
6624
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6625
53.0k
        return 0;
6626
53.2k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6555
16
                                    std::string_view k, std::string_view v) -> int {
6556
16
        ++num_scanned;
6557
16
        total_rowset_key_size += k.size();
6558
16
        total_rowset_value_size += v.size();
6559
16
        doris::RowsetMetaCloudPB rowset;
6560
16
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6561
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6562
0
            return -1;
6563
0
        }
6564
16
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6565
16
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6566
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6567
0
                   << " txn_expiration=" << rowset.txn_expiration()
6568
0
                   << " rowset_creation_time=" << rowset.creation_time();
6569
16
        int64_t current_time = ::time(nullptr);
6570
16
        if (current_time < expiration) { // not expired
6571
0
            return 0;
6572
0
        }
6573
16
        ++num_expired;
6574
16
        expired_rowset_size += v.size();
6575
16
        if (!rowset.has_resource_id()) {
6576
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6577
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6578
0
                return -1;
6579
0
            }
6580
            // might be a delete pred rowset
6581
0
            tmp_rowset_keys.emplace_back(k);
6582
0
            return 0;
6583
0
        }
6584
6585
        // TODO(plat1ko): check rowset not referenced
6586
16
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6587
16
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6588
16
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6589
16
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6590
16
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6591
16
                  << " num_expired=" << num_expired
6592
16
                  << " task_type=" << metrics_context.operation_type;
6593
6594
16
        if (config::enable_mark_delete_rowset_before_recycle) {
6595
16
            if (need_mark_rowset_as_recycled(rowset)) {
6596
9
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6597
9
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6598
9
                             "at next turn, instance_id="
6599
9
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6600
9
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6601
9
                return 0;
6602
9
            }
6603
16
        }
6604
6605
7
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6606
7
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6607
3
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6608
3
                             "instance_id="
6609
3
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6610
3
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6611
3
                tmp_rowset_keys_to_abort.emplace_back(k);
6612
3
                return 0;
6613
3
            }
6614
7
        }
6615
6616
4
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6617
        // Remove the rowset ref count key directly since it has not been used.
6618
4
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6619
4
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6620
4
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6621
4
                  << "key=" << hex(rowset_ref_count_key);
6622
4
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6623
6624
4
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6625
4
        return 0;
6626
7
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6555
53.2k
                                    std::string_view k, std::string_view v) -> int {
6556
53.2k
        ++num_scanned;
6557
53.2k
        total_rowset_key_size += k.size();
6558
53.2k
        total_rowset_value_size += v.size();
6559
53.2k
        doris::RowsetMetaCloudPB rowset;
6560
53.2k
        if (!rowset.ParseFromArray(v.data(), v.size())) {
6561
0
            LOG_WARNING("malformed rowset meta").tag("key", hex(k));
6562
0
            return -1;
6563
0
        }
6564
53.2k
        int64_t expiration = calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
6565
53.2k
        VLOG_DEBUG << "recycle tmp rowset scan, key=" << hex(k) << " num_scanned=" << num_scanned
6566
0
                   << " num_expired=" << num_expired << " expiration=" << expiration
6567
0
                   << " txn_expiration=" << rowset.txn_expiration()
6568
0
                   << " rowset_creation_time=" << rowset.creation_time();
6569
53.2k
        int64_t current_time = ::time(nullptr);
6570
53.2k
        if (current_time < expiration) { // not expired
6571
0
            return 0;
6572
0
        }
6573
53.2k
        ++num_expired;
6574
53.2k
        expired_rowset_size += v.size();
6575
53.2k
        if (!rowset.has_resource_id()) {
6576
0
            if (rowset.num_segments() > 0) [[unlikely]] { // impossible
6577
0
                LOG_WARNING("rowset meta has empty resource id").tag("key", k);
6578
0
                return -1;
6579
0
            }
6580
            // might be a delete pred rowset
6581
0
            tmp_rowset_keys.emplace_back(k);
6582
0
            return 0;
6583
0
        }
6584
6585
        // TODO(plat1ko): check rowset not referenced
6586
53.2k
        LOG(INFO) << "delete rowset data, instance_id=" << instance_id_
6587
53.2k
                  << " tablet_id=" << rowset.tablet_id() << " rowset_id=" << rowset.rowset_id_v2()
6588
53.2k
                  << " version=[" << rowset.start_version() << '-' << rowset.end_version()
6589
53.2k
                  << "] txn_id=" << rowset.txn_id() << " rowset_meta_size=" << v.size()
6590
53.2k
                  << " creation_time=" << rowset.creation_time() << " num_scanned=" << num_scanned
6591
53.2k
                  << " num_expired=" << num_expired
6592
53.2k
                  << " task_type=" << metrics_context.operation_type;
6593
6594
53.2k
        if (config::enable_mark_delete_rowset_before_recycle) {
6595
0
            if (need_mark_rowset_as_recycled(rowset)) {
6596
0
                tmp_rowset_keys_to_mark_recycled.emplace_back(k);
6597
0
                LOG(INFO) << "rowset queued to mark as recycled, recycler will delete data and kv "
6598
0
                             "at next turn, instance_id="
6599
0
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6600
0
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6601
0
                return 0;
6602
0
            }
6603
0
        }
6604
6605
53.2k
        if (config::enable_abort_txn_and_job_for_delete_rowset_before_recycle) {
6606
258
            if (make_related_txn_or_job_abort_task(rowset).has_value()) {
6607
258
                LOG(INFO) << "rowset queued to abort related txn or job after current scan batch, "
6608
258
                             "instance_id="
6609
258
                          << instance_id_ << " tablet_id=" << rowset.tablet_id() << " version=["
6610
258
                          << rowset.start_version() << '-' << rowset.end_version() << "]";
6611
258
                tmp_rowset_keys_to_abort.emplace_back(k);
6612
258
                return 0;
6613
258
            }
6614
258
        }
6615
6616
53.0k
        tmp_rowset_keys.emplace_back(k.data(), k.size());
6617
        // Remove the rowset ref count key directly since it has not been used.
6618
53.0k
        std::string rowset_ref_count_key = versioned::data_rowset_ref_count_key(
6619
53.0k
                {instance_id_, rowset.tablet_id(), rowset.rowset_id_v2()});
6620
53.0k
        LOG(INFO) << "delete rowset ref count key, instance_id=" << instance_id_
6621
53.0k
                  << "key=" << hex(rowset_ref_count_key);
6622
53.0k
        tmp_rowset_ref_count_keys.push_back(rowset_ref_count_key);
6623
6624
53.0k
        tmp_rowsets.emplace(rowset.rowset_id_v2(), std::move(rowset));
6625
53.0k
        return 0;
6626
53.2k
    };
6627
6628
37
    auto loop_done = [&]() -> int {
6629
24
        DORIS_CLOUD_DEFER {
6630
24
            metrics_context.kv_scanned_num.set(num_scanned);
6631
24
            metrics_context.kv_expired_num.set(num_expired);
6632
24
            metrics_context.kv_recycled_num.set(num_recycled);
6633
24
            metrics_context.update_metrics();
6634
24
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6629
12
        DORIS_CLOUD_DEFER {
6630
12
            metrics_context.kv_scanned_num.set(num_scanned);
6631
12
            metrics_context.kv_expired_num.set(num_expired);
6632
12
            metrics_context.kv_recycled_num.set(num_recycled);
6633
12
            metrics_context.update_metrics();
6634
12
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6629
12
        DORIS_CLOUD_DEFER {
6630
12
            metrics_context.kv_scanned_num.set(num_scanned);
6631
12
            metrics_context.kv_expired_num.set(num_expired);
6632
12
            metrics_context.kv_recycled_num.set(num_recycled);
6633
12
            metrics_context.update_metrics();
6634
12
        };
6635
24
        std::vector<std::string> tmp_rowset_keys_to_delete;
6636
24
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6637
24
        std::vector<std::string> mark_keys_to_process;
6638
24
        std::vector<std::string> abort_keys_to_process;
6639
24
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6640
24
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6641
24
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6642
24
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6643
24
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6644
24
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6645
24
        if (!mark_keys_to_process.empty()) {
6646
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6647
7
                    *worker_pool, std::move(mark_keys_to_process));
6648
7
        }
6649
24
        if (!abort_keys_to_process.empty()) {
6650
5
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6651
5
                                           &num_recycled, &metrics_context);
6652
5
        }
6653
24
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6654
24
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6655
24
                             tmp_rowset_ref_count_keys_to_delete =
6656
24
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6657
24
                             mark_keys_to_process = std::move(mark_keys_to_process),
6658
24
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6659
24
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6660
24
                                   metrics_context) != 0) {
6661
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6662
2
                return;
6663
2
            }
6664
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6665
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6666
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6667
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6668
0
                                 << rs.ShortDebugString();
6669
0
                    return;
6670
0
                }
6671
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6672
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6673
0
                                 << rs.ShortDebugString();
6674
0
                    return;
6675
0
                }
6676
51.0k
            }
6677
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6678
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6679
0
                return;
6680
0
            }
6681
22
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6682
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6683
0
                return;
6684
0
            }
6685
22
            num_recycled += tmp_rowset_keys_to_delete.size();
6686
22
            return;
6687
22
        });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE0_clEv
Line
Count
Source
6658
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6659
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6660
12
                                   metrics_context) != 0) {
6661
0
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6662
0
                return;
6663
0
            }
6664
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6665
4
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6666
4
                                                       rs.rowset_id_v2()) != 0) {
6667
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6668
0
                                 << rs.ShortDebugString();
6669
0
                    return;
6670
0
                }
6671
4
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6672
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6673
0
                                 << rs.ShortDebugString();
6674
0
                    return;
6675
0
                }
6676
4
            }
6677
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6678
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6679
0
                return;
6680
0
            }
6681
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6682
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6683
0
                return;
6684
0
            }
6685
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6686
12
            return;
6687
12
        });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEvENUlvE0_clEv
Line
Count
Source
6658
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6659
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6660
12
                                   metrics_context) != 0) {
6661
2
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6662
2
                return;
6663
2
            }
6664
51.0k
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6665
51.0k
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6666
51.0k
                                                       rs.rowset_id_v2()) != 0) {
6667
0
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6668
0
                                 << rs.ShortDebugString();
6669
0
                    return;
6670
0
                }
6671
51.0k
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6672
0
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6673
0
                                 << rs.ShortDebugString();
6674
0
                    return;
6675
0
                }
6676
51.0k
            }
6677
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6678
0
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6679
0
                return;
6680
0
            }
6681
10
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6682
0
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6683
0
                return;
6684
0
            }
6685
10
            num_recycled += tmp_rowset_keys_to_delete.size();
6686
10
            return;
6687
10
        });
6688
24
        return 0;
6689
24
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6628
12
    auto loop_done = [&]() -> int {
6629
12
        DORIS_CLOUD_DEFER {
6630
12
            metrics_context.kv_scanned_num.set(num_scanned);
6631
12
            metrics_context.kv_expired_num.set(num_expired);
6632
12
            metrics_context.kv_recycled_num.set(num_recycled);
6633
12
            metrics_context.update_metrics();
6634
12
        };
6635
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6636
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6637
12
        std::vector<std::string> mark_keys_to_process;
6638
12
        std::vector<std::string> abort_keys_to_process;
6639
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6640
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6641
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6642
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6643
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6644
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6645
12
        if (!mark_keys_to_process.empty()) {
6646
7
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6647
7
                    *worker_pool, std::move(mark_keys_to_process));
6648
7
        }
6649
12
        if (!abort_keys_to_process.empty()) {
6650
3
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6651
3
                                           &num_recycled, &metrics_context);
6652
3
        }
6653
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6654
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6655
12
                             tmp_rowset_ref_count_keys_to_delete =
6656
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6657
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6658
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6659
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6660
12
                                   metrics_context) != 0) {
6661
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6662
12
                return;
6663
12
            }
6664
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6665
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6666
12
                                                       rs.rowset_id_v2()) != 0) {
6667
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6668
12
                                 << rs.ShortDebugString();
6669
12
                    return;
6670
12
                }
6671
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6672
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6673
12
                                 << rs.ShortDebugString();
6674
12
                    return;
6675
12
                }
6676
12
            }
6677
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6678
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6679
12
                return;
6680
12
            }
6681
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6682
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6683
12
                return;
6684
12
            }
6685
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6686
12
            return;
6687
12
        });
6688
12
        return 0;
6689
12
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler19recycle_tmp_rowsetsEvENK3$_1clEv
Line
Count
Source
6628
12
    auto loop_done = [&]() -> int {
6629
12
        DORIS_CLOUD_DEFER {
6630
12
            metrics_context.kv_scanned_num.set(num_scanned);
6631
12
            metrics_context.kv_expired_num.set(num_expired);
6632
12
            metrics_context.kv_recycled_num.set(num_recycled);
6633
12
            metrics_context.update_metrics();
6634
12
        };
6635
12
        std::vector<std::string> tmp_rowset_keys_to_delete;
6636
12
        std::vector<std::string> tmp_rowset_ref_count_keys_to_delete;
6637
12
        std::vector<std::string> mark_keys_to_process;
6638
12
        std::vector<std::string> abort_keys_to_process;
6639
12
        std::map<std::string, doris::RowsetMetaCloudPB> tmp_rowsets_to_delete;
6640
12
        tmp_rowset_keys_to_delete.swap(tmp_rowset_keys);
6641
12
        tmp_rowsets_to_delete.swap(tmp_rowsets);
6642
12
        tmp_rowset_ref_count_keys_to_delete.swap(tmp_rowset_ref_count_keys);
6643
12
        mark_keys_to_process.swap(tmp_rowset_keys_to_mark_recycled);
6644
12
        abort_keys_to_process.swap(tmp_rowset_keys_to_abort);
6645
12
        if (!mark_keys_to_process.empty()) {
6646
0
            submit_batch_mark_rowsets_as_recycled_job<RowsetMetaCloudPB>(
6647
0
                    *worker_pool, std::move(mark_keys_to_process));
6648
0
        }
6649
12
        if (!abort_keys_to_process.empty()) {
6650
2
            submit_recycle_tmp_rowsets_job(*worker_pool, std::move(abort_keys_to_process),
6651
2
                                           &num_recycled, &metrics_context);
6652
2
        }
6653
12
        worker_pool->submit([&, tmp_rowset_keys_to_delete = std::move(tmp_rowset_keys_to_delete),
6654
12
                             tmp_rowsets_to_delete = std::move(tmp_rowsets_to_delete),
6655
12
                             tmp_rowset_ref_count_keys_to_delete =
6656
12
                                     std::move(tmp_rowset_ref_count_keys_to_delete),
6657
12
                             mark_keys_to_process = std::move(mark_keys_to_process),
6658
12
                             abort_keys_to_process = std::move(abort_keys_to_process)]() mutable {
6659
12
            if (delete_rowset_data(tmp_rowsets_to_delete, RowsetRecyclingState::TMP_ROWSET,
6660
12
                                   metrics_context) != 0) {
6661
12
                LOG(WARNING) << "failed to delete tmp rowset data, instance_id=" << instance_id_;
6662
12
                return;
6663
12
            }
6664
12
            for (const auto& [_, rs] : tmp_rowsets_to_delete) {
6665
12
                if (delete_versioned_delete_bitmap_kvs(rs.partition_id(), rs.tablet_id(),
6666
12
                                                       rs.rowset_id_v2()) != 0) {
6667
12
                    LOG(WARNING) << "failed to delete versioned delete bitmap kv, rs="
6668
12
                                 << rs.ShortDebugString();
6669
12
                    return;
6670
12
                }
6671
12
                if (delete_delete_bitmap_kvs(rs.tablet_id(), rs.rowset_id_v2()) != 0) {
6672
12
                    LOG(WARNING) << "failed to delete delete bitmap kv, rs="
6673
12
                                 << rs.ShortDebugString();
6674
12
                    return;
6675
12
                }
6676
12
            }
6677
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_keys_to_delete) != 0) {
6678
12
                LOG(WARNING) << "failed to tmp rowset kv, instance_id=" << instance_id_;
6679
12
                return;
6680
12
            }
6681
12
            if (txn_remove(txn_kv_.get(), tmp_rowset_ref_count_keys_to_delete) != 0) {
6682
12
                LOG(WARNING) << "failed to tmp rowset ref count kv, instance_id=" << instance_id_;
6683
12
                return;
6684
12
            }
6685
12
            num_recycled += tmp_rowset_keys_to_delete.size();
6686
12
            return;
6687
12
        });
6688
12
        return 0;
6689
12
    };
6690
6691
    // recycle_func and loop_done for scan and recycle
6692
37
    int ret = scan_and_recycle(tmp_rs_key0, tmp_rs_key1, std::move(handle_rowset_kv),
6693
37
                               std::move(loop_done));
6694
6695
37
    worker_pool->stop();
6696
6697
37
    return ret;
6698
37
}
6699
6700
int InstanceRecycler::scan_and_recycle(
6701
        std::string begin, std::string_view end,
6702
        std::function<int(std::string_view k, std::string_view v)> recycle_func,
6703
326
        std::function<int()> loop_done, std::function<bool(std::string*)> next_begin_getter) {
6704
326
    LOG(INFO) << "begin scan_and_recycle key_range=[" << hex(begin) << "," << hex(end) << ")";
6705
326
    int ret = 0;
6706
326
    int64_t cnt = 0;
6707
326
    int get_range_retried = 0;
6708
326
    std::string err;
6709
326
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6710
326
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6711
326
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6712
326
                  << " ret=" << ret << " err=" << err;
6713
326
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6709
39
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6710
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6711
39
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6712
39
                  << " ret=" << ret << " err=" << err;
6713
39
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler16scan_and_recycleENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESt17basic_string_viewIcS5_ESt8functionIFiS9_S9_EESA_IFivEESA_IFbPS7_EEENK3$_0clEv
Line
Count
Source
6709
287
    DORIS_CLOUD_DEFER_COPY(begin, end) {
6710
        LOG(INFO) << "finish scan_and_recycle key_range=[" << hex(begin) << "," << hex(end)
6711
287
                  << ") num_scanned=" << cnt << " get_range_retried=" << get_range_retried
6712
287
                  << " ret=" << ret << " err=" << err;
6713
287
    };
6714
6715
326
    std::unique_ptr<RangeGetIterator> it;
6716
532
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
6717
357
        if (get_range_retried > 1000) {
6718
0
            err = "txn_get exceeds max retry(1000), may not scan all keys";
6719
0
            ret = -3;
6720
0
            return ret;
6721
0
        }
6722
357
        int get_ret = txn_get(txn_kv_.get(), begin, end, it);
6723
357
        if (get_ret != 0) { // txn kv may complain "Request for future version"
6724
0
            LOG(WARNING) << "failed to get kv, range=[" << hex(begin) << "," << hex(end)
6725
0
                         << ") num_scanned=" << cnt << " txn_get_ret=" << get_ret
6726
0
                         << " get_range_retried=" << get_range_retried;
6727
0
            ++get_range_retried;
6728
0
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
6729
0
            continue; // try again
6730
0
        }
6731
357
        if (!it->has_next()) {
6732
151
            LOG(INFO) << "no keys in the given range=[" << hex(begin) << "," << hex(end) << ")";
6733
151
            break; // scan finished
6734
151
        }
6735
206
        bool begin_updated = false;
6736
206
        LOG(INFO) << "scan_and_recycle iterator key_range=[" << hex(begin) << "," << hex(end)
6737
206
                  << ") iterator->size()=" << it->size();
6738
138k
        while (it->has_next()) {
6739
138k
            ++cnt;
6740
            // recycle corresponding resources
6741
138k
            auto [k, v] = it->next();
6742
138k
            if (!it->has_next()) {
6743
207
                begin = k;
6744
207
                VLOG_DEBUG << "iterator has no more kvs. key=" << hex(k);
6745
207
            }
6746
            // FIXME(gavin): if we want to continue scanning, the recycle_func should not return non-zero
6747
138k
            if (recycle_func(k, v) != 0) {
6748
4.00k
                err = "recycle_func error";
6749
4.00k
                ret = -1;
6750
4.00k
            }
6751
138k
            if (next_begin_getter) {
6752
0
                std::string next_begin;
6753
0
                if (next_begin_getter(&next_begin)) {
6754
0
                    if (next_begin > k) {
6755
0
                        begin = std::move(next_begin);
6756
0
                        begin_updated = true;
6757
0
                        VLOG_DEBUG << "scan_and_recycle updates begin to " << hex(begin)
6758
0
                                   << " after key=" << hex(k);
6759
0
                        break;
6760
0
                    }
6761
0
                    LOG_WARNING("ignore invalid next begin in scan_and_recycle")
6762
0
                            .tag("next_begin", hex(next_begin))
6763
0
                            .tag("current_key", hex(k));
6764
0
                }
6765
0
            }
6766
138k
        }
6767
207
        if (!begin_updated) {
6768
207
            begin.push_back('\x00'); // Update to next smallest key for iteration
6769
18.4E
        } else {
6770
18.4E
            it.reset();
6771
18.4E
        }
6772
6773
        // FIXME(gavin): if we want to continue scanning, the loop_done should not return non-zero
6774
        // if we want to continue scanning, the recycle_func should not return non-zero
6775
206
        if (loop_done && loop_done() != 0) {
6776
8
            err = "loop_done error";
6777
8
            ret = -1;
6778
8
        }
6779
206
    }
6780
326
    return ret;
6781
326
}
6782
6783
19
int InstanceRecycler::abort_timeout_txn() {
6784
19
    const std::string task_name = "abort_timeout_txn";
6785
19
    int64_t num_scanned = 0;
6786
19
    int64_t num_timeout = 0;
6787
19
    int64_t num_abort = 0;
6788
19
    int64_t num_advance = 0;
6789
19
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6790
6791
19
    TxnRunningKeyInfo txn_running_key_info0 {instance_id_, 0, 0};
6792
19
    TxnRunningKeyInfo txn_running_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6793
19
    std::string begin_txn_running_key;
6794
19
    std::string end_txn_running_key;
6795
19
    txn_running_key(txn_running_key_info0, &begin_txn_running_key);
6796
19
    txn_running_key(txn_running_key_info1, &end_txn_running_key);
6797
6798
19
    LOG_WARNING("begin to abort timeout txn").tag("instance_id", instance_id_);
6799
6800
19
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6801
19
    register_recycle_task(task_name, start_time);
6802
6803
19
    DORIS_CLOUD_DEFER {
6804
19
        unregister_recycle_task(task_name);
6805
19
        metrics_context.kv_scanned_num.set(num_scanned);
6806
19
        metrics_context.kv_expired_num.set(num_timeout);
6807
19
        metrics_context.kv_recycled_num.set(num_abort);
6808
19
        int64_t cost =
6809
19
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6810
19
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6811
19
                .tag("instance_id", instance_id_)
6812
19
                .tag("num_scanned", num_scanned)
6813
19
                .tag("num_timeout", num_timeout)
6814
19
                .tag("num_abort", num_abort)
6815
19
                .tag("num_advance", num_advance);
6816
19
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6803
3
    DORIS_CLOUD_DEFER {
6804
3
        unregister_recycle_task(task_name);
6805
3
        metrics_context.kv_scanned_num.set(num_scanned);
6806
3
        metrics_context.kv_expired_num.set(num_timeout);
6807
3
        metrics_context.kv_recycled_num.set(num_abort);
6808
3
        int64_t cost =
6809
3
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6810
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6811
3
                .tag("instance_id", instance_id_)
6812
3
                .tag("num_scanned", num_scanned)
6813
3
                .tag("num_timeout", num_timeout)
6814
3
                .tag("num_abort", num_abort)
6815
3
                .tag("num_advance", num_advance);
6816
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_0clEv
Line
Count
Source
6803
16
    DORIS_CLOUD_DEFER {
6804
16
        unregister_recycle_task(task_name);
6805
16
        metrics_context.kv_scanned_num.set(num_scanned);
6806
16
        metrics_context.kv_expired_num.set(num_timeout);
6807
16
        metrics_context.kv_recycled_num.set(num_abort);
6808
16
        int64_t cost =
6809
16
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6810
        LOG_WARNING("end to abort timeout txn, cost={}s", cost)
6811
16
                .tag("instance_id", instance_id_)
6812
16
                .tag("num_scanned", num_scanned)
6813
16
                .tag("num_timeout", num_timeout)
6814
16
                .tag("num_abort", num_abort)
6815
16
                .tag("num_advance", num_advance);
6816
16
    };
6817
6818
19
    int64_t current_time =
6819
19
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6820
6821
19
    auto handle_txn_running_kv = [&num_scanned, &num_timeout, &num_abort, &num_advance,
6822
19
                                  &current_time,
6823
19
                                  this](std::string_view k, std::string_view v) -> int {
6824
9
        ++num_scanned;
6825
9
        std::unique_ptr<Transaction> txn;
6826
9
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6827
9
        if (err != TxnErrorCode::TXN_OK) {
6828
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6829
0
            return -1;
6830
0
        }
6831
9
        std::string_view k1 = k;
6832
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6833
9
        k1.remove_prefix(1); // Remove key space
6834
9
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6835
9
        if (decode_key(&k1, &out) != 0) {
6836
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6837
0
            return -1;
6838
0
        }
6839
9
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6840
9
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6841
9
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6842
        // Update txn_info
6843
9
        std::string txn_inf_key, txn_inf_val;
6844
9
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6845
9
        err = txn->get(txn_inf_key, &txn_inf_val);
6846
9
        if (err != TxnErrorCode::TXN_OK) {
6847
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6848
0
            return -1;
6849
0
        }
6850
9
        TxnInfoPB txn_info;
6851
9
        if (!txn_info.ParseFromString(txn_inf_val)) {
6852
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6853
0
            return -1;
6854
0
        }
6855
6856
9
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6857
3
            txn.reset();
6858
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6859
3
            std::shared_ptr<TxnLazyCommitTask> task =
6860
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6861
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6862
3
            if (ret.first != MetaServiceCode::OK) {
6863
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6864
0
                             << "msg=" << ret.second;
6865
0
                return -1;
6866
0
            }
6867
3
            ++num_advance;
6868
3
            return 0;
6869
6
        } else {
6870
6
            TxnRunningPB txn_running_pb;
6871
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6872
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6873
0
                return -1;
6874
0
            }
6875
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6876
4
                return 0;
6877
4
            }
6878
2
            ++num_timeout;
6879
6880
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6881
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6882
2
            txn_info.set_finish_time(current_time);
6883
2
            txn_info.set_reason("timeout");
6884
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6885
2
            txn_inf_val.clear();
6886
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6887
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6888
0
                return -1;
6889
0
            }
6890
2
            txn->put(txn_inf_key, txn_inf_val);
6891
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6892
            // Put recycle txn key
6893
2
            std::string recyc_txn_key, recyc_txn_val;
6894
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6895
2
            RecycleTxnPB recycle_txn_pb;
6896
2
            recycle_txn_pb.set_creation_time(current_time);
6897
2
            recycle_txn_pb.set_label(txn_info.label());
6898
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6899
0
                LOG_WARNING("failed to serialize txn recycle info")
6900
0
                        .tag("key", hex(k))
6901
0
                        .tag("db_id", db_id)
6902
0
                        .tag("txn_id", txn_id);
6903
0
                return -1;
6904
0
            }
6905
2
            txn->put(recyc_txn_key, recyc_txn_val);
6906
            // Remove txn running key
6907
2
            txn->remove(k);
6908
2
            err = txn->commit();
6909
2
            if (err != TxnErrorCode::TXN_OK) {
6910
0
                LOG_WARNING("failed to commit txn err={}", err)
6911
0
                        .tag("key", hex(k))
6912
0
                        .tag("db_id", db_id)
6913
0
                        .tag("txn_id", txn_id);
6914
0
                return -1;
6915
0
            }
6916
2
            ++num_abort;
6917
2
        }
6918
6919
2
        return 0;
6920
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6823
3
                                  this](std::string_view k, std::string_view v) -> int {
6824
3
        ++num_scanned;
6825
3
        std::unique_ptr<Transaction> txn;
6826
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6827
3
        if (err != TxnErrorCode::TXN_OK) {
6828
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6829
0
            return -1;
6830
0
        }
6831
3
        std::string_view k1 = k;
6832
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6833
3
        k1.remove_prefix(1); // Remove key space
6834
3
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6835
3
        if (decode_key(&k1, &out) != 0) {
6836
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6837
0
            return -1;
6838
0
        }
6839
3
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6840
3
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6841
3
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6842
        // Update txn_info
6843
3
        std::string txn_inf_key, txn_inf_val;
6844
3
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6845
3
        err = txn->get(txn_inf_key, &txn_inf_val);
6846
3
        if (err != TxnErrorCode::TXN_OK) {
6847
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6848
0
            return -1;
6849
0
        }
6850
3
        TxnInfoPB txn_info;
6851
3
        if (!txn_info.ParseFromString(txn_inf_val)) {
6852
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6853
0
            return -1;
6854
0
        }
6855
6856
3
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6857
3
            txn.reset();
6858
3
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6859
3
            std::shared_ptr<TxnLazyCommitTask> task =
6860
3
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6861
3
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6862
3
            if (ret.first != MetaServiceCode::OK) {
6863
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6864
0
                             << "msg=" << ret.second;
6865
0
                return -1;
6866
0
            }
6867
3
            ++num_advance;
6868
3
            return 0;
6869
3
        } else {
6870
0
            TxnRunningPB txn_running_pb;
6871
0
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6872
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6873
0
                return -1;
6874
0
            }
6875
0
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6876
0
                return 0;
6877
0
            }
6878
0
            ++num_timeout;
6879
6880
0
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6881
0
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6882
0
            txn_info.set_finish_time(current_time);
6883
0
            txn_info.set_reason("timeout");
6884
0
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6885
0
            txn_inf_val.clear();
6886
0
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6887
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6888
0
                return -1;
6889
0
            }
6890
0
            txn->put(txn_inf_key, txn_inf_val);
6891
0
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6892
            // Put recycle txn key
6893
0
            std::string recyc_txn_key, recyc_txn_val;
6894
0
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6895
0
            RecycleTxnPB recycle_txn_pb;
6896
0
            recycle_txn_pb.set_creation_time(current_time);
6897
0
            recycle_txn_pb.set_label(txn_info.label());
6898
0
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6899
0
                LOG_WARNING("failed to serialize txn recycle info")
6900
0
                        .tag("key", hex(k))
6901
0
                        .tag("db_id", db_id)
6902
0
                        .tag("txn_id", txn_id);
6903
0
                return -1;
6904
0
            }
6905
0
            txn->put(recyc_txn_key, recyc_txn_val);
6906
            // Remove txn running key
6907
0
            txn->remove(k);
6908
0
            err = txn->commit();
6909
0
            if (err != TxnErrorCode::TXN_OK) {
6910
0
                LOG_WARNING("failed to commit txn err={}", err)
6911
0
                        .tag("key", hex(k))
6912
0
                        .tag("db_id", db_id)
6913
0
                        .tag("txn_id", txn_id);
6914
0
                return -1;
6915
0
            }
6916
0
            ++num_abort;
6917
0
        }
6918
6919
0
        return 0;
6920
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6823
6
                                  this](std::string_view k, std::string_view v) -> int {
6824
6
        ++num_scanned;
6825
6
        std::unique_ptr<Transaction> txn;
6826
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
6827
6
        if (err != TxnErrorCode::TXN_OK) {
6828
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
6829
0
            return -1;
6830
0
        }
6831
6
        std::string_view k1 = k;
6832
        //TxnRunningKeyInfo 0:instance_id  1:db_id  2:txn_id
6833
6
        k1.remove_prefix(1); // Remove key space
6834
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6835
6
        if (decode_key(&k1, &out) != 0) {
6836
0
            LOG_ERROR("failed to decode key").tag("key", hex(k));
6837
0
            return -1;
6838
0
        }
6839
6
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
6840
6
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
6841
6
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
6842
        // Update txn_info
6843
6
        std::string txn_inf_key, txn_inf_val;
6844
6
        txn_info_key({instance_id_, db_id, txn_id}, &txn_inf_key);
6845
6
        err = txn->get(txn_inf_key, &txn_inf_val);
6846
6
        if (err != TxnErrorCode::TXN_OK) {
6847
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(txn_inf_key));
6848
0
            return -1;
6849
0
        }
6850
6
        TxnInfoPB txn_info;
6851
6
        if (!txn_info.ParseFromString(txn_inf_val)) {
6852
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(k));
6853
0
            return -1;
6854
0
        }
6855
6856
6
        if (TxnStatusPB::TXN_STATUS_COMMITTED == txn_info.status()) {
6857
0
            txn.reset();
6858
0
            TEST_SYNC_POINT_CALLBACK("abort_timeout_txn::advance_last_pending_txn_id", &txn_info);
6859
0
            std::shared_ptr<TxnLazyCommitTask> task =
6860
0
                    txn_lazy_committer_->submit(instance_id_, txn_info.txn_id());
6861
0
            std::pair<MetaServiceCode, std::string> ret = task->wait();
6862
0
            if (ret.first != MetaServiceCode::OK) {
6863
0
                LOG(WARNING) << "lazy commit txn failed txn_id=" << txn_id << " code=" << ret.first
6864
0
                             << "msg=" << ret.second;
6865
0
                return -1;
6866
0
            }
6867
0
            ++num_advance;
6868
0
            return 0;
6869
6
        } else {
6870
6
            TxnRunningPB txn_running_pb;
6871
6
            if (!txn_running_pb.ParseFromArray(v.data(), v.size())) {
6872
0
                LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6873
0
                return -1;
6874
0
            }
6875
6
            if (!config::force_immediate_recycle && txn_running_pb.timeout_time() > current_time) {
6876
4
                return 0;
6877
4
            }
6878
2
            ++num_timeout;
6879
6880
2
            DCHECK(txn_info.status() != TxnStatusPB::TXN_STATUS_VISIBLE);
6881
2
            txn_info.set_status(TxnStatusPB::TXN_STATUS_ABORTED);
6882
2
            txn_info.set_finish_time(current_time);
6883
2
            txn_info.set_reason("timeout");
6884
2
            VLOG_DEBUG << "txn_info=" << txn_info.ShortDebugString();
6885
2
            txn_inf_val.clear();
6886
2
            if (!txn_info.SerializeToString(&txn_inf_val)) {
6887
0
                LOG_WARNING("failed to serialize txn info").tag("key", hex(k));
6888
0
                return -1;
6889
0
            }
6890
2
            txn->put(txn_inf_key, txn_inf_val);
6891
2
            VLOG_DEBUG << "txn->put, txn_inf_key=" << hex(txn_inf_key);
6892
            // Put recycle txn key
6893
2
            std::string recyc_txn_key, recyc_txn_val;
6894
2
            recycle_txn_key({instance_id_, db_id, txn_id}, &recyc_txn_key);
6895
2
            RecycleTxnPB recycle_txn_pb;
6896
2
            recycle_txn_pb.set_creation_time(current_time);
6897
2
            recycle_txn_pb.set_label(txn_info.label());
6898
2
            if (!recycle_txn_pb.SerializeToString(&recyc_txn_val)) {
6899
0
                LOG_WARNING("failed to serialize txn recycle info")
6900
0
                        .tag("key", hex(k))
6901
0
                        .tag("db_id", db_id)
6902
0
                        .tag("txn_id", txn_id);
6903
0
                return -1;
6904
0
            }
6905
2
            txn->put(recyc_txn_key, recyc_txn_val);
6906
            // Remove txn running key
6907
2
            txn->remove(k);
6908
2
            err = txn->commit();
6909
2
            if (err != TxnErrorCode::TXN_OK) {
6910
0
                LOG_WARNING("failed to commit txn err={}", err)
6911
0
                        .tag("key", hex(k))
6912
0
                        .tag("db_id", db_id)
6913
0
                        .tag("txn_id", txn_id);
6914
0
                return -1;
6915
0
            }
6916
2
            ++num_abort;
6917
2
        }
6918
6919
2
        return 0;
6920
6
    };
6921
6922
19
    auto loop_done = [&]() -> int {
6923
9
        DORIS_CLOUD_DEFER {
6924
9
            metrics_context.kv_scanned_num.set(num_scanned);
6925
9
            metrics_context.kv_expired_num.set(num_timeout);
6926
9
            metrics_context.kv_recycled_num.set(num_abort);
6927
9
            metrics_context.update_metrics();
6928
9
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6923
3
        DORIS_CLOUD_DEFER {
6924
3
            metrics_context.kv_scanned_num.set(num_scanned);
6925
3
            metrics_context.kv_expired_num.set(num_timeout);
6926
3
            metrics_context.kv_recycled_num.set(num_abort);
6927
3
            metrics_context.update_metrics();
6928
3
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
6923
6
        DORIS_CLOUD_DEFER {
6924
6
            metrics_context.kv_scanned_num.set(num_scanned);
6925
6
            metrics_context.kv_expired_num.set(num_timeout);
6926
6
            metrics_context.kv_recycled_num.set(num_abort);
6927
6
            metrics_context.update_metrics();
6928
6
        };
6929
9
        return 0;
6930
9
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clEv
Line
Count
Source
6922
3
    auto loop_done = [&]() -> int {
6923
3
        DORIS_CLOUD_DEFER {
6924
3
            metrics_context.kv_scanned_num.set(num_scanned);
6925
3
            metrics_context.kv_expired_num.set(num_timeout);
6926
3
            metrics_context.kv_recycled_num.set(num_abort);
6927
3
            metrics_context.update_metrics();
6928
3
        };
6929
3
        return 0;
6930
3
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17abort_timeout_txnEvENK3$_1clEv
Line
Count
Source
6922
6
    auto loop_done = [&]() -> int {
6923
6
        DORIS_CLOUD_DEFER {
6924
6
            metrics_context.kv_scanned_num.set(num_scanned);
6925
6
            metrics_context.kv_expired_num.set(num_timeout);
6926
6
            metrics_context.kv_recycled_num.set(num_abort);
6927
6
            metrics_context.update_metrics();
6928
6
        };
6929
6
        return 0;
6930
6
    };
6931
6932
    // recycle_func and loop_done for scan and recycle
6933
19
    return scan_and_recycle(begin_txn_running_key, end_txn_running_key,
6934
19
                            std::move(handle_txn_running_kv), std::move(loop_done));
6935
19
}
6936
6937
22
int InstanceRecycler::recycle_expired_txn_label() {
6938
22
    const std::string task_name = "recycle_expired_txn_label";
6939
22
    int64_t num_scanned = 0;
6940
22
    int64_t num_expired = 0;
6941
22
    std::atomic_long num_recycled = 0;
6942
22
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
6943
22
    int ret = 0;
6944
6945
22
    RecycleTxnKeyInfo recycle_txn_key_info0 {instance_id_, 0, 0};
6946
22
    RecycleTxnKeyInfo recycle_txn_key_info1 {instance_id_, INT64_MAX, INT64_MAX};
6947
22
    std::string begin_recycle_txn_key;
6948
22
    std::string end_recycle_txn_key;
6949
22
    recycle_txn_key(recycle_txn_key_info0, &begin_recycle_txn_key);
6950
22
    recycle_txn_key(recycle_txn_key_info1, &end_recycle_txn_key);
6951
22
    std::unordered_map<std::string, std::vector<std::string>> recycle_txn_keys_by_label;
6952
6953
22
    LOG_WARNING("begin to recycle expired txn").tag("instance_id", instance_id_);
6954
6955
22
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
6956
22
    register_recycle_task(task_name, start_time);
6957
22
    DORIS_CLOUD_DEFER {
6958
22
        metrics_context.kv_scanned_num.set(num_scanned);
6959
22
        metrics_context.kv_expired_num.set(num_expired);
6960
22
        metrics_context.kv_recycled_num.set(num_recycled);
6961
22
        unregister_recycle_task(task_name);
6962
22
        int64_t cost =
6963
22
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6964
22
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6965
22
                .tag("instance_id", instance_id_)
6966
22
                .tag("num_scanned", num_scanned)
6967
22
                .tag("num_expired", num_expired)
6968
22
                .tag("num_recycled", num_recycled);
6969
22
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6957
1
    DORIS_CLOUD_DEFER {
6958
1
        metrics_context.kv_scanned_num.set(num_scanned);
6959
1
        metrics_context.kv_expired_num.set(num_expired);
6960
1
        metrics_context.kv_recycled_num.set(num_recycled);
6961
1
        unregister_recycle_task(task_name);
6962
1
        int64_t cost =
6963
1
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6964
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6965
1
                .tag("instance_id", instance_id_)
6966
1
                .tag("num_scanned", num_scanned)
6967
1
                .tag("num_expired", num_expired)
6968
1
                .tag("num_recycled", num_recycled);
6969
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_0clEv
Line
Count
Source
6957
21
    DORIS_CLOUD_DEFER {
6958
21
        metrics_context.kv_scanned_num.set(num_scanned);
6959
21
        metrics_context.kv_expired_num.set(num_expired);
6960
21
        metrics_context.kv_recycled_num.set(num_recycled);
6961
21
        unregister_recycle_task(task_name);
6962
21
        int64_t cost =
6963
21
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
6964
        LOG_WARNING("end to recycle expired txn, cost={}s", cost)
6965
21
                .tag("instance_id", instance_id_)
6966
21
                .tag("num_scanned", num_scanned)
6967
21
                .tag("num_expired", num_expired)
6968
21
                .tag("num_recycled", num_recycled);
6969
21
    };
6970
6971
22
    int64_t earlest_ts = std::numeric_limits<int64_t>::max();
6972
6973
22
    SyncExecutor<int> concurrent_delete_executor(
6974
22
            _thread_pool_group.s3_producer_pool,
6975
22
            fmt::format("recycle expired txn label, instance id {}", instance_id_),
6976
38.0k
            [](const int& ret) { return ret != 0; });
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6976
1
            [](const int& ret) { return ret != 0; });
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_1clERKi
Line
Count
Source
6976
38.0k
            [](const int& ret) { return ret != 0; });
6977
6978
22
    int64_t current_time_ms =
6979
22
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
6980
6981
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6982
50.0k
        ++num_scanned;
6983
50.0k
        RecycleTxnPB recycle_txn_pb;
6984
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6985
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6986
0
            return -1;
6987
0
        }
6988
50.0k
        if ((config::force_immediate_recycle) ||
6989
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6990
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6991
50.0k
             current_time_ms)) {
6992
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6993
38.0k
            num_expired++;
6994
6995
38.0k
            std::string_view k1 = k;
6996
38.0k
            k1.remove_prefix(1); // Remove key space
6997
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6998
38.0k
            if (decode_key(&k1, &out) != 0) {
6999
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7000
0
                return -1;
7001
0
            }
7002
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7003
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7004
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7005
38.0k
        }
7006
50.0k
        return 0;
7007
50.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6981
1
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6982
1
        ++num_scanned;
6983
1
        RecycleTxnPB recycle_txn_pb;
6984
1
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6985
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6986
0
            return -1;
6987
0
        }
6988
1
        if ((config::force_immediate_recycle) ||
6989
1
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6990
1
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6991
1
             current_time_ms)) {
6992
1
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6993
1
            num_expired++;
6994
6995
1
            std::string_view k1 = k;
6996
1
            k1.remove_prefix(1); // Remove key space
6997
1
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6998
1
            if (decode_key(&k1, &out) != 0) {
6999
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7000
0
                return -1;
7001
0
            }
7002
1
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7003
1
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7004
1
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7005
1
        }
7006
1
        return 0;
7007
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_3clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
6981
50.0k
    auto handle_recycle_txn_kv = [&, this](std::string_view k, std::string_view v) -> int {
6982
50.0k
        ++num_scanned;
6983
50.0k
        RecycleTxnPB recycle_txn_pb;
6984
50.0k
        if (!recycle_txn_pb.ParseFromArray(v.data(), v.size())) {
6985
0
            LOG_WARNING("malformed txn_running_pb").tag("key", hex(k));
6986
0
            return -1;
6987
0
        }
6988
50.0k
        if ((config::force_immediate_recycle) ||
6989
50.0k
            (recycle_txn_pb.has_immediate() && recycle_txn_pb.immediate()) ||
6990
50.0k
            (calculate_txn_expired_time(instance_id_, recycle_txn_pb, &earlest_ts) <=
6991
50.0k
             current_time_ms)) {
6992
38.0k
            VLOG_DEBUG << "found recycle txn, key=" << hex(k);
6993
38.0k
            num_expired++;
6994
6995
38.0k
            std::string_view k1 = k;
6996
38.0k
            k1.remove_prefix(1); // Remove key space
6997
38.0k
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
6998
38.0k
            if (decode_key(&k1, &out) != 0) {
6999
0
                LOG_ERROR("failed to decode key").tag("key", hex(k));
7000
0
                return -1;
7001
0
            }
7002
38.0k
            int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7003
38.0k
            auto label_key = txn_label_key({instance_id_, db_id, recycle_txn_pb.label()});
7004
38.0k
            recycle_txn_keys_by_label[label_key].emplace_back(k);
7005
38.0k
        }
7006
50.0k
        return 0;
7007
50.0k
    };
7008
7009
    // int 0 for success, 1 for conflict, -1 for error
7010
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7011
38.0k
        std::string_view k1 = k;
7012
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7013
38.0k
        k1.remove_prefix(1); // Remove key space
7014
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7015
38.0k
        int ret = decode_key(&k1, &out);
7016
38.0k
        if (ret != 0) {
7017
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7018
0
            return -1;
7019
0
        }
7020
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7021
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7022
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7023
38.0k
        std::unique_ptr<Transaction> txn;
7024
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7025
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7026
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7027
0
            return -1;
7028
0
        }
7029
        // Remove txn index kv
7030
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7031
38.0k
        txn->remove(index_key);
7032
        // Remove txn info kv
7033
38.0k
        std::string info_key, info_val;
7034
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7035
38.0k
        err = txn->get(info_key, &info_val);
7036
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7037
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7038
0
            return -1;
7039
0
        }
7040
38.0k
        TxnInfoPB txn_info;
7041
38.0k
        if (!txn_info.ParseFromString(info_val)) {
7042
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7043
0
            return -1;
7044
0
        }
7045
38.0k
        txn->remove(info_key);
7046
        // Remove sub txn index kvs
7047
38.0k
        std::vector<std::string> sub_txn_index_keys;
7048
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7049
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7050
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7051
38.0k
        }
7052
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7053
38.0k
            txn->remove(sub_txn_index_key);
7054
38.0k
        }
7055
        // Update txn label
7056
38.0k
        std::string label_key, label_val;
7057
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7058
38.0k
        err = txn->get(label_key, &label_val);
7059
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7060
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7061
0
                         << " err=" << err;
7062
0
            return -1;
7063
0
        }
7064
38.0k
        TxnLabelPB txn_label;
7065
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7066
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7067
0
            return -1;
7068
0
        }
7069
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7070
38.0k
        if (it != txn_label.txn_ids().end()) {
7071
38.0k
            txn_label.mutable_txn_ids()->erase(it);
7072
38.0k
        }
7073
38.0k
        if (txn_label.txn_ids().empty()) {
7074
38.0k
            txn->remove(label_key);
7075
38.0k
            TEST_SYNC_POINT_CALLBACK(
7076
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7077
38.0k
        } else {
7078
13
            if (!txn_label.SerializeToString(&label_val)) {
7079
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7080
0
                return -1;
7081
0
            }
7082
13
            TEST_SYNC_POINT_CALLBACK(
7083
13
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7084
13
            txn->atomic_set_ver_value(label_key, label_val);
7085
13
            TEST_SYNC_POINT_CALLBACK(
7086
13
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7087
13
        }
7088
        // Remove recycle txn kv
7089
38.0k
        txn->remove(k);
7090
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7091
38.0k
        err = txn->commit();
7092
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7093
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
7094
4
                TEST_SYNC_POINT_CALLBACK(
7095
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7096
                // log the txn_id and label
7097
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7098
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7099
4
                             << " txn_label=" << txn_info.label();
7100
4
                return 1;
7101
4
            }
7102
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7103
0
            return -1;
7104
4
        }
7105
38.0k
        ++num_recycled;
7106
7107
38.0k
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7108
38.0k
        return 0;
7109
38.0k
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7010
1
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7011
1
        std::string_view k1 = k;
7012
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7013
1
        k1.remove_prefix(1); // Remove key space
7014
1
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7015
1
        int ret = decode_key(&k1, &out);
7016
1
        if (ret != 0) {
7017
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7018
0
            return -1;
7019
0
        }
7020
1
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7021
1
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7022
1
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7023
1
        std::unique_ptr<Transaction> txn;
7024
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7025
1
        if (err != TxnErrorCode::TXN_OK) {
7026
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7027
0
            return -1;
7028
0
        }
7029
        // Remove txn index kv
7030
1
        auto index_key = txn_index_key({instance_id_, txn_id});
7031
1
        txn->remove(index_key);
7032
        // Remove txn info kv
7033
1
        std::string info_key, info_val;
7034
1
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7035
1
        err = txn->get(info_key, &info_val);
7036
1
        if (err != TxnErrorCode::TXN_OK) {
7037
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7038
0
            return -1;
7039
0
        }
7040
1
        TxnInfoPB txn_info;
7041
1
        if (!txn_info.ParseFromString(info_val)) {
7042
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7043
0
            return -1;
7044
0
        }
7045
1
        txn->remove(info_key);
7046
        // Remove sub txn index kvs
7047
1
        std::vector<std::string> sub_txn_index_keys;
7048
1
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7049
0
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7050
0
            sub_txn_index_keys.push_back(sub_txn_index_key);
7051
0
        }
7052
1
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7053
0
            txn->remove(sub_txn_index_key);
7054
0
        }
7055
        // Update txn label
7056
1
        std::string label_key, label_val;
7057
1
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7058
1
        err = txn->get(label_key, &label_val);
7059
1
        if (err != TxnErrorCode::TXN_OK) {
7060
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7061
0
                         << " err=" << err;
7062
0
            return -1;
7063
0
        }
7064
1
        TxnLabelPB txn_label;
7065
1
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7066
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7067
0
            return -1;
7068
0
        }
7069
1
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7070
1
        if (it != txn_label.txn_ids().end()) {
7071
1
            txn_label.mutable_txn_ids()->erase(it);
7072
1
        }
7073
1
        if (txn_label.txn_ids().empty()) {
7074
1
            txn->remove(label_key);
7075
1
            TEST_SYNC_POINT_CALLBACK(
7076
1
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7077
1
        } else {
7078
0
            if (!txn_label.SerializeToString(&label_val)) {
7079
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7080
0
                return -1;
7081
0
            }
7082
0
            TEST_SYNC_POINT_CALLBACK(
7083
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7084
0
            txn->atomic_set_ver_value(label_key, label_val);
7085
0
            TEST_SYNC_POINT_CALLBACK(
7086
0
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7087
0
        }
7088
        // Remove recycle txn kv
7089
1
        txn->remove(k);
7090
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7091
1
        err = txn->commit();
7092
1
        if (err != TxnErrorCode::TXN_OK) {
7093
0
            if (err == TxnErrorCode::TXN_CONFLICT) {
7094
0
                TEST_SYNC_POINT_CALLBACK(
7095
0
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7096
                // log the txn_id and label
7097
0
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7098
0
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7099
0
                             << " txn_label=" << txn_info.label();
7100
0
                return 1;
7101
0
            }
7102
0
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7103
0
            return -1;
7104
0
        }
7105
1
        ++num_recycled;
7106
7107
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7108
1
        return 0;
7109
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_4clERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
Line
Count
Source
7010
38.0k
    auto delete_recycle_txn_kv = [&](const std::string& k) -> int {
7011
38.0k
        std::string_view k1 = k;
7012
        //RecycleTxnKeyInfo 0:instance_id  1:db_id  2:txn_id
7013
38.0k
        k1.remove_prefix(1); // Remove key space
7014
38.0k
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7015
38.0k
        int ret = decode_key(&k1, &out);
7016
38.0k
        if (ret != 0) {
7017
0
            LOG_ERROR("failed to decode key, ret={}", ret).tag("key", hex(k));
7018
0
            return -1;
7019
0
        }
7020
38.0k
        int64_t db_id = std::get<int64_t>(std::get<0>(out[3]));
7021
38.0k
        int64_t txn_id = std::get<int64_t>(std::get<0>(out[4]));
7022
38.0k
        VLOG_DEBUG << "instance_id=" << instance_id_ << " db_id=" << db_id << " txn_id=" << txn_id;
7023
38.0k
        std::unique_ptr<Transaction> txn;
7024
38.0k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7025
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7026
0
            LOG_ERROR("failed to create txn err={}", err).tag("key", hex(k));
7027
0
            return -1;
7028
0
        }
7029
        // Remove txn index kv
7030
38.0k
        auto index_key = txn_index_key({instance_id_, txn_id});
7031
38.0k
        txn->remove(index_key);
7032
        // Remove txn info kv
7033
38.0k
        std::string info_key, info_val;
7034
38.0k
        txn_info_key({instance_id_, db_id, txn_id}, &info_key);
7035
38.0k
        err = txn->get(info_key, &info_val);
7036
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7037
0
            LOG_WARNING("failed to get txn info err={}", err).tag("key", hex(info_key));
7038
0
            return -1;
7039
0
        }
7040
38.0k
        TxnInfoPB txn_info;
7041
38.0k
        if (!txn_info.ParseFromString(info_val)) {
7042
0
            LOG_WARNING("failed to parse txn info").tag("key", hex(info_key));
7043
0
            return -1;
7044
0
        }
7045
38.0k
        txn->remove(info_key);
7046
        // Remove sub txn index kvs
7047
38.0k
        std::vector<std::string> sub_txn_index_keys;
7048
38.0k
        for (auto sub_txn_id : txn_info.sub_txn_ids()) {
7049
38.0k
            auto sub_txn_index_key = txn_index_key({instance_id_, sub_txn_id});
7050
38.0k
            sub_txn_index_keys.push_back(sub_txn_index_key);
7051
38.0k
        }
7052
38.0k
        for (auto& sub_txn_index_key : sub_txn_index_keys) {
7053
38.0k
            txn->remove(sub_txn_index_key);
7054
38.0k
        }
7055
        // Update txn label
7056
38.0k
        std::string label_key, label_val;
7057
38.0k
        txn_label_key({instance_id_, db_id, txn_info.label()}, &label_key);
7058
38.0k
        err = txn->get(label_key, &label_val);
7059
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7060
0
            LOG(WARNING) << "failed to get txn label, txn_id=" << txn_id << " key=" << label_key
7061
0
                         << " err=" << err;
7062
0
            return -1;
7063
0
        }
7064
38.0k
        TxnLabelPB txn_label;
7065
38.0k
        if (!txn_label.ParseFromArray(label_val.data(), label_val.size() - VERSION_STAMP_LEN)) {
7066
0
            LOG_WARNING("failed to parse txn label").tag("key", hex(label_key));
7067
0
            return -1;
7068
0
        }
7069
38.0k
        auto it = std::find(txn_label.txn_ids().begin(), txn_label.txn_ids().end(), txn_id);
7070
38.0k
        if (it != txn_label.txn_ids().end()) {
7071
38.0k
            txn_label.mutable_txn_ids()->erase(it);
7072
38.0k
        }
7073
38.0k
        if (txn_label.txn_ids().empty()) {
7074
38.0k
            txn->remove(label_key);
7075
38.0k
            TEST_SYNC_POINT_CALLBACK(
7076
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.remove_label_before");
7077
38.0k
        } else {
7078
13
            if (!txn_label.SerializeToString(&label_val)) {
7079
0
                LOG(WARNING) << "failed to serialize txn label, key=" << hex(label_key);
7080
0
                return -1;
7081
0
            }
7082
13
            TEST_SYNC_POINT_CALLBACK(
7083
13
                    "InstanceRecycler::recycle_expired_txn_label.update_label_before");
7084
13
            txn->atomic_set_ver_value(label_key, label_val);
7085
13
            TEST_SYNC_POINT_CALLBACK(
7086
13
                    "InstanceRecycler::recycle_expired_txn_label.update_label_after");
7087
13
        }
7088
        // Remove recycle txn kv
7089
38.0k
        txn->remove(k);
7090
38.0k
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.before_commit");
7091
38.0k
        err = txn->commit();
7092
38.0k
        if (err != TxnErrorCode::TXN_OK) {
7093
4
            if (err == TxnErrorCode::TXN_CONFLICT) {
7094
4
                TEST_SYNC_POINT_CALLBACK(
7095
4
                        "InstanceRecycler::recycle_expired_txn_label.txn_conflict");
7096
                // log the txn_id and label
7097
4
                LOG(WARNING) << "txn conflict, txn_id=" << txn_id
7098
4
                             << " txn_label_pb=" << txn_label.ShortDebugString()
7099
4
                             << " txn_label=" << txn_info.label();
7100
4
                return 1;
7101
4
            }
7102
4
            LOG(WARNING) << "failed to delete expired txn, err=" << err << " key=" << hex(k);
7103
0
            return -1;
7104
4
        }
7105
38.0k
        ++num_recycled;
7106
7107
        LOG(INFO) << "recycle expired txn, key=" << hex(k);
7108
38.0k
        return 0;
7109
38.0k
    };
7110
7111
22
    auto loop_done = [&]() -> int {
7112
15
        DORIS_CLOUD_DEFER {
7113
15
            metrics_context.kv_scanned_num.set(num_scanned);
7114
15
            metrics_context.kv_expired_num.set(num_expired);
7115
15
            metrics_context.kv_recycled_num.set(num_recycled);
7116
15
            metrics_context.update_metrics();
7117
15
            recycle_txn_keys_by_label.clear();
7118
15
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7112
1
        DORIS_CLOUD_DEFER {
7113
1
            metrics_context.kv_scanned_num.set(num_scanned);
7114
1
            metrics_context.kv_expired_num.set(num_expired);
7115
1
            metrics_context.kv_recycled_num.set(num_recycled);
7116
1
            metrics_context.update_metrics();
7117
1
            recycle_txn_keys_by_label.clear();
7118
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE_clEv
Line
Count
Source
7112
14
        DORIS_CLOUD_DEFER {
7113
14
            metrics_context.kv_scanned_num.set(num_scanned);
7114
14
            metrics_context.kv_expired_num.set(num_expired);
7115
14
            metrics_context.kv_recycled_num.set(num_recycled);
7116
14
            metrics_context.update_metrics();
7117
14
            recycle_txn_keys_by_label.clear();
7118
14
        };
7119
15
        TEST_SYNC_POINT_CALLBACK(
7120
15
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7121
15
                &recycle_txn_keys_by_label);
7122
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7123
38.0k
            int ret = delete_recycle_txn_kv(k);
7124
38.0k
            TEST_SYNC_POINT_CALLBACK(
7125
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7126
38.0k
                    &ret);
7127
38.0k
            if (ret == 1) {
7128
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7129
4
                for (int i = 1; i <= max_retry; ++i) {
7130
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7131
3
                    ret = delete_recycle_txn_kv(k);
7132
3
                    TEST_SYNC_POINT_CALLBACK(
7133
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7134
3
                            "error",
7135
3
                            &ret);
7136
3
                    if (ret != 1) {
7137
1
                        break;
7138
1
                    }
7139
                    // random sleep 0-100 ms to retry
7140
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7141
2
                }
7142
2
            }
7143
38.0k
            return ret;
7144
38.0k
        };
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
7122
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7123
1
            int ret = delete_recycle_txn_kv(k);
7124
1
            TEST_SYNC_POINT_CALLBACK(
7125
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7126
1
                    &ret);
7127
1
            if (ret == 1) {
7128
0
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7129
0
                for (int i = 1; i <= max_retry; ++i) {
7130
0
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7131
0
                    ret = delete_recycle_txn_kv(k);
7132
0
                    TEST_SYNC_POINT_CALLBACK(
7133
0
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7134
0
                            "error",
7135
0
                            &ret);
7136
0
                    if (ret != 1) {
7137
0
                        break;
7138
0
                    }
7139
                    // random sleep 0-100 ms to retry
7140
0
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7141
0
                }
7142
0
            }
7143
1
            return ret;
7144
1
        };
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEE_clESA_
Line
Count
Source
7122
38.0k
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7123
38.0k
            int ret = delete_recycle_txn_kv(k);
7124
38.0k
            TEST_SYNC_POINT_CALLBACK(
7125
38.0k
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7126
38.0k
                    &ret);
7127
38.0k
            if (ret == 1) {
7128
2
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7129
4
                for (int i = 1; i <= max_retry; ++i) {
7130
3
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7131
3
                    ret = delete_recycle_txn_kv(k);
7132
3
                    TEST_SYNC_POINT_CALLBACK(
7133
3
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7134
3
                            "error",
7135
3
                            &ret);
7136
3
                    if (ret != 1) {
7137
1
                        break;
7138
1
                    }
7139
                    // random sleep 0-100 ms to retry
7140
2
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7141
2
                }
7142
2
            }
7143
38.0k
            return ret;
7144
38.0k
        };
7145
7146
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7147
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7148
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7149
0
                           << " txn_count=" << txn_keys.size();
7150
38.0k
                for (const auto& k : txn_keys) {
7151
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7152
38.0k
                    if (ret != 0) {
7153
2
                        LOG_WARNING("failed to delete recycle txn kv")
7154
2
                                .tag("instance id", instance_id_)
7155
2
                                .tag("key", hex(k))
7156
2
                                .tag("label_key", hex(label_key));
7157
2
                        return -1;
7158
2
                    }
7159
38.0k
                }
7160
38.0k
                return 0;
7161
38.0k
            });
recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7147
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7148
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7149
0
                           << " txn_count=" << txn_keys.size();
7150
1
                for (const auto& k : txn_keys) {
7151
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7152
1
                    if (ret != 0) {
7153
0
                        LOG_WARNING("failed to delete recycle txn kv")
7154
0
                                .tag("instance id", instance_id_)
7155
0
                                .tag("key", hex(k))
7156
0
                                .tag("label_key", hex(label_key));
7157
0
                        return -1;
7158
0
                    }
7159
1
                }
7160
1
                return 0;
7161
1
            });
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEvENKUlvE0_clEv
Line
Count
Source
7147
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7148
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7149
0
                           << " txn_count=" << txn_keys.size();
7150
38.0k
                for (const auto& k : txn_keys) {
7151
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7152
38.0k
                    if (ret != 0) {
7153
2
                        LOG_WARNING("failed to delete recycle txn kv")
7154
2
                                .tag("instance id", instance_id_)
7155
2
                                .tag("key", hex(k))
7156
2
                                .tag("label_key", hex(label_key));
7157
2
                        return -1;
7158
2
                    }
7159
38.0k
                }
7160
38.0k
                return 0;
7161
38.0k
            });
7162
38.0k
        }
7163
15
        bool finished = true;
7164
15
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7165
38.0k
        for (int r : rets) {
7166
38.0k
            if (r != 0) {
7167
2
                ret = -1;
7168
2
            }
7169
38.0k
        }
7170
7171
15
        ret = finished ? ret : -1;
7172
15
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7173
7174
15
        if (ret != 0) {
7175
6
            LOG_WARNING("recycle txn kv ret!=0")
7176
6
                    .tag("finished", finished)
7177
6
                    .tag("ret", ret)
7178
6
                    .tag("instance_id", instance_id_);
7179
6
            return ret;
7180
6
        }
7181
9
        return ret;
7182
15
    };
recycler.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7111
1
    auto loop_done = [&]() -> int {
7112
1
        DORIS_CLOUD_DEFER {
7113
1
            metrics_context.kv_scanned_num.set(num_scanned);
7114
1
            metrics_context.kv_expired_num.set(num_expired);
7115
1
            metrics_context.kv_recycled_num.set(num_recycled);
7116
1
            metrics_context.update_metrics();
7117
1
            recycle_txn_keys_by_label.clear();
7118
1
        };
7119
1
        TEST_SYNC_POINT_CALLBACK(
7120
1
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7121
1
                &recycle_txn_keys_by_label);
7122
1
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7123
1
            int ret = delete_recycle_txn_kv(k);
7124
1
            TEST_SYNC_POINT_CALLBACK(
7125
1
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7126
1
                    &ret);
7127
1
            if (ret == 1) {
7128
1
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7129
1
                for (int i = 1; i <= max_retry; ++i) {
7130
1
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7131
1
                    ret = delete_recycle_txn_kv(k);
7132
1
                    TEST_SYNC_POINT_CALLBACK(
7133
1
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7134
1
                            "error",
7135
1
                            &ret);
7136
1
                    if (ret != 1) {
7137
1
                        break;
7138
1
                    }
7139
                    // random sleep 0-100 ms to retry
7140
1
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7141
1
                }
7142
1
            }
7143
1
            return ret;
7144
1
        };
7145
7146
1
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7147
1
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7148
1
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7149
1
                           << " txn_count=" << txn_keys.size();
7150
1
                for (const auto& k : txn_keys) {
7151
1
                    int ret = delete_recycle_txn_kv_with_retry(k);
7152
1
                    if (ret != 0) {
7153
1
                        LOG_WARNING("failed to delete recycle txn kv")
7154
1
                                .tag("instance id", instance_id_)
7155
1
                                .tag("key", hex(k))
7156
1
                                .tag("label_key", hex(label_key));
7157
1
                        return -1;
7158
1
                    }
7159
1
                }
7160
1
                return 0;
7161
1
            });
7162
1
        }
7163
1
        bool finished = true;
7164
1
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7165
1
        for (int r : rets) {
7166
1
            if (r != 0) {
7167
0
                ret = -1;
7168
0
            }
7169
1
        }
7170
7171
1
        ret = finished ? ret : -1;
7172
1
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7173
7174
1
        if (ret != 0) {
7175
0
            LOG_WARNING("recycle txn kv ret!=0")
7176
0
                    .tag("finished", finished)
7177
0
                    .tag("ret", ret)
7178
0
                    .tag("instance_id", instance_id_);
7179
0
            return ret;
7180
0
        }
7181
1
        return ret;
7182
1
    };
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler25recycle_expired_txn_labelEvENK3$_2clEv
Line
Count
Source
7111
14
    auto loop_done = [&]() -> int {
7112
14
        DORIS_CLOUD_DEFER {
7113
14
            metrics_context.kv_scanned_num.set(num_scanned);
7114
14
            metrics_context.kv_expired_num.set(num_expired);
7115
14
            metrics_context.kv_recycled_num.set(num_recycled);
7116
14
            metrics_context.update_metrics();
7117
14
            recycle_txn_keys_by_label.clear();
7118
14
        };
7119
14
        TEST_SYNC_POINT_CALLBACK(
7120
14
                "InstanceRecycler::recycle_expired_txn_label.check_recycle_txn_keys_by_label",
7121
14
                &recycle_txn_keys_by_label);
7122
14
        auto delete_recycle_txn_kv_with_retry = [&](const std::string& k) -> int {
7123
14
            int ret = delete_recycle_txn_kv(k);
7124
14
            TEST_SYNC_POINT_CALLBACK(
7125
14
                    "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_error",
7126
14
                    &ret);
7127
14
            if (ret == 1) {
7128
14
                const int max_retry = std::max(1, config::recycle_txn_delete_max_retry_times);
7129
14
                for (int i = 1; i <= max_retry; ++i) {
7130
14
                    LOG(WARNING) << "txn conflict, retry times=" << i << " key=" << hex(k);
7131
14
                    ret = delete_recycle_txn_kv(k);
7132
14
                    TEST_SYNC_POINT_CALLBACK(
7133
14
                            "InstanceRecycler::recycle_expired_txn_label.delete_recycle_txn_kv_"
7134
14
                            "error",
7135
14
                            &ret);
7136
14
                    if (ret != 1) {
7137
14
                        break;
7138
14
                    }
7139
                    // random sleep 0-100 ms to retry
7140
14
                    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));
7141
14
                }
7142
14
            }
7143
14
            return ret;
7144
14
        };
7145
7146
38.0k
        for (auto& [label_key, txn_keys] : recycle_txn_keys_by_label) {
7147
38.0k
            concurrent_delete_executor.add([&, txn_keys = std::move(txn_keys), label_key]() {
7148
38.0k
                VLOG_DEBUG << "recycle txn label group, key=" << hex(label_key)
7149
38.0k
                           << " txn_count=" << txn_keys.size();
7150
38.0k
                for (const auto& k : txn_keys) {
7151
38.0k
                    int ret = delete_recycle_txn_kv_with_retry(k);
7152
38.0k
                    if (ret != 0) {
7153
38.0k
                        LOG_WARNING("failed to delete recycle txn kv")
7154
38.0k
                                .tag("instance id", instance_id_)
7155
38.0k
                                .tag("key", hex(k))
7156
38.0k
                                .tag("label_key", hex(label_key));
7157
38.0k
                        return -1;
7158
38.0k
                    }
7159
38.0k
                }
7160
38.0k
                return 0;
7161
38.0k
            });
7162
38.0k
        }
7163
14
        bool finished = true;
7164
14
        std::vector<int> rets = concurrent_delete_executor.when_all(&finished);
7165
38.0k
        for (int r : rets) {
7166
38.0k
            if (r != 0) {
7167
2
                ret = -1;
7168
2
            }
7169
38.0k
        }
7170
7171
14
        ret = finished ? ret : -1;
7172
14
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::recycle_expired_txn_label.failure", &ret);
7173
7174
14
        if (ret != 0) {
7175
6
            LOG_WARNING("recycle txn kv ret!=0")
7176
6
                    .tag("finished", finished)
7177
6
                    .tag("ret", ret)
7178
6
                    .tag("instance_id", instance_id_);
7179
6
            return ret;
7180
6
        }
7181
8
        return ret;
7182
14
    };
7183
7184
    // recycle_func and loop_done for scan and recycle
7185
22
    return scan_and_recycle(begin_recycle_txn_key, end_recycle_txn_key,
7186
22
                            std::move(handle_recycle_txn_kv), std::move(loop_done));
7187
22
}
7188
7189
struct CopyJobIdTuple {
7190
    std::string instance_id;
7191
    std::string stage_id;
7192
    long table_id;
7193
    std::string copy_id;
7194
    std::string stage_path;
7195
};
7196
struct BatchObjStoreAccessor {
7197
    BatchObjStoreAccessor(std::shared_ptr<StorageVaultAccessor> accessor, uint64_t& batch_count,
7198
                          TxnKv* txn_kv)
7199
3
            : accessor_(std::move(accessor)), batch_count_(batch_count), txn_kv_(txn_kv) {};
7200
3
    ~BatchObjStoreAccessor() {
7201
3
        if (!paths_.empty()) {
7202
3
            consume();
7203
3
        }
7204
3
    }
7205
7206
    /**
7207
    * To implicitely do batch work and submit the batch delete task to s3
7208
    * The s3 delete opreations would be done in batches, and then delete CopyJobPB key one by one
7209
    *
7210
    * @param copy_job The protubuf struct consists of the copy job files.
7211
    * @param key The copy job's key on fdb, the key is originally occupied by fdb range iterator, to make sure
7212
    *            it would last until we finish the delete task, here we need pass one string value
7213
    * @param cope_job_id_tuple One tuple {log_trace instance_id, stage_id, table_id, query_id, stage_path} to print log
7214
    */
7215
5
    void add(CopyJobPB copy_job, std::string key, const CopyJobIdTuple cope_job_id_tuple) {
7216
5
        auto& [instance_id, stage_id, table_id, copy_id, path] = cope_job_id_tuple;
7217
5
        auto& file_keys = copy_file_keys_[key];
7218
5
        file_keys.log_trace =
7219
5
                fmt::format("instance_id={}, stage_id={}, table_id={}, query_id={}, path={}",
7220
5
                            instance_id, stage_id, table_id, copy_id, path);
7221
5
        std::string_view log_trace = file_keys.log_trace;
7222
2.03k
        for (const auto& file : copy_job.object_files()) {
7223
2.03k
            auto relative_path = file.relative_path();
7224
2.03k
            paths_.push_back(relative_path);
7225
2.03k
            file_keys.keys.push_back(copy_file_key(
7226
2.03k
                    {instance_id, stage_id, table_id, file.relative_path(), file.etag()}));
7227
2.03k
            LOG_INFO(log_trace)
7228
2.03k
                    .tag("relative_path", relative_path)
7229
2.03k
                    .tag("batch_count", batch_count_);
7230
2.03k
        }
7231
5
        LOG_INFO(log_trace)
7232
5
                .tag("objects_num", copy_job.object_files().size())
7233
5
                .tag("batch_count", batch_count_);
7234
        // 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
7235
        // recommend using delete objects when objects num is less than 10)
7236
5
        if (paths_.size() < 1000) {
7237
3
            return;
7238
3
        }
7239
2
        consume();
7240
2
    }
7241
7242
private:
7243
5
    void consume() {
7244
5
        DORIS_CLOUD_DEFER {
7245
5
            paths_.clear();
7246
5
            copy_file_keys_.clear();
7247
5
            batch_count_++;
7248
7249
5
            LOG_WARNING("begin to delete {} internal stage objects in batch {}", paths_.size(),
7250
5
                        batch_count_);
7251
5
        };
7252
7253
5
        StopWatch sw;
7254
        // TODO(yuejing): 在accessor的delete_objets的实现里可以考虑如果_paths数量不超过10个的话,就直接发10个delete objection operation而不是发post
7255
5
        if (0 != accessor_->delete_files(paths_)) {
7256
2
            LOG_WARNING("failed to delete {} internal stage objects in batch {} and it takes {} us",
7257
2
                        paths_.size(), batch_count_, sw.elapsed_us());
7258
2
            return;
7259
2
        }
7260
3
        LOG_WARNING("succeed to delete {} internal stage objects in batch {} and it takes {} us",
7261
3
                    paths_.size(), batch_count_, sw.elapsed_us());
7262
        // delete fdb's keys
7263
3
        for (auto& file_keys : copy_file_keys_) {
7264
3
            auto& [log_trace, keys] = file_keys.second;
7265
3
            std::unique_ptr<Transaction> txn;
7266
3
            if (txn_kv_->create_txn(&txn) != cloud::TxnErrorCode::TXN_OK) {
7267
0
                LOG(WARNING) << "failed to create txn";
7268
0
                continue;
7269
0
            }
7270
            // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7271
            // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7272
            // limited, should not cause the txn commit failed.
7273
1.02k
            for (const auto& key : keys) {
7274
1.02k
                txn->remove(key);
7275
1.02k
                LOG_INFO("remove copy_file_key={}, {}", hex(key), log_trace);
7276
1.02k
            }
7277
3
            txn->remove(file_keys.first);
7278
3
            if (auto ret = txn->commit(); ret != cloud::TxnErrorCode::TXN_OK) {
7279
0
                LOG(WARNING) << "failed to commit txn ret is " << ret;
7280
0
                continue;
7281
0
            }
7282
3
        }
7283
3
    }
7284
    std::shared_ptr<StorageVaultAccessor> accessor_;
7285
    // the path of the s3 files to be deleted
7286
    std::vector<std::string> paths_;
7287
    struct CopyFiles {
7288
        std::string log_trace;
7289
        std::vector<std::string> keys;
7290
    };
7291
    // pair<std::string, std::vector<std::string>>
7292
    // first: instance_id_ stage_id table_id query_id
7293
    // second: keys to be deleted
7294
    // <fdb key, <{instance_id_ stage_id table_id query_id}, file keys to be deleted>>
7295
    std::unordered_map<std::string, CopyFiles> copy_file_keys_;
7296
    // used to distinguish different batch tasks, the task log consists of thread ID and batch number
7297
    // which can together uniquely identifies different tasks for tracing log
7298
    uint64_t& batch_count_;
7299
    TxnKv* txn_kv_;
7300
};
7301
7302
13
int InstanceRecycler::recycle_copy_jobs() {
7303
13
    int64_t num_scanned = 0;
7304
13
    int64_t num_finished = 0;
7305
13
    int64_t num_expired = 0;
7306
13
    int64_t num_recycled = 0;
7307
    // Used for INTERNAL stage's copy jobs to tag each batch for log trace
7308
13
    uint64_t batch_count = 0;
7309
13
    const std::string task_name = "recycle_copy_jobs";
7310
13
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7311
7312
13
    LOG_WARNING("begin to recycle copy jobs").tag("instance_id", instance_id_);
7313
7314
13
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7315
13
    register_recycle_task(task_name, start_time);
7316
7317
13
    DORIS_CLOUD_DEFER {
7318
13
        unregister_recycle_task(task_name);
7319
13
        metrics_context.kv_scanned_num.set(num_scanned);
7320
13
        metrics_context.kv_expired_num.set(num_expired);
7321
13
        metrics_context.kv_recycled_num.set(num_recycled);
7322
13
        int64_t cost =
7323
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7324
13
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7325
13
                .tag("instance_id", instance_id_)
7326
13
                .tag("num_scanned", num_scanned)
7327
13
                .tag("num_finished", num_finished)
7328
13
                .tag("num_expired", num_expired)
7329
13
                .tag("num_recycled", num_recycled);
7330
13
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_0clEv
Line
Count
Source
7317
13
    DORIS_CLOUD_DEFER {
7318
13
        unregister_recycle_task(task_name);
7319
13
        metrics_context.kv_scanned_num.set(num_scanned);
7320
13
        metrics_context.kv_expired_num.set(num_expired);
7321
13
        metrics_context.kv_recycled_num.set(num_recycled);
7322
13
        int64_t cost =
7323
13
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7324
        LOG_WARNING("recycle copy jobs finished, cost={}s", cost)
7325
13
                .tag("instance_id", instance_id_)
7326
13
                .tag("num_scanned", num_scanned)
7327
13
                .tag("num_finished", num_finished)
7328
13
                .tag("num_expired", num_expired)
7329
13
                .tag("num_recycled", num_recycled);
7330
13
    };
7331
7332
13
    CopyJobKeyInfo key_info0 {instance_id_, "", 0, "", 0};
7333
13
    CopyJobKeyInfo key_info1 {instance_id_, "\xff", 0, "", 0};
7334
13
    std::string key0;
7335
13
    std::string key1;
7336
13
    copy_job_key(key_info0, &key0);
7337
13
    copy_job_key(key_info1, &key1);
7338
13
    std::unordered_map<std::string, std::shared_ptr<BatchObjStoreAccessor>> stage_accessor_map;
7339
13
    auto recycle_func = [&start_time, &num_scanned, &num_finished, &num_expired, &num_recycled,
7340
13
                         &batch_count, &stage_accessor_map, &task_name,
7341
16
                         this](std::string_view k, std::string_view v) -> int {
7342
16
        ++num_scanned;
7343
16
        CopyJobPB copy_job;
7344
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7345
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7346
0
            return -1;
7347
0
        }
7348
7349
        // decode copy job key
7350
16
        auto k1 = k;
7351
16
        k1.remove_prefix(1);
7352
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7353
16
        decode_key(&k1, &out);
7354
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7355
        // -> CopyJobPB
7356
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7357
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7358
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7359
7360
16
        bool check_storage = true;
7361
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7362
12
            ++num_finished;
7363
7364
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7365
7
                auto it = stage_accessor_map.find(stage_id);
7366
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7367
7
                std::string_view path;
7368
7
                if (it != stage_accessor_map.end()) {
7369
2
                    accessor = it->second;
7370
5
                } else {
7371
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7372
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7373
5
                                                      &inner_accessor);
7374
5
                    if (ret < 0) { // error
7375
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7376
0
                        return -1;
7377
5
                    } else if (ret == 0) {
7378
3
                        path = inner_accessor->uri();
7379
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7380
3
                                inner_accessor, batch_count, txn_kv_.get());
7381
3
                        stage_accessor_map.emplace(stage_id, accessor);
7382
3
                    } else { // stage not found, skip check storage
7383
2
                        check_storage = false;
7384
2
                    }
7385
5
                }
7386
7
                if (check_storage) {
7387
                    // TODO delete objects with key and etag is not supported
7388
5
                    accessor->add(std::move(copy_job), std::string(k),
7389
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7390
5
                    return 0;
7391
5
                }
7392
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7393
5
                int64_t current_time =
7394
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7395
5
                if (copy_job.finish_time_ms() > 0) {
7396
2
                    if (!config::force_immediate_recycle &&
7397
2
                        current_time < copy_job.finish_time_ms() +
7398
2
                                               config::copy_job_max_retention_second * 1000) {
7399
1
                        return 0;
7400
1
                    }
7401
3
                } else {
7402
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7403
3
                    if (!config::force_immediate_recycle &&
7404
3
                        current_time < copy_job.start_time_ms() +
7405
3
                                               config::copy_job_max_retention_second * 1000) {
7406
1
                        return 0;
7407
1
                    }
7408
3
                }
7409
5
            }
7410
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7411
4
            int64_t current_time =
7412
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7413
            // if copy job is timeout: delete all copy file kvs and copy job kv
7414
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7415
2
                return 0;
7416
2
            }
7417
4
        }
7418
7
        ++num_expired;
7419
7420
        // delete all copy files
7421
7
        std::vector<std::string> copy_file_keys;
7422
70
        for (auto& file : copy_job.object_files()) {
7423
70
            copy_file_keys.push_back(copy_file_key(
7424
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7425
70
        }
7426
7
        std::unique_ptr<Transaction> txn;
7427
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7428
0
            LOG(WARNING) << "failed to create txn";
7429
0
            return -1;
7430
0
        }
7431
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7432
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7433
        // limited, should not cause the txn commit failed.
7434
70
        for (const auto& key : copy_file_keys) {
7435
70
            txn->remove(key);
7436
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7437
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7438
70
                      << ", query_id=" << copy_id;
7439
70
        }
7440
7
        txn->remove(k);
7441
7
        TxnErrorCode err = txn->commit();
7442
7
        if (err != TxnErrorCode::TXN_OK) {
7443
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7444
0
            return -1;
7445
0
        }
7446
7447
7
        ++num_recycled;
7448
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7449
7
        return 0;
7450
7
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7341
16
                         this](std::string_view k, std::string_view v) -> int {
7342
16
        ++num_scanned;
7343
16
        CopyJobPB copy_job;
7344
16
        if (!copy_job.ParseFromArray(v.data(), v.size())) {
7345
0
            LOG_WARNING("malformed copy job").tag("key", hex(k));
7346
0
            return -1;
7347
0
        }
7348
7349
        // decode copy job key
7350
16
        auto k1 = k;
7351
16
        k1.remove_prefix(1);
7352
16
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
7353
16
        decode_key(&k1, &out);
7354
        // 0x01 "copy" ${instance_id} "job" ${stage_id} ${table_id} ${copy_id} ${group_id}
7355
        // -> CopyJobPB
7356
16
        const auto& stage_id = std::get<std::string>(std::get<0>(out[3]));
7357
16
        const auto& table_id = std::get<int64_t>(std::get<0>(out[4]));
7358
16
        const auto& copy_id = std::get<std::string>(std::get<0>(out[5]));
7359
7360
16
        bool check_storage = true;
7361
16
        if (copy_job.job_status() == CopyJobPB::FINISH) {
7362
12
            ++num_finished;
7363
7364
12
            if (copy_job.stage_type() == StagePB::INTERNAL) {
7365
7
                auto it = stage_accessor_map.find(stage_id);
7366
7
                std::shared_ptr<BatchObjStoreAccessor> accessor;
7367
7
                std::string_view path;
7368
7
                if (it != stage_accessor_map.end()) {
7369
2
                    accessor = it->second;
7370
5
                } else {
7371
5
                    std::shared_ptr<StorageVaultAccessor> inner_accessor;
7372
5
                    auto ret = init_copy_job_accessor(stage_id, copy_job.stage_type(),
7373
5
                                                      &inner_accessor);
7374
5
                    if (ret < 0) { // error
7375
0
                        LOG_WARNING("Failed to init_copy_job_accessor due to error code {}", ret);
7376
0
                        return -1;
7377
5
                    } else if (ret == 0) {
7378
3
                        path = inner_accessor->uri();
7379
3
                        accessor = std::make_shared<BatchObjStoreAccessor>(
7380
3
                                inner_accessor, batch_count, txn_kv_.get());
7381
3
                        stage_accessor_map.emplace(stage_id, accessor);
7382
3
                    } else { // stage not found, skip check storage
7383
2
                        check_storage = false;
7384
2
                    }
7385
5
                }
7386
7
                if (check_storage) {
7387
                    // TODO delete objects with key and etag is not supported
7388
5
                    accessor->add(std::move(copy_job), std::string(k),
7389
5
                                  {instance_id_, stage_id, table_id, copy_id, std::string(path)});
7390
5
                    return 0;
7391
5
                }
7392
7
            } else if (copy_job.stage_type() == StagePB::EXTERNAL) {
7393
5
                int64_t current_time =
7394
5
                        duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7395
5
                if (copy_job.finish_time_ms() > 0) {
7396
2
                    if (!config::force_immediate_recycle &&
7397
2
                        current_time < copy_job.finish_time_ms() +
7398
2
                                               config::copy_job_max_retention_second * 1000) {
7399
1
                        return 0;
7400
1
                    }
7401
3
                } else {
7402
                    // For compatibility, copy job does not contain finish time before 2.2.2, use start time
7403
3
                    if (!config::force_immediate_recycle &&
7404
3
                        current_time < copy_job.start_time_ms() +
7405
3
                                               config::copy_job_max_retention_second * 1000) {
7406
1
                        return 0;
7407
1
                    }
7408
3
                }
7409
5
            }
7410
12
        } else if (copy_job.job_status() == CopyJobPB::LOADING) {
7411
4
            int64_t current_time =
7412
4
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
7413
            // if copy job is timeout: delete all copy file kvs and copy job kv
7414
4
            if (!config::force_immediate_recycle && current_time <= copy_job.timeout_time_ms()) {
7415
2
                return 0;
7416
2
            }
7417
4
        }
7418
7
        ++num_expired;
7419
7420
        // delete all copy files
7421
7
        std::vector<std::string> copy_file_keys;
7422
70
        for (auto& file : copy_job.object_files()) {
7423
70
            copy_file_keys.push_back(copy_file_key(
7424
70
                    {instance_id_, stage_id, table_id, file.relative_path(), file.etag()}));
7425
70
        }
7426
7
        std::unique_ptr<Transaction> txn;
7427
7
        if (txn_kv_->create_txn(&txn) != TxnErrorCode::TXN_OK) {
7428
0
            LOG(WARNING) << "failed to create txn";
7429
0
            return -1;
7430
0
        }
7431
        // FIXME: We have already limited the file num and file meta size when selecting file in FE.
7432
        // And if too many copy files, begin_copy failed commit too. So here the copy file keys are
7433
        // limited, should not cause the txn commit failed.
7434
70
        for (const auto& key : copy_file_keys) {
7435
70
            txn->remove(key);
7436
70
            LOG(INFO) << "remove copy_file_key=" << hex(key) << ", instance_id=" << instance_id_
7437
70
                      << ", stage_id=" << stage_id << ", table_id=" << table_id
7438
70
                      << ", query_id=" << copy_id;
7439
70
        }
7440
7
        txn->remove(k);
7441
7
        TxnErrorCode err = txn->commit();
7442
7
        if (err != TxnErrorCode::TXN_OK) {
7443
0
            LOG(WARNING) << "failed to commit txn, err=" << err;
7444
0
            return -1;
7445
0
        }
7446
7447
7
        ++num_recycled;
7448
7
        check_recycle_task(instance_id_, task_name, num_scanned, num_recycled, start_time);
7449
7
        return 0;
7450
7
    };
7451
7452
13
    auto loop_done = [&]() -> int {
7453
3
        DORIS_CLOUD_DEFER {
7454
3
            metrics_context.kv_scanned_num.set(num_scanned);
7455
3
            metrics_context.kv_expired_num.set(num_expired);
7456
3
            metrics_context.kv_recycled_num.set(num_recycled);
7457
3
            metrics_context.update_metrics();
7458
3
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7453
3
        DORIS_CLOUD_DEFER {
7454
3
            metrics_context.kv_scanned_num.set(num_scanned);
7455
3
            metrics_context.kv_expired_num.set(num_expired);
7456
3
            metrics_context.kv_recycled_num.set(num_recycled);
7457
3
            metrics_context.update_metrics();
7458
3
        };
7459
3
        return 0;
7460
3
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler17recycle_copy_jobsEvENK3$_1clEv
Line
Count
Source
7452
3
    auto loop_done = [&]() -> int {
7453
3
        DORIS_CLOUD_DEFER {
7454
3
            metrics_context.kv_scanned_num.set(num_scanned);
7455
3
            metrics_context.kv_expired_num.set(num_expired);
7456
3
            metrics_context.kv_recycled_num.set(num_recycled);
7457
3
            metrics_context.update_metrics();
7458
3
        };
7459
3
        return 0;
7460
3
    };
7461
7462
    // recycle_func and loop_done for scan and recycle
7463
13
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7464
13
}
7465
7466
int InstanceRecycler::init_copy_job_accessor(const std::string& stage_id,
7467
                                             const StagePB::StageType& stage_type,
7468
5
                                             std::shared_ptr<StorageVaultAccessor>* accessor) {
7469
5
#ifdef UNIT_TEST
7470
    // In unit test, external use the same accessor as the internal stage
7471
5
    auto it = accessor_map_.find(stage_id);
7472
5
    if (it != accessor_map_.end()) {
7473
3
        *accessor = it->second;
7474
3
    } else {
7475
2
        std::cout << "UT can not find accessor with stage_id: " << stage_id << std::endl;
7476
2
        return 1;
7477
2
    }
7478
#else
7479
    // init s3 accessor and add to accessor map
7480
    auto stage_it =
7481
            std::find_if(instance_info_.stages().begin(), instance_info_.stages().end(),
7482
                         [&stage_id](auto&& stage) { return stage.stage_id() == stage_id; });
7483
7484
    if (stage_it == instance_info_.stages().end()) {
7485
        LOG(INFO) << "Recycle nonexisted stage copy jobs. instance_id=" << instance_id_
7486
                  << ", stage_id=" << stage_id << ", stage_type=" << stage_type;
7487
        return 1;
7488
    }
7489
7490
    const auto& object_store_info = stage_it->obj_info();
7491
    auto stage_access_type = stage_it->has_access_type() ? stage_it->access_type() : StagePB::AKSK;
7492
7493
    S3Conf s3_conf;
7494
    if (stage_type == StagePB::EXTERNAL) {
7495
        if (stage_access_type == StagePB::AKSK) {
7496
            auto conf = S3Conf::from_obj_store_info(object_store_info);
7497
            if (!conf) {
7498
                return -1;
7499
            }
7500
7501
            s3_conf = std::move(*conf);
7502
        } else if (stage_access_type == StagePB::BUCKET_ACL) {
7503
            auto conf = S3Conf::from_obj_store_info(object_store_info, true /* skip_aksk */);
7504
            if (!conf) {
7505
                return -1;
7506
            }
7507
7508
            s3_conf = std::move(*conf);
7509
            if (instance_info_.ram_user().has_encryption_info()) {
7510
                AkSkPair plain_ak_sk_pair;
7511
                int ret = decrypt_ak_sk_helper(
7512
                        instance_info_.ram_user().ak(), instance_info_.ram_user().sk(),
7513
                        instance_info_.ram_user().encryption_info(), &plain_ak_sk_pair);
7514
                if (ret != 0) {
7515
                    LOG(WARNING) << "fail to decrypt ak sk. instance_id: " << instance_id_
7516
                                 << " ram_user: " << proto_to_json(instance_info_.ram_user());
7517
                    return -1;
7518
                }
7519
                s3_conf.ak = std::move(plain_ak_sk_pair.first);
7520
                s3_conf.sk = std::move(plain_ak_sk_pair.second);
7521
            } else {
7522
                s3_conf.ak = instance_info_.ram_user().ak();
7523
                s3_conf.sk = instance_info_.ram_user().sk();
7524
            }
7525
        } else {
7526
            LOG(INFO) << "Unsupported stage access type=" << stage_access_type
7527
                      << ", instance_id=" << instance_id_ << ", stage_id=" << stage_id;
7528
            return -1;
7529
        }
7530
    } else if (stage_type == StagePB::INTERNAL) {
7531
        int idx = stoi(object_store_info.id());
7532
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7533
            LOG(WARNING) << "invalid idx: " << idx;
7534
            return -1;
7535
        }
7536
7537
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7538
        auto conf = S3Conf::from_obj_store_info(old_obj);
7539
        if (!conf) {
7540
            return -1;
7541
        }
7542
7543
        s3_conf = std::move(*conf);
7544
        s3_conf.prefix = object_store_info.prefix();
7545
    } else {
7546
        LOG(WARNING) << "unknown stage type " << stage_type;
7547
        return -1;
7548
    }
7549
7550
    std::shared_ptr<S3Accessor> s3_accessor;
7551
    int ret = S3Accessor::create(std::move(s3_conf), &s3_accessor);
7552
    if (ret != 0) {
7553
        LOG(WARNING) << "failed to init s3 accessor ret=" << ret;
7554
        return -1;
7555
    }
7556
7557
    *accessor = std::move(s3_accessor);
7558
#endif
7559
3
    return 0;
7560
5
}
7561
7562
11
int InstanceRecycler::recycle_stage() {
7563
11
    int64_t num_scanned = 0;
7564
11
    int64_t num_expired = 0;
7565
11
    int64_t num_recycled = 0;
7566
11
    const std::string task_name = "recycle_stage";
7567
11
    RecyclerMetricsContext metrics_context(instance_id_, task_name);
7568
7569
11
    LOG_WARNING("begin to recycle stage").tag("instance_id", instance_id_);
7570
7571
11
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7572
11
    register_recycle_task(task_name, start_time);
7573
7574
11
    DORIS_CLOUD_DEFER {
7575
11
        metrics_context.kv_scanned_num.set(num_scanned);
7576
11
        metrics_context.kv_expired_num.set(num_expired);
7577
11
        metrics_context.kv_recycled_num.set(num_recycled);
7578
11
        unregister_recycle_task(task_name);
7579
11
        int64_t cost =
7580
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7581
11
        LOG_WARNING("recycle stage, cost={}s", cost)
7582
11
                .tag("instance_id", instance_id_)
7583
11
                .tag("num_scanned", num_scanned)
7584
11
                .tag("num_recycled", num_recycled);
7585
11
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_0clEv
Line
Count
Source
7574
11
    DORIS_CLOUD_DEFER {
7575
11
        metrics_context.kv_scanned_num.set(num_scanned);
7576
11
        metrics_context.kv_expired_num.set(num_expired);
7577
11
        metrics_context.kv_recycled_num.set(num_recycled);
7578
11
        unregister_recycle_task(task_name);
7579
11
        int64_t cost =
7580
11
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7581
        LOG_WARNING("recycle stage, cost={}s", cost)
7582
11
                .tag("instance_id", instance_id_)
7583
11
                .tag("num_scanned", num_scanned)
7584
11
                .tag("num_recycled", num_recycled);
7585
11
    };
7586
7587
11
    RecycleStageKeyInfo key_info0 {instance_id_, ""};
7588
11
    RecycleStageKeyInfo key_info1 {instance_id_, "\xff"};
7589
11
    std::string key0 = recycle_stage_key(key_info0);
7590
11
    std::string key1 = recycle_stage_key(key_info1);
7591
7592
11
    std::vector<std::string_view> stage_keys;
7593
11
    auto recycle_func = [&start_time, &num_scanned, &num_expired, &num_recycled, &stage_keys, this](
7594
11
                                std::string_view k, std::string_view v) -> int {
7595
1
        ++num_scanned;
7596
1
        RecycleStagePB recycle_stage;
7597
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7598
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7599
0
            return -1;
7600
0
        }
7601
7602
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7603
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7604
0
            LOG(WARNING) << "invalid idx: " << idx;
7605
0
            return -1;
7606
0
        }
7607
7608
1
        ++num_expired;
7609
7610
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7611
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7612
1
                [&] {
7613
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7614
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7615
1
                    if (!s3_conf) {
7616
1
                        return -1;
7617
1
                    }
7618
7619
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7620
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7621
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7622
1
                    if (ret != 0) {
7623
1
                        return -1;
7624
1
                    }
7625
7626
1
                    accessor = std::move(s3_accessor);
7627
1
                    return 0;
7628
1
                }(),
7629
1
                "recycle_stage:get_accessor", &accessor);
7630
7631
1
        if (ret != 0) {
7632
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7633
0
            return ret;
7634
0
        }
7635
7636
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7637
1
                .tag("instance_id", instance_id_)
7638
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7639
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7640
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7641
1
                .tag("obj_info_id", idx)
7642
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7643
1
        ret = accessor->delete_all();
7644
1
        if (ret != 0) {
7645
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7646
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7647
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7648
0
                         << ", ret=" << ret;
7649
0
            return -1;
7650
0
        }
7651
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7652
1
        stage_keys.push_back(k);
7653
1
        return 0;
7654
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_2clESt17basic_string_viewIcSt11char_traitsIcEES6_
Line
Count
Source
7594
1
                                std::string_view k, std::string_view v) -> int {
7595
1
        ++num_scanned;
7596
1
        RecycleStagePB recycle_stage;
7597
1
        if (!recycle_stage.ParseFromArray(v.data(), v.size())) {
7598
0
            LOG_WARNING("malformed recycle stage").tag("key", hex(k));
7599
0
            return -1;
7600
0
        }
7601
7602
1
        int idx = stoi(recycle_stage.stage().obj_info().id());
7603
1
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7604
0
            LOG(WARNING) << "invalid idx: " << idx;
7605
0
            return -1;
7606
0
        }
7607
7608
1
        ++num_expired;
7609
7610
1
        std::shared_ptr<StorageVaultAccessor> accessor;
7611
1
        int ret = SYNC_POINT_HOOK_RETURN_VALUE(
7612
1
                [&] {
7613
1
                    auto& old_obj = instance_info_.obj_info()[idx - 1];
7614
1
                    auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7615
1
                    if (!s3_conf) {
7616
1
                        return -1;
7617
1
                    }
7618
7619
1
                    s3_conf->prefix = recycle_stage.stage().obj_info().prefix();
7620
1
                    std::shared_ptr<S3Accessor> s3_accessor;
7621
1
                    int ret = S3Accessor::create(std::move(s3_conf.value()), &s3_accessor);
7622
1
                    if (ret != 0) {
7623
1
                        return -1;
7624
1
                    }
7625
7626
1
                    accessor = std::move(s3_accessor);
7627
1
                    return 0;
7628
1
                }(),
7629
1
                "recycle_stage:get_accessor", &accessor);
7630
7631
1
        if (ret != 0) {
7632
0
            LOG(WARNING) << "failed to init accessor ret=" << ret;
7633
0
            return ret;
7634
0
        }
7635
7636
1
        LOG_WARNING("begin to delete objects of dropped internal stage")
7637
1
                .tag("instance_id", instance_id_)
7638
1
                .tag("stage_id", recycle_stage.stage().stage_id())
7639
1
                .tag("user_name", recycle_stage.stage().mysql_user_name()[0])
7640
1
                .tag("user_id", recycle_stage.stage().mysql_user_id()[0])
7641
1
                .tag("obj_info_id", idx)
7642
1
                .tag("prefix", recycle_stage.stage().obj_info().prefix());
7643
1
        ret = accessor->delete_all();
7644
1
        if (ret != 0) {
7645
0
            LOG(WARNING) << "failed to delete objects of dropped internal stage. instance_id="
7646
0
                         << instance_id_ << ", stage_id=" << recycle_stage.stage().stage_id()
7647
0
                         << ", prefix=" << recycle_stage.stage().obj_info().prefix()
7648
0
                         << ", ret=" << ret;
7649
0
            return -1;
7650
0
        }
7651
1
        check_recycle_task(instance_id_, "recycle_stage", num_scanned, num_recycled, start_time);
7652
1
        stage_keys.push_back(k);
7653
1
        return 0;
7654
1
    };
7655
7656
11
    auto loop_done = [&stage_keys, &metrics_context, &num_scanned, &num_expired, &num_recycled,
7657
11
                      this]() -> int {
7658
1
        DORIS_CLOUD_DEFER {
7659
1
            metrics_context.kv_scanned_num.set(num_scanned);
7660
1
            metrics_context.kv_expired_num.set(num_expired);
7661
1
            metrics_context.kv_recycled_num.set(num_recycled);
7662
1
            metrics_context.update_metrics();
7663
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE_clEv
Line
Count
Source
7658
1
        DORIS_CLOUD_DEFER {
7659
1
            metrics_context.kv_scanned_num.set(num_scanned);
7660
1
            metrics_context.kv_expired_num.set(num_expired);
7661
1
            metrics_context.kv_recycled_num.set(num_recycled);
7662
1
            metrics_context.update_metrics();
7663
1
        };
7664
1
        if (stage_keys.empty()) return 0;
7665
1
        DORIS_CLOUD_DEFER {
7666
1
            stage_keys.clear();
7667
1
        };
Unexecuted instantiation: recycler.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE0_clEv
recycler_test.cpp:_ZZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEvENKUlvE0_clEv
Line
Count
Source
7665
1
        DORIS_CLOUD_DEFER {
7666
1
            stage_keys.clear();
7667
1
        };
7668
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7669
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7670
0
            return -1;
7671
0
        }
7672
        // Count only after the recycle KV keys are successfully deleted.
7673
1
        num_recycled += stage_keys.size();
7674
1
        return 0;
7675
1
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler13recycle_stageEvENK3$_1clEv
Line
Count
Source
7657
1
                      this]() -> int {
7658
1
        DORIS_CLOUD_DEFER {
7659
1
            metrics_context.kv_scanned_num.set(num_scanned);
7660
1
            metrics_context.kv_expired_num.set(num_expired);
7661
1
            metrics_context.kv_recycled_num.set(num_recycled);
7662
1
            metrics_context.update_metrics();
7663
1
        };
7664
1
        if (stage_keys.empty()) return 0;
7665
1
        DORIS_CLOUD_DEFER {
7666
1
            stage_keys.clear();
7667
1
        };
7668
1
        if (0 != txn_remove(txn_kv_.get(), stage_keys)) {
7669
0
            LOG(WARNING) << "failed to delete recycle partition kv, instance_id=" << instance_id_;
7670
0
            return -1;
7671
0
        }
7672
        // Count only after the recycle KV keys are successfully deleted.
7673
1
        num_recycled += stage_keys.size();
7674
1
        return 0;
7675
1
    };
7676
    // recycle_func and loop_done for scan and recycle
7677
11
    return scan_and_recycle(key0, key1, std::move(recycle_func), std::move(loop_done));
7678
11
}
7679
7680
10
int InstanceRecycler::recycle_expired_stage_objects() {
7681
10
    LOG_WARNING("begin to recycle expired stage objects").tag("instance_id", instance_id_);
7682
7683
10
    int64_t start_time = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7684
10
    RecyclerMetricsContext metrics_context(instance_id_, "recycle_expired_stage_objects");
7685
10
    int64_t num_scanned = 0;
7686
10
    int64_t num_expired = 0;
7687
10
    int64_t num_recycled = 0;
7688
7689
10
    DORIS_CLOUD_DEFER {
7690
10
        metrics_context.kv_scanned_num.set(num_scanned);
7691
10
        metrics_context.kv_expired_num.set(num_expired);
7692
10
        metrics_context.kv_recycled_num.set(num_recycled);
7693
10
        int64_t cost =
7694
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7695
10
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7696
10
                .tag("instance_id", instance_id_);
7697
10
    };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_0clEv
Line
Count
Source
7689
10
    DORIS_CLOUD_DEFER {
7690
10
        metrics_context.kv_scanned_num.set(num_scanned);
7691
10
        metrics_context.kv_expired_num.set(num_expired);
7692
10
        metrics_context.kv_recycled_num.set(num_recycled);
7693
10
        int64_t cost =
7694
10
                duration_cast<seconds>(steady_clock::now().time_since_epoch()).count() - start_time;
7695
        LOG_WARNING("recycle expired stage objects, cost={}s", cost)
7696
10
                .tag("instance_id", instance_id_);
7697
10
    };
7698
7699
10
    int ret = 0;
7700
7701
10
    for (const auto& stage : instance_info_.stages()) {
7702
0
        std::stringstream ss;
7703
0
        ss << "instance_id=" << instance_id_ << ", stage_id=" << stage.stage_id() << ", user_name="
7704
0
           << (stage.mysql_user_name().empty() ? "null" : stage.mysql_user_name().at(0))
7705
0
           << ", user_id=" << (stage.mysql_user_id().empty() ? "null" : stage.mysql_user_id().at(0))
7706
0
           << ", prefix=" << stage.obj_info().prefix();
7707
7708
0
        DORIS_CLOUD_DEFER {
7709
0
            metrics_context.kv_scanned_num.set(num_scanned);
7710
0
            metrics_context.kv_expired_num.set(num_expired);
7711
0
            metrics_context.kv_recycled_num.set(num_recycled);
7712
0
            metrics_context.update_metrics();
7713
0
        };
Unexecuted instantiation: recycler.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_1clEv
Unexecuted instantiation: recycler_test.cpp:_ZZN5doris5cloud16InstanceRecycler29recycle_expired_stage_objectsEvENK3$_1clEv
7714
7715
0
        if (stopped()) {
7716
0
            break;
7717
0
        }
7718
0
        if (stage.type() == StagePB::EXTERNAL) {
7719
0
            continue;
7720
0
        }
7721
7722
0
        int idx = stoi(stage.obj_info().id());
7723
0
        if (idx > instance_info_.obj_info().size() || idx < 1) {
7724
0
            LOG(WARNING) << "invalid idx: " << idx << ", id: " << stage.obj_info().id();
7725
0
            continue;
7726
0
        }
7727
7728
0
        const auto& old_obj = instance_info_.obj_info()[idx - 1];
7729
0
        auto s3_conf = S3Conf::from_obj_store_info(old_obj);
7730
0
        if (!s3_conf) {
7731
0
            LOG(WARNING) << "failed to init s3_conf with obj_info=" << old_obj.ShortDebugString();
7732
0
            continue;
7733
0
        }
7734
7735
0
        s3_conf->prefix = stage.obj_info().prefix();
7736
0
        std::shared_ptr<S3Accessor> accessor;
7737
0
        int ret1 = S3Accessor::create(*s3_conf, &accessor);
7738
0
        if (ret1 != 0) {
7739
0
            LOG(WARNING) << "failed to init s3 accessor ret=" << ret1 << " " << ss.str();
7740
0
            ret = -1;
7741
0
            continue;
7742
0
        }
7743
7744
0
        if (s3_conf->prefix.find("/stage/") == std::string::npos) {
7745
0
            LOG(WARNING) << "try to delete illegal prefix, which is catastrophic, " << ss.str();
7746
0
            ret = -1;
7747
0
            continue;
7748
0
        }
7749
0
        ++num_scanned;
7750
7751
0
        LOG(INFO) << "recycle expired stage objects, " << ss.str();
7752
0
        int64_t expiration_time =
7753
0
                duration_cast<seconds>(system_clock::now().time_since_epoch()).count() -
7754
0
                config::internal_stage_objects_expire_time_second;
7755
0
        if (config::force_immediate_recycle) {
7756
0
            expiration_time = INT64_MAX;
7757
0
        }
7758
0
        ret1 = accessor->delete_all(expiration_time);
7759
0
        if (ret1 != 0) {
7760
0
            LOG(WARNING) << "failed to recycle expired stage objects, ret=" << ret1 << " "
7761
0
                         << ss.str();
7762
0
            ret = -1;
7763
0
            continue;
7764
0
        }
7765
0
        ++num_expired;
7766
0
        ++num_recycled;
7767
        // Note: this function only deletes S3 objects, not KV keys; no kv_recycled_num update.
7768
0
    }
7769
10
    return ret;
7770
10
}
7771
7772
228
void InstanceRecycler::register_recycle_task(const std::string& task_name, int64_t start_time) {
7773
228
    std::lock_guard lock(recycle_tasks_mutex);
7774
228
    running_recycle_tasks[task_name] = start_time;
7775
228
}
7776
7777
228
void InstanceRecycler::unregister_recycle_task(const std::string& task_name) {
7778
228
    std::lock_guard lock(recycle_tasks_mutex);
7779
228
    DCHECK(running_recycle_tasks[task_name] > 0);
7780
228
    running_recycle_tasks.erase(task_name);
7781
228
}
7782
7783
21
bool InstanceRecycler::check_recycle_tasks() {
7784
21
    std::map<std::string, int64_t> tmp_running_recycle_tasks;
7785
21
    {
7786
21
        std::lock_guard lock(recycle_tasks_mutex);
7787
21
        tmp_running_recycle_tasks = running_recycle_tasks;
7788
21
    }
7789
7790
21
    bool found = false;
7791
21
    int64_t now = duration_cast<seconds>(steady_clock::now().time_since_epoch()).count();
7792
21
    for (auto& [task_name, start_time] : tmp_running_recycle_tasks) {
7793
20
        int64_t cost = now - start_time;
7794
20
        if (cost > config::recycle_task_threshold_seconds) [[unlikely]] {
7795
20
            LOG_INFO("recycle task cost too much time cost={}s", cost)
7796
20
                    .tag("instance_id", instance_id_)
7797
20
                    .tag("task", task_name);
7798
20
            found = true;
7799
20
        }
7800
20
    }
7801
7802
21
    return found;
7803
21
}
7804
7805
int InstanceRecycler::classify_rowset_task_by_ref_count(
7806
60
        RowsetDeleteTask& task, std::vector<RowsetDeleteTask>& batch_delete_tasks) {
7807
60
    constexpr int MAX_RETRY = 10;
7808
60
    const auto& rowset_meta = task.rowset_meta;
7809
60
    int64_t tablet_id = rowset_meta.tablet_id();
7810
60
    const std::string& rowset_id = rowset_meta.rowset_id_v2();
7811
60
    std::string_view reference_instance_id = instance_id_;
7812
60
    if (rowset_meta.has_reference_instance_id()) {
7813
5
        reference_instance_id = rowset_meta.reference_instance_id();
7814
5
    }
7815
7816
61
    for (int i = 0; i < MAX_RETRY; ++i) {
7817
61
        std::unique_ptr<Transaction> txn;
7818
61
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7819
61
        if (err != TxnErrorCode::TXN_OK) {
7820
0
            LOG_WARNING("failed to create txn when classifying rowset task")
7821
0
                    .tag("instance_id", instance_id_)
7822
0
                    .tag("tablet_id", tablet_id)
7823
0
                    .tag("rowset_id", rowset_id)
7824
0
                    .tag("err", err);
7825
0
            return -1;
7826
0
        }
7827
7828
61
        std::string rowset_ref_count_key =
7829
61
                versioned::data_rowset_ref_count_key({reference_instance_id, tablet_id, rowset_id});
7830
61
        task.rowset_ref_count_key = rowset_ref_count_key;
7831
7832
61
        int64_t ref_count = 0;
7833
61
        {
7834
61
            std::string value;
7835
61
            TxnErrorCode err = txn->get(rowset_ref_count_key, &value);
7836
61
            if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
7837
0
                ref_count = 1;
7838
61
            } else if (err != TxnErrorCode::TXN_OK) {
7839
0
                LOG_WARNING("failed to get rowset ref count key when classifying")
7840
0
                        .tag("instance_id", instance_id_)
7841
0
                        .tag("tablet_id", tablet_id)
7842
0
                        .tag("rowset_id", rowset_id)
7843
0
                        .tag("err", err);
7844
0
                return -1;
7845
61
            } else if (!txn->decode_atomic_int(value, &ref_count)) {
7846
0
                LOG_WARNING("failed to decode rowset data ref count when classifying")
7847
0
                        .tag("instance_id", instance_id_)
7848
0
                        .tag("tablet_id", tablet_id)
7849
0
                        .tag("rowset_id", rowset_id)
7850
0
                        .tag("value", hex(value));
7851
0
                return -1;
7852
0
            }
7853
61
        }
7854
7855
61
        if (ref_count > 1) {
7856
            // ref_count > 1: decrement count, remove recycle keys, don't add to batch delete
7857
12
            txn->atomic_add(rowset_ref_count_key, -1);
7858
12
            LOG_INFO("decrease rowset data ref count in classification phase")
7859
12
                    .tag("instance_id", instance_id_)
7860
12
                    .tag("tablet_id", tablet_id)
7861
12
                    .tag("rowset_id", rowset_id)
7862
12
                    .tag("ref_count", ref_count - 1)
7863
12
                    .tag("ref_count_key", hex(rowset_ref_count_key));
7864
7865
12
            if (!task.recycle_rowset_key.empty()) {
7866
0
                txn->remove(task.recycle_rowset_key);
7867
0
                LOG_INFO("remove recycle rowset key in classification phase")
7868
0
                        .tag("key", hex(task.recycle_rowset_key));
7869
0
            }
7870
12
            if (!task.non_versioned_rowset_key.empty()) {
7871
12
                txn->remove(task.non_versioned_rowset_key);
7872
12
                LOG_INFO("remove non versioned rowset key in classification phase")
7873
12
                        .tag("key", hex(task.non_versioned_rowset_key));
7874
12
            }
7875
7876
12
            err = txn->commit();
7877
12
            if (err == TxnErrorCode::TXN_CONFLICT) {
7878
1
                VLOG_DEBUG << "decrease rowset ref count but txn conflict in classification, retry"
7879
0
                           << " tablet_id=" << tablet_id << " rowset_id=" << rowset_id
7880
0
                           << ", ref_count=" << ref_count << ", retry=" << i;
7881
1
                std::this_thread::sleep_for(std::chrono::milliseconds(500));
7882
1
                continue;
7883
11
            } else if (err != TxnErrorCode::TXN_OK) {
7884
0
                LOG_WARNING("failed to commit txn when classifying rowset task")
7885
0
                        .tag("instance_id", instance_id_)
7886
0
                        .tag("tablet_id", tablet_id)
7887
0
                        .tag("rowset_id", rowset_id)
7888
0
                        .tag("err", err);
7889
0
                return -1;
7890
0
            }
7891
11
            return 1; // handled, not added to batch delete
7892
49
        } else {
7893
            // ref_count == 1: Add to batch delete plan without modifying any KV.
7894
            // Keep recycle_rowset_key as "pending recycle" marker until data is actually deleted.
7895
49
            LOG_INFO("add rowset to batch delete plan")
7896
49
                    .tag("instance_id", instance_id_)
7897
49
                    .tag("tablet_id", tablet_id)
7898
49
                    .tag("rowset_id", rowset_id)
7899
49
                    .tag("resource_id", rowset_meta.resource_id())
7900
49
                    .tag("ref_count", ref_count);
7901
7902
49
            batch_delete_tasks.push_back(std::move(task));
7903
49
            return 0; // added to batch delete
7904
49
        }
7905
61
    }
7906
7907
0
    LOG_WARNING("failed to classify rowset task after retry")
7908
0
            .tag("instance_id", instance_id_)
7909
0
            .tag("tablet_id", tablet_id)
7910
0
            .tag("rowset_id", rowset_id)
7911
0
            .tag("retry", MAX_RETRY);
7912
0
    return -1;
7913
60
}
7914
7915
10
int InstanceRecycler::cleanup_rowset_metadata(const std::vector<RowsetDeleteTask>& tasks) {
7916
10
    int ret = 0;
7917
49
    for (const auto& task : tasks) {
7918
49
        int64_t tablet_id = task.rowset_meta.tablet_id();
7919
49
        const std::string& rowset_id = task.rowset_meta.rowset_id_v2();
7920
7921
        // Note: decrement_packed_file_ref_counts is already called in delete_rowset_data,
7922
        // so we don't need to call it again here.
7923
7924
        // Remove all metadata keys in one transaction
7925
49
        std::unique_ptr<Transaction> txn;
7926
49
        TxnErrorCode err = txn_kv_->create_txn(&txn);
7927
49
        if (err != TxnErrorCode::TXN_OK) {
7928
0
            LOG_WARNING("failed to create txn when cleaning up metadata")
7929
0
                    .tag("instance_id", instance_id_)
7930
0
                    .tag("tablet_id", tablet_id)
7931
0
                    .tag("rowset_id", rowset_id)
7932
0
                    .tag("err", err);
7933
0
            ret = -1;
7934
0
            continue;
7935
0
        }
7936
7937
49
        std::string_view reference_instance_id = instance_id_;
7938
49
        if (task.rowset_meta.has_reference_instance_id()) {
7939
5
            reference_instance_id = task.rowset_meta.reference_instance_id();
7940
5
        }
7941
7942
49
        txn->remove(task.rowset_ref_count_key);
7943
49
        LOG_INFO("delete rowset data ref count key in cleanup phase")
7944
49
                .tag("instance_id", instance_id_)
7945
49
                .tag("tablet_id", tablet_id)
7946
49
                .tag("rowset_id", rowset_id)
7947
49
                .tag("ref_count_key", hex(task.rowset_ref_count_key));
7948
7949
49
        std::string dbm_start_key =
7950
49
                meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id, 0, 0});
7951
49
        std::string dbm_end_key = meta_delete_bitmap_key(
7952
49
                {reference_instance_id, tablet_id, rowset_id, std::numeric_limits<int64_t>::max(),
7953
49
                 std::numeric_limits<int64_t>::max()});
7954
49
        txn->remove(dbm_start_key, dbm_end_key);
7955
49
        LOG_INFO("remove delete bitmap kv in cleanup phase")
7956
49
                .tag("instance_id", instance_id_)
7957
49
                .tag("tablet_id", tablet_id)
7958
49
                .tag("rowset_id", rowset_id)
7959
49
                .tag("begin", hex(dbm_start_key))
7960
49
                .tag("end", hex(dbm_end_key));
7961
7962
49
        std::string versioned_dbm_start_key =
7963
49
                versioned::meta_delete_bitmap_key({reference_instance_id, tablet_id, rowset_id});
7964
49
        std::string versioned_dbm_end_key = versioned_dbm_start_key;
7965
49
        encode_int64(INT64_MAX, &versioned_dbm_end_key);
7966
49
        txn->remove(versioned_dbm_start_key, versioned_dbm_end_key);
7967
49
        LOG_INFO("remove versioned delete bitmap kv in cleanup phase")
7968
49
                .tag("instance_id", instance_id_)
7969
49
                .tag("tablet_id", tablet_id)
7970
49
                .tag("rowset_id", rowset_id)
7971
49
                .tag("begin", hex(versioned_dbm_start_key))
7972
49
                .tag("end", hex(versioned_dbm_end_key));
7973
7974
        // Remove versioned meta rowset key
7975
49
        if (!task.versioned_rowset_key.empty()) {
7976
49
            versioned::document_remove<RowsetMetaCloudPB>(txn.get(), task.versioned_rowset_key,
7977
49
                                                          task.versionstamp);
7978
49
            LOG_INFO("remove versioned meta rowset key in cleanup phase")
7979
49
                    .tag("instance_id", instance_id_)
7980
49
                    .tag("tablet_id", tablet_id)
7981
49
                    .tag("rowset_id", rowset_id)
7982
49
                    .tag("key_prefix", hex(task.versioned_rowset_key));
7983
49
        }
7984
7985
49
        if (!task.non_versioned_rowset_key.empty()) {
7986
49
            txn->remove(task.non_versioned_rowset_key);
7987
49
            LOG_INFO("remove non versioned rowset key in cleanup phase")
7988
49
                    .tag("instance_id", instance_id_)
7989
49
                    .tag("tablet_id", tablet_id)
7990
49
                    .tag("rowset_id", rowset_id)
7991
49
                    .tag("key", hex(task.non_versioned_rowset_key));
7992
49
        }
7993
7994
        // Remove recycle_rowset_key last to ensure retry safety:
7995
        // if cleanup fails, this key remains and triggers next round retry.
7996
49
        if (!task.recycle_rowset_key.empty()) {
7997
0
            txn->remove(task.recycle_rowset_key);
7998
0
            LOG_INFO("remove recycle rowset key in cleanup phase")
7999
0
                    .tag("instance_id", instance_id_)
8000
0
                    .tag("tablet_id", tablet_id)
8001
0
                    .tag("rowset_id", rowset_id)
8002
0
                    .tag("key", hex(task.recycle_rowset_key));
8003
0
        }
8004
8005
49
        err = txn->commit();
8006
49
        if (err != TxnErrorCode::TXN_OK) {
8007
            // Metadata cleanup failed. recycle_rowset_key remains, next round will retry.
8008
0
            LOG_WARNING("failed to commit cleanup metadata txn, will retry next round")
8009
0
                    .tag("instance_id", instance_id_)
8010
0
                    .tag("tablet_id", tablet_id)
8011
0
                    .tag("rowset_id", rowset_id)
8012
0
                    .tag("err", err);
8013
0
            ret = -1;
8014
0
            continue;
8015
0
        }
8016
8017
49
        LOG_INFO("cleanup rowset metadata success")
8018
49
                .tag("instance_id", instance_id_)
8019
49
                .tag("tablet_id", tablet_id)
8020
49
                .tag("rowset_id", rowset_id);
8021
49
    }
8022
10
    return ret;
8023
10
}
8024
8025
} // namespace doris::cloud