Coverage Report

Created: 2026-06-30 22:09

/root/doris/cloud/src/recycler/checker.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "recycler/checker.h"
19
20
#include <aws/s3/S3Client.h>
21
#include <aws/s3/model/ListObjectsV2Request.h>
22
#include <butil/endpoint.h>
23
#include <butil/strings/string_split.h>
24
#include <fmt/core.h>
25
#include <gen_cpp/cloud.pb.h>
26
#include <gen_cpp/olap_file.pb.h>
27
#include <glog/logging.h>
28
29
#include <algorithm>
30
#include <chrono>
31
#include <climits>
32
#include <cstdint>
33
#include <functional>
34
#include <memory>
35
#include <mutex>
36
#include <numeric>
37
#include <sstream>
38
#include <string_view>
39
#include <unordered_map>
40
#include <unordered_set>
41
#include <vector>
42
43
#include "common/bvars.h"
44
#include "common/config.h"
45
#include "common/defer.h"
46
#include "common/encryption_util.h"
47
#include "common/logging.h"
48
#include "common/util.h"
49
#include "cpp/sync_point.h"
50
#include "meta-service/meta_service.h"
51
#include "meta-service/meta_service_schema.h"
52
#include "meta-service/meta_service_tablet_stats.h"
53
#include "meta-store/blob_message.h"
54
#include "meta-store/keys.h"
55
#include "meta-store/txn_kv.h"
56
#include "snapshot/snapshot_manager_factory.h"
57
#ifdef ENABLE_HDFS_STORAGE_VAULT
58
#include "recycler/hdfs_accessor.h"
59
#endif
60
#include "recycler/s3_accessor.h"
61
#include "recycler/storage_vault_accessor.h"
62
#ifdef UNIT_TEST
63
#include "../test/mock_accessor.h"
64
#endif
65
#include "recycler/recycler.h"
66
#include "recycler/util.h"
67
68
namespace doris::cloud {
69
namespace config {
70
extern int32_t brpc_listen_port;
71
extern int32_t scan_instances_interval_seconds;
72
extern int32_t recycle_job_lease_expired_ms;
73
extern int32_t recycle_concurrency;
74
extern std::vector<std::string> recycle_whitelist;
75
extern std::vector<std::string> recycle_blacklist;
76
extern bool enable_inverted_check;
77
} // namespace config
78
79
using namespace std::chrono;
80
81
5
Checker::Checker(std::shared_ptr<TxnKv> txn_kv) : txn_kv_(std::move(txn_kv)) {
82
5
    ip_port_ = std::string(butil::my_ip_cstr()) + ":" + std::to_string(config::brpc_listen_port);
83
5
}
84
85
5
Checker::~Checker() {
86
5
    if (!stopped()) {
87
1
        stop();
88
1
    }
89
5
}
90
91
4
int Checker::start() {
92
4
    DCHECK(txn_kv_);
93
4
    instance_filter_.reset(config::recycle_whitelist, config::recycle_blacklist);
94
95
    // launch instance scanner
96
4
    auto scanner_func = [this]() {
97
4
        std::this_thread::sleep_for(
98
4
                std::chrono::seconds(config::recycler_sleep_before_scheduling_seconds));
99
8
        while (!stopped()) {
100
4
            std::vector<InstanceInfoPB> instances;
101
4
            get_all_instances(txn_kv_.get(), instances);
102
4
            LOG(INFO) << "Checker get instances: " << [&instances] {
103
4
                std::stringstream ss;
104
30
                for (auto& i : instances) ss << ' ' << i.instance_id();
105
4
                return ss.str();
106
4
            }();
107
4
            if (!instances.empty()) {
108
                // enqueue instances
109
3
                std::lock_guard lock(mtx_);
110
30
                for (auto& instance : instances) {
111
30
                    if (instance_filter_.filter_out(instance.instance_id())) continue;
112
30
                    if (instance.status() == InstanceInfoPB::DELETED) continue;
113
30
                    using namespace std::chrono;
114
30
                    auto enqueue_time_s =
115
30
                            duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
116
30
                    auto [_, success] =
117
30
                            pending_instance_map_.insert({instance.instance_id(), enqueue_time_s});
118
                    // skip instance already in pending queue
119
30
                    if (success) {
120
30
                        pending_instance_queue_.push_back(std::move(instance));
121
30
                    }
122
30
                }
123
3
                pending_instance_cond_.notify_all();
124
3
            }
125
4
            {
126
4
                std::unique_lock lock(mtx_);
127
4
                notifier_.wait_for(lock,
128
4
                                   std::chrono::seconds(config::scan_instances_interval_seconds),
129
7
                                   [&]() { return stopped(); });
130
4
            }
131
4
        }
132
4
    };
133
4
    workers_.emplace_back(scanner_func);
134
    // Launch lease thread
135
4
    workers_.emplace_back([this] { lease_check_jobs(); });
136
    // Launch inspect thread
137
4
    workers_.emplace_back([this] { inspect_instance_check_interval(); });
138
139
    // launch check workers
140
8
    auto checker_func = [this]() {
141
38
        while (!stopped()) {
142
            // fetch instance to check
143
36
            InstanceInfoPB instance;
144
36
            long enqueue_time_s = 0;
145
36
            {
146
36
                std::unique_lock lock(mtx_);
147
48
                pending_instance_cond_.wait(lock, [&]() -> bool {
148
48
                    return !pending_instance_queue_.empty() || stopped();
149
48
                });
150
36
                if (stopped()) {
151
6
                    return;
152
6
                }
153
30
                instance = std::move(pending_instance_queue_.front());
154
30
                pending_instance_queue_.pop_front();
155
30
                enqueue_time_s = pending_instance_map_[instance.instance_id()];
156
30
                pending_instance_map_.erase(instance.instance_id());
157
30
            }
158
0
            const auto& instance_id = instance.instance_id();
159
30
            {
160
30
                std::lock_guard lock(mtx_);
161
                // skip instance in recycling
162
30
                if (working_instance_map_.count(instance_id)) {
163
0
                    LOG(INFO) << "checker skip instance already working, instance_id="
164
0
                              << instance_id;
165
0
                    continue;
166
0
                }
167
30
            }
168
30
            auto checker = std::make_shared<InstanceChecker>(txn_kv_, instance.instance_id());
169
30
            if (checker->init(instance) != 0) {
170
0
                LOG(WARNING) << "failed to init instance checker, instance_id="
171
0
                             << instance.instance_id();
172
0
                continue;
173
0
            }
174
30
            std::string check_job_key;
175
30
            job_check_key({instance.instance_id()}, &check_job_key);
176
30
            LOG(INFO) << "checker picked instance, instance_id=" << instance.instance_id()
177
30
                      << " enqueue_time_s=" << enqueue_time_s;
178
30
            int ret = prepare_instance_recycle_job(txn_kv_.get(), check_job_key,
179
30
                                                   instance.instance_id(), ip_port_,
180
30
                                                   config::check_object_interval_seconds * 1000);
181
30
            if (ret != 0) { // Prepare failed
182
20
                LOG(WARNING) << "checker prepare job failed, instance_id=" << instance.instance_id()
183
20
                             << " ret=" << ret;
184
20
                continue;
185
20
            } else {
186
10
                std::lock_guard lock(mtx_);
187
10
                working_instance_map_.emplace(instance_id, checker);
188
10
            }
189
10
            if (stopped()) return;
190
10
            using namespace std::chrono;
191
10
            auto ctime_ms =
192
10
                    duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
193
10
            g_bvar_checker_enqueue_cost_s.put(instance_id, ctime_ms / 1000 - enqueue_time_s);
194
195
10
            bool success {true};
196
10
            auto log_progress = [&](std::string_view stage) {
197
10
                LOG(INFO) << "checker progress, instance_id=" << instance_id << " stage=" << stage;
198
10
            };
199
200
10
            log_progress("do_check");
201
10
            if (int ret = checker->do_check(); ret != 0) {
202
0
                success = false;
203
0
            }
204
205
10
            if (config::enable_inverted_check) {
206
0
                log_progress("do_inverted_check");
207
0
                if (int ret = checker->do_inverted_check(); ret != 0) {
208
0
                    success = false;
209
0
                }
210
0
            }
211
212
10
            if (config::enable_delete_bitmap_inverted_check) {
213
0
                log_progress("do_delete_bitmap_inverted_check");
214
0
                if (int ret = checker->do_delete_bitmap_inverted_check(); ret != 0) {
215
0
                    success = false;
216
0
                }
217
0
            }
218
219
10
            if (config::enable_mow_job_key_check) {
220
0
                log_progress("do_mow_job_key_check");
221
0
                if (int ret = checker->do_mow_job_key_check(); ret != 0) {
222
0
                    success = false;
223
0
                }
224
0
            }
225
226
10
            if (config::enable_tablet_stats_key_check) {
227
0
                log_progress("do_tablet_stats_key_check");
228
0
                if (int ret = checker->do_tablet_stats_key_check(); ret != 0) {
229
0
                    success = false;
230
0
                }
231
0
            }
232
233
10
            if (config::enable_restore_job_check) {
234
0
                log_progress("do_restore_job_check");
235
0
                if (int ret = checker->do_restore_job_check(); ret != 0) {
236
0
                    success = false;
237
0
                }
238
0
            }
239
240
10
            if (config::enable_txn_key_check) {
241
0
                log_progress("do_txn_key_check");
242
0
                if (int ret = checker->do_txn_key_check(); ret != 0) {
243
0
                    success = false;
244
0
                }
245
0
            }
246
247
10
            if (config::enable_meta_rowset_key_check) {
248
0
                log_progress("do_meta_rowset_key_check");
249
0
                if (int ret = checker->do_meta_rowset_key_check(); ret != 0) {
250
0
                    success = false;
251
0
                }
252
0
            }
253
254
10
            if (config::enable_delete_bitmap_storage_optimize_v2_check) {
255
0
                log_progress("do_delete_bitmap_storage_optimize_check_v2");
256
0
                if (int ret = checker->do_delete_bitmap_storage_optimize_check(2 /*version*/);
257
0
                    ret != 0) {
258
0
                    success = false;
259
0
                }
260
0
            }
261
262
10
            if (config::enable_version_key_check) {
263
0
                log_progress("do_version_key_check");
264
0
                if (int ret = checker->do_version_key_check(); ret != 0) {
265
0
                    success = false;
266
0
                }
267
0
            }
268
269
10
            if (config::enable_snapshot_check) {
270
0
                log_progress("do_snapshots_check");
271
0
                if (int ret = checker->do_snapshots_check(); ret != 0) {
272
0
                    success = false;
273
0
                }
274
0
            }
275
276
10
            if (config::enable_mvcc_meta_key_check) {
277
0
                log_progress("do_mvcc_meta_key_check");
278
0
                if (int ret = checker->do_mvcc_meta_key_check(); ret != 0) {
279
0
                    success = false;
280
0
                }
281
0
            }
282
283
10
            if (config::enable_packed_file_check) {
284
0
                log_progress("do_packed_file_check");
285
0
                if (int ret = checker->do_packed_file_check(); ret != 0) {
286
0
                    success = false;
287
0
                }
288
0
            }
289
290
            // If instance checker has been aborted, don't finish this job
291
10
            if (!checker->stopped()) {
292
10
                finish_instance_recycle_job(txn_kv_.get(), check_job_key, instance.instance_id(),
293
10
                                            ip_port_, success, ctime_ms);
294
10
            }
295
10
            LOG(INFO) << "checker finished instance, instance_id=" << instance.instance_id()
296
10
                      << " success=" << success;
297
10
            {
298
10
                std::lock_guard lock(mtx_);
299
10
                working_instance_map_.erase(instance.instance_id());
300
10
            }
301
10
        }
302
8
    };
303
4
    int num_threads = config::recycle_concurrency; // FIXME: use a new config entry?
304
12
    for (int i = 0; i < num_threads; ++i) {
305
8
        workers_.emplace_back(checker_func);
306
8
    }
307
4
    return 0;
308
4
}
309
310
5
void Checker::stop() {
311
5
    stopped_ = true;
312
5
    notifier_.notify_all();
313
5
    pending_instance_cond_.notify_all();
314
5
    {
315
5
        std::lock_guard lock(mtx_);
316
5
        for (auto& [_, checker] : working_instance_map_) {
317
0
            checker->stop();
318
0
        }
319
5
    }
320
20
    for (auto& w : workers_) {
321
20
        if (w.joinable()) w.join();
322
20
    }
323
5
}
324
325
4
void Checker::lease_check_jobs() {
326
55
    while (!stopped()) {
327
51
        std::vector<std::string> instances;
328
51
        instances.reserve(working_instance_map_.size());
329
51
        {
330
51
            std::lock_guard lock(mtx_);
331
51
            for (auto& [id, _] : working_instance_map_) {
332
30
                instances.push_back(id);
333
30
            }
334
51
        }
335
51
        for (auto& i : instances) {
336
30
            std::string check_job_key;
337
30
            job_check_key({i}, &check_job_key);
338
30
            int ret = lease_instance_recycle_job(txn_kv_.get(), check_job_key, i, ip_port_);
339
30
            if (ret == 1) {
340
0
                std::lock_guard lock(mtx_);
341
0
                if (auto it = working_instance_map_.find(i); it != working_instance_map_.end()) {
342
0
                    it->second->stop();
343
0
                }
344
0
            }
345
30
        }
346
51
        {
347
51
            std::unique_lock lock(mtx_);
348
51
            notifier_.wait_for(lock,
349
51
                               std::chrono::milliseconds(config::recycle_job_lease_expired_ms / 3),
350
101
                               [&]() { return stopped(); });
351
51
        }
352
51
    }
353
4
}
354
0
#define LOG_CHECK_INTERVAL_ALARM LOG(WARNING) << "Err for check interval: "
355
34
void Checker::do_inspect(const InstanceInfoPB& instance) {
356
34
    std::string check_job_key = job_check_key({instance.instance_id()});
357
34
    std::unique_ptr<Transaction> txn;
358
34
    std::string val;
359
34
    TxnErrorCode err = txn_kv_->create_txn(&txn);
360
34
    if (err != TxnErrorCode::TXN_OK) {
361
0
        LOG_CHECK_INTERVAL_ALARM << "failed to create txn";
362
0
        return;
363
0
    }
364
34
    err = txn->get(check_job_key, &val);
365
34
    if (err != TxnErrorCode::TXN_OK && err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
366
0
        LOG_CHECK_INTERVAL_ALARM << "failed to get kv, err=" << err
367
0
                                 << " key=" << hex(check_job_key);
368
0
        return;
369
0
    }
370
34
    auto checker = InstanceChecker(txn_kv_, instance.instance_id());
371
34
    if (checker.init(instance) != 0) {
372
0
        LOG_CHECK_INTERVAL_ALARM << "failed to init instance checker, instance_id="
373
0
                                 << instance.instance_id();
374
0
        return;
375
0
    }
376
377
34
    int64_t bucket_lifecycle_days = 0;
378
34
    if (checker.get_bucket_lifecycle(&bucket_lifecycle_days) != 0) {
379
0
        LOG_CHECK_INTERVAL_ALARM << "failed to get bucket lifecycle, instance_id="
380
0
                                 << instance.instance_id();
381
0
        return;
382
0
    }
383
34
    DCHECK(bucket_lifecycle_days > 0);
384
385
34
    if (bucket_lifecycle_days == INT64_MAX) {
386
        // No s3 bucket (may all accessors are HdfsAccessor), skip inspect
387
34
        return;
388
34
    }
389
390
0
    int64_t last_ctime_ms = -1;
391
0
    auto job_status = JobRecyclePB::IDLE;
392
0
    auto has_last_ctime = [&]() {
393
0
        JobRecyclePB job_info;
394
0
        if (!job_info.ParseFromString(val)) {
395
0
            LOG_CHECK_INTERVAL_ALARM << "failed to parse JobRecyclePB, key=" << hex(check_job_key);
396
0
        }
397
0
        DCHECK(job_info.instance_id() == instance.instance_id());
398
0
        if (!job_info.has_last_ctime_ms()) return false;
399
0
        last_ctime_ms = job_info.last_ctime_ms();
400
0
        job_status = job_info.status();
401
0
        g_bvar_checker_last_success_time_ms.put(instance.instance_id(),
402
0
                                                job_info.last_success_time_ms());
403
0
        return true;
404
0
    };
405
0
    using namespace std::chrono;
406
0
    auto now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
407
0
    if (err == TxnErrorCode::TXN_KEY_NOT_FOUND || !has_last_ctime()) {
408
        // Use instance's ctime for instances that do not have job's last ctime
409
0
        last_ctime_ms = instance.ctime();
410
0
    }
411
0
    DCHECK(now - last_ctime_ms >= 0);
412
0
    int64_t expiration_ms =
413
0
            bucket_lifecycle_days > config::reserved_buffer_days
414
0
                    ? (bucket_lifecycle_days - config::reserved_buffer_days) * 86400000
415
0
                    : bucket_lifecycle_days * 86400000;
416
0
    TEST_SYNC_POINT_CALLBACK("Checker:do_inspect", &last_ctime_ms);
417
0
    if (now - last_ctime_ms >= expiration_ms) {
418
0
        LOG_CHECK_INTERVAL_ALARM << "check risks, instance_id: " << instance.instance_id()
419
0
                                 << " last_ctime_ms: " << last_ctime_ms
420
0
                                 << " job_status: " << job_status
421
0
                                 << " bucket_lifecycle_days: " << bucket_lifecycle_days
422
0
                                 << " reserved_buffer_days: " << config::reserved_buffer_days
423
0
                                 << " expiration_ms: " << expiration_ms;
424
0
    }
425
0
}
426
#undef LOG_CHECK_INTERVAL_ALARM
427
4
void Checker::inspect_instance_check_interval() {
428
7
    while (!stopped()) {
429
3
        LOG(INFO) << "start to inspect instance check interval";
430
3
        std::vector<InstanceInfoPB> instances;
431
3
        get_all_instances(txn_kv_.get(), instances);
432
30
        for (const auto& instance : instances) {
433
30
            if (instance_filter_.filter_out(instance.instance_id())) continue;
434
30
            if (stopped()) return;
435
30
            if (instance.status() == InstanceInfoPB::DELETED) continue;
436
30
            do_inspect(instance);
437
30
        }
438
3
        {
439
3
            std::unique_lock lock(mtx_);
440
3
            notifier_.wait_for(lock, std::chrono::seconds(config::scan_instances_interval_seconds),
441
6
                               [&]() { return stopped(); });
442
3
        }
443
3
    }
444
4
}
445
446
// return 0 for success get a key, 1 for key not found, negative for error
447
26
int key_exist(TxnKv* txn_kv, std::string_view key) {
448
26
    std::unique_ptr<Transaction> txn;
449
26
    TxnErrorCode err = txn_kv->create_txn(&txn);
450
26
    if (err != TxnErrorCode::TXN_OK) {
451
0
        LOG(WARNING) << "failed to init txn, err=" << err;
452
0
        return -1;
453
0
    }
454
26
    std::string val;
455
26
    switch (txn->get(key, &val)) {
456
23
    case TxnErrorCode::TXN_OK:
457
23
        return 0;
458
3
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
459
3
        return 1;
460
0
    default:
461
0
        return -1;
462
26
    }
463
26
}
464
465
InstanceChecker::InstanceChecker(std::shared_ptr<TxnKv> txn_kv, const std::string& instance_id)
466
100
        : txn_kv_(txn_kv), instance_id_(instance_id) {
467
100
    snapshot_manager_ = create_snapshot_manager(txn_kv);
468
100
    resource_mgr_ = std::make_shared<ResourceManager>(std::move(txn_kv));
469
100
    resource_mgr_->init();
470
100
}
471
472
100
int InstanceChecker::init(const InstanceInfoPB& instance) {
473
100
    int ret = init_obj_store_accessors(instance);
474
100
    if (ret != 0) {
475
0
        return ret;
476
0
    }
477
478
100
    return init_storage_vault_accessors(instance);
479
100
}
480
481
100
int InstanceChecker::init_obj_store_accessors(const InstanceInfoPB& instance) {
482
100
    for (const auto& obj_info : instance.obj_info()) {
483
100
#ifdef UNIT_TEST
484
100
        auto accessor = std::make_shared<MockAccessor>();
485
#else
486
        auto s3_conf = S3Conf::from_obj_store_info(obj_info);
487
        if (!s3_conf) {
488
            LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
489
            return -1;
490
        }
491
492
        std::shared_ptr<S3Accessor> accessor;
493
        int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
494
        if (ret != 0) {
495
            LOG(WARNING) << "failed to init object accessor. instance_id=" << instance_id_
496
                         << " resource_id=" << obj_info.id();
497
            return ret;
498
        }
499
#endif
500
501
100
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
502
100
    }
503
504
100
    return 0;
505
100
}
506
507
100
int InstanceChecker::init_storage_vault_accessors(const InstanceInfoPB& instance) {
508
100
    if (instance.resource_ids().empty()) {
509
100
        return 0;
510
100
    }
511
512
0
    FullRangeGetOptions opts(txn_kv_);
513
0
    opts.prefetch = true;
514
0
    auto it = txn_kv_->full_range_get(storage_vault_key({instance_id_, ""}),
515
0
                                      storage_vault_key({instance_id_, "\xff"}), std::move(opts));
516
517
0
    for (auto kv = it->next(); kv.has_value(); kv = it->next()) {
518
0
        auto [k, v] = *kv;
519
0
        StorageVaultPB vault;
520
0
        if (!vault.ParseFromArray(v.data(), v.size())) {
521
0
            LOG(WARNING) << "malformed storage vault, unable to deserialize key=" << hex(k);
522
0
            return -1;
523
0
        }
524
0
        TEST_SYNC_POINT_CALLBACK("InstanceRecycler::init_storage_vault_accessors.mock_vault",
525
0
                                 &accessor_map_, &vault);
526
0
        if (vault.has_hdfs_info()) {
527
0
#ifdef ENABLE_HDFS_STORAGE_VAULT
528
0
            auto accessor = std::make_shared<HdfsAccessor>(vault.hdfs_info());
529
0
            int ret = accessor->init();
530
0
            if (ret != 0) {
531
0
                LOG(WARNING) << "failed to init hdfs accessor. instance_id=" << instance_id_
532
0
                             << " resource_id=" << vault.id() << " name=" << vault.name();
533
0
                return ret;
534
0
            }
535
536
0
            accessor_map_.emplace(vault.id(), std::move(accessor));
537
#else
538
            LOG(ERROR) << "HDFS is disabled (via the ENABLE_HDFS_STORAGE_VAULT build option), "
539
                       << "but HDFS storage vaults were detected";
540
#endif
541
0
        } else if (vault.has_obj_info()) {
542
0
#ifdef UNIT_TEST
543
0
            auto accessor = std::make_shared<MockAccessor>();
544
#else
545
            auto s3_conf = S3Conf::from_obj_store_info(vault.obj_info());
546
            if (!s3_conf) {
547
                LOG(WARNING) << "failed to init object accessor, instance_id=" << instance_id_;
548
                return -1;
549
            }
550
551
            std::shared_ptr<S3Accessor> accessor;
552
            int ret = S3Accessor::create(std::move(*s3_conf), &accessor);
553
            if (ret != 0) {
554
                LOG(WARNING) << "failed to init s3 accessor. instance_id=" << instance_id_
555
                             << " resource_id=" << vault.id() << " name=" << vault.name();
556
                return ret;
557
            }
558
#endif
559
560
0
            accessor_map_.emplace(vault.id(), std::move(accessor));
561
0
        }
562
0
    }
563
564
0
    if (!it->is_valid()) {
565
0
        LOG_WARNING("failed to get storage vault kv");
566
0
        return -1;
567
0
    }
568
0
    return 0;
569
0
}
570
571
16
int InstanceChecker::do_check() {
572
16
    TEST_SYNC_POINT("InstanceChecker.do_check");
573
16
    LOG(INFO) << "begin to check instance objects instance_id=" << instance_id_;
574
16
    int check_ret = 0;
575
16
    long num_scanned = 0;
576
16
    long num_scanned_with_segment = 0;
577
16
    long num_rowset_loss = 0;
578
16
    long instance_volume = 0;
579
16
    using namespace std::chrono;
580
16
    auto start_time = steady_clock::now();
581
16
    DORIS_CLOUD_DEFER {
582
16
        auto cost = duration<float>(steady_clock::now() - start_time).count();
583
16
        LOG(INFO) << "check instance objects finished, cost=" << cost
584
16
                  << "s. instance_id=" << instance_id_ << " num_scanned=" << num_scanned
585
16
                  << " num_scanned_with_segment=" << num_scanned_with_segment
586
16
                  << " num_rowset_loss=" << num_rowset_loss
587
16
                  << " instance_volume=" << instance_volume;
588
16
        g_bvar_checker_num_scanned.put(instance_id_, num_scanned);
589
16
        g_bvar_checker_num_scanned_with_segment.put(instance_id_, num_scanned_with_segment);
590
16
        g_bvar_checker_num_check_failed.put(instance_id_, num_rowset_loss);
591
16
        g_bvar_checker_check_cost_s.put(instance_id_, static_cast<long>(cost));
592
        // FIXME(plat1ko): What if some list operation failed?
593
16
        g_bvar_checker_instance_volume.put(instance_id_, instance_volume);
594
16
    };
595
596
16
    struct TabletFiles {
597
16
        int64_t tablet_id {0};
598
16
        std::unordered_set<std::string> files;
599
16
    };
600
16
    TabletFiles tablet_files_cache;
601
602
4.05k
    auto check_rowset_objects = [&, this](doris::RowsetMetaCloudPB& rs_meta, std::string_view key) {
603
4.05k
        if (rs_meta.num_segments() == 0) {
604
0
            return;
605
0
        }
606
607
4.05k
        bool data_loss = false;
608
4.05k
        bool segment_file_loss = false;
609
4.05k
        bool index_file_loss = false;
610
611
4.05k
        DORIS_CLOUD_DEFER {
612
4.05k
            if (data_loss) {
613
35
                LOG(INFO) << "segment file is" << (segment_file_loss ? "" : " not") << " loss, "
614
35
                          << "index file is" << (index_file_loss ? "" : " not") << " loss, "
615
35
                          << "rowset.tablet_id = " << rs_meta.tablet_id();
616
35
                num_rowset_loss++;
617
35
            }
618
4.05k
        };
619
620
4.05k
        ++num_scanned_with_segment;
621
4.05k
        if (tablet_files_cache.tablet_id != rs_meta.tablet_id()) {
622
454
            long tablet_volume = 0;
623
            // Clear cache
624
454
            tablet_files_cache.tablet_id = 0;
625
454
            tablet_files_cache.files.clear();
626
            // Get all file paths under this tablet directory
627
454
            auto find_it = accessor_map_.find(rs_meta.resource_id());
628
454
            if (find_it == accessor_map_.end()) {
629
0
                LOG_WARNING("resource id not found in accessor map")
630
0
                        .tag("resource_id", rs_meta.resource_id())
631
0
                        .tag("tablet_id", rs_meta.tablet_id())
632
0
                        .tag("rowset_id", rs_meta.rowset_id_v2());
633
0
                check_ret = -1;
634
0
                return;
635
0
            }
636
637
454
            std::unique_ptr<ListIterator> list_iter;
638
454
            int ret = find_it->second->list_directory(tablet_path_prefix(rs_meta.tablet_id()),
639
454
                                                      &list_iter);
640
454
            if (ret != 0) { // No need to log, because S3Accessor has logged this error
641
0
                check_ret = -1;
642
0
                return;
643
0
            }
644
645
18.5k
            for (auto file = list_iter->next(); file.has_value(); file = list_iter->next()) {
646
18.0k
                tablet_files_cache.files.insert(std::move(file->path));
647
18.0k
                tablet_volume += file->size;
648
18.0k
            }
649
454
            tablet_files_cache.tablet_id = rs_meta.tablet_id();
650
454
            instance_volume += tablet_volume;
651
454
        }
652
653
16.1k
        for (int i = 0; i < rs_meta.num_segments(); ++i) {
654
12.0k
            auto path = segment_path(rs_meta.tablet_id(), rs_meta.rowset_id_v2(), i);
655
656
            // Skip check if segment is already packed into a larger file
657
12.0k
            const auto& index_map = rs_meta.packed_slice_locations();
658
12.0k
            if (index_map.find(path) != index_map.end()) {
659
0
                continue;
660
0
            }
661
662
12.0k
            if (tablet_files_cache.files.contains(path)) {
663
12.0k
                continue;
664
12.0k
            }
665
666
14
            if (1 == key_exist(txn_kv_.get(), key)) {
667
                // Rowset has been deleted instead of data loss
668
0
                break;
669
0
            }
670
14
            data_loss = true;
671
14
            segment_file_loss = true;
672
14
            TEST_SYNC_POINT_CALLBACK("InstanceChecker.do_check1", &path);
673
14
            LOG(WARNING) << "object not exist, path=" << path
674
14
                         << ", rs_meta=" << rs_meta.ShortDebugString() << " key=" << hex(key);
675
14
        }
676
677
4.05k
        std::unique_ptr<Transaction> txn;
678
4.05k
        TxnErrorCode err = txn_kv_->create_txn(&txn);
679
4.05k
        if (err != TxnErrorCode::TXN_OK) {
680
0
            LOG(WARNING) << "failed to init txn, err=" << err;
681
0
            check_ret = -1;
682
0
            return;
683
0
        }
684
685
4.05k
        TabletIndexPB tablet_index;
686
4.05k
        if (get_tablet_idx(txn_kv_.get(), instance_id_, rs_meta.tablet_id(), tablet_index) == -1) {
687
0
            LOG(WARNING) << "failed to get tablet index, tablet_id= " << rs_meta.tablet_id();
688
0
            check_ret = -1;
689
0
            return;
690
0
        }
691
692
4.05k
        auto tablet_schema_key =
693
4.05k
                meta_schema_key({instance_id_, tablet_index.index_id(), rs_meta.schema_version()});
694
4.05k
        ValueBuf tablet_schema_val;
695
4.05k
        err = cloud::blob_get(txn.get(), tablet_schema_key, &tablet_schema_val);
696
697
4.05k
        if (err != TxnErrorCode::TXN_OK) {
698
2.00k
            check_ret = -1;
699
2.00k
            LOG(WARNING) << "failed to get schema, err=" << err;
700
2.00k
            return;
701
2.00k
        }
702
703
2.05k
        auto* schema = rs_meta.mutable_tablet_schema();
704
2.05k
        if (!parse_schema_value(tablet_schema_val, schema)) {
705
0
            LOG(WARNING) << "malformed schema value, key=" << hex(tablet_schema_key);
706
0
            return;
707
0
        }
708
709
2.05k
        std::vector<std::pair<int64_t, std::string>> index_ids;
710
2.05k
        for (const auto& i : rs_meta.tablet_schema().index()) {
711
2.05k
            if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
712
2.05k
                index_ids.emplace_back(i.index_id(), i.index_suffix_name());
713
2.05k
            }
714
2.05k
        }
715
2.05k
        if (!index_ids.empty()) {
716
2.05k
            const auto& index_map = rs_meta.packed_slice_locations();
717
8.10k
            for (int i = 0; i < rs_meta.num_segments(); ++i) {
718
6.05k
                std::vector<std::string> index_path_v;
719
6.05k
                if (rs_meta.tablet_schema().inverted_index_storage_format() ==
720
6.05k
                    InvertedIndexStorageFormatPB::V1) {
721
6.01k
                    for (const auto& index_id : index_ids) {
722
6.01k
                        LOG(INFO) << "check inverted index, tablet_id=" << rs_meta.tablet_id()
723
6.01k
                                  << " rowset_id=" << rs_meta.rowset_id_v2() << " segment_id=" << i
724
6.01k
                                  << " index_id=" << index_id.first
725
6.01k
                                  << " index_suffix_name=" << index_id.second;
726
6.01k
                        index_path_v.emplace_back(
727
6.01k
                                inverted_index_path_v1(rs_meta.tablet_id(), rs_meta.rowset_id_v2(),
728
6.01k
                                                       i, index_id.first, index_id.second));
729
6.01k
                    }
730
6.01k
                } else {
731
40
                    index_path_v.emplace_back(
732
40
                            inverted_index_path_v2(rs_meta.tablet_id(), rs_meta.rowset_id_v2(), i));
733
40
                }
734
735
6.05k
                if (std::ranges::all_of(index_path_v, [&](const auto& idx_file_path) {
736
                        // Skip check if inverted index file is already packed into a larger file
737
6.05k
                        if (index_map.find(idx_file_path) != index_map.end()) {
738
0
                            return true;
739
0
                        }
740
6.05k
                        if (!tablet_files_cache.files.contains(idx_file_path)) {
741
23
                            LOG(INFO) << "loss index file: " << idx_file_path;
742
23
                            return false;
743
23
                        }
744
6.03k
                        return true;
745
6.05k
                    })) {
746
6.03k
                    continue;
747
6.03k
                }
748
23
                index_file_loss = true;
749
23
                data_loss = true;
750
23
            }
751
2.05k
        }
752
2.05k
    };
753
754
    // scan visible rowsets
755
16
    auto start_key = meta_rowset_key({instance_id_, 0, 0});
756
16
    auto end_key = meta_rowset_key({instance_id_, INT64_MAX, 0});
757
758
16
    std::unique_ptr<RangeGetIterator> it;
759
32
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
760
16
        std::unique_ptr<Transaction> txn;
761
16
        TxnErrorCode err = txn_kv_->create_txn(&txn);
762
16
        if (err != TxnErrorCode::TXN_OK) {
763
0
            LOG(WARNING) << "failed to init txn, err=" << err;
764
0
            return -1;
765
0
        }
766
767
16
        err = txn->get(start_key, end_key, &it);
768
16
        if (err != TxnErrorCode::TXN_OK) {
769
0
            LOG(WARNING) << "internal error, failed to get rowset meta, err=" << err;
770
0
            return -1;
771
0
        }
772
16
        num_scanned += it->size();
773
774
4.07k
        while (it->has_next() && !stopped()) {
775
4.05k
            auto [k, v] = it->next();
776
4.05k
            if (!it->has_next()) {
777
6
                start_key = k;
778
6
            }
779
780
4.05k
            doris::RowsetMetaCloudPB rs_meta;
781
4.05k
            if (!rs_meta.ParseFromArray(v.data(), v.size())) {
782
0
                ++num_rowset_loss;
783
0
                LOG(WARNING) << "malformed rowset meta. key=" << hex(k) << " val=" << hex(v);
784
0
                continue;
785
0
            }
786
4.05k
            check_rowset_objects(rs_meta, k);
787
4.05k
        }
788
16
        start_key.push_back('\x00'); // Update to next smallest key for iteration
789
16
    }
790
791
16
    return num_rowset_loss > 0 ? 1 : check_ret;
792
16
}
793
794
34
int InstanceChecker::get_bucket_lifecycle(int64_t* lifecycle_days) {
795
    // If there are multiple buckets, return the minimum lifecycle.
796
34
    int64_t min_lifecycle_days = INT64_MAX;
797
34
    int64_t tmp_liefcycle_days = 0;
798
34
    for (const auto& [id, accessor] : accessor_map_) {
799
34
        if (accessor->type() != AccessorType::S3) {
800
34
            continue;
801
34
        }
802
803
0
        auto* s3_accessor = static_cast<S3Accessor*>(accessor.get());
804
805
0
        if (s3_accessor->check_versioning() != 0) {
806
0
            return -1;
807
0
        }
808
809
0
        if (s3_accessor->get_life_cycle(&tmp_liefcycle_days) != 0) {
810
0
            return -1;
811
0
        }
812
813
0
        if (tmp_liefcycle_days < min_lifecycle_days) {
814
0
            min_lifecycle_days = tmp_liefcycle_days;
815
0
        }
816
0
    }
817
34
    *lifecycle_days = min_lifecycle_days;
818
34
    return 0;
819
34
}
820
821
5
int InstanceChecker::do_inverted_check() {
822
5
    if (accessor_map_.size() > 1) {
823
0
        LOG(INFO) << "currently not support inverted check for multi accessor. instance_id="
824
0
                  << instance_id_;
825
0
        return 0;
826
0
    }
827
828
5
    LOG(INFO) << "begin to inverted check objects instance_id=" << instance_id_;
829
5
    int check_ret = 0;
830
5
    long num_scanned = 0;
831
5
    long num_file_leak = 0;
832
5
    using namespace std::chrono;
833
5
    auto start_time = steady_clock::now();
834
5
    DORIS_CLOUD_DEFER {
835
5
        g_bvar_inverted_checker_num_scanned.put(instance_id_, num_scanned);
836
5
        g_bvar_inverted_checker_num_check_failed.put(instance_id_, num_file_leak);
837
5
        auto cost = duration<float>(steady_clock::now() - start_time).count();
838
5
        LOG(INFO) << "inverted check instance objects finished, cost=" << cost
839
5
                  << "s. instance_id=" << instance_id_ << " num_scanned=" << num_scanned
840
5
                  << " num_file_leak=" << num_file_leak;
841
5
    };
842
843
5
    struct TabletRowsets {
844
5
        int64_t tablet_id {0};
845
5
        std::unordered_set<std::string> rowset_ids;
846
5
    };
847
5
    TabletRowsets tablet_rowsets_cache;
848
849
5
    RowsetIndexesFormatV1 rowset_index_cache_v1;
850
5
    RowsetIndexesFormatV2 rowset_index_cache_v2;
851
852
    // Return 0 if check success, return 1 if file is garbage data, negative if error occurred
853
108
    auto check_segment_file = [&](const std::string& obj_key) {
854
108
        std::vector<std::string> str;
855
108
        butil::SplitString(obj_key, '/', &str);
856
        // data/{tablet_id}/{rowset_id}_{seg_num}.dat
857
108
        if (str.size() < 3) {
858
            // clang-format off
859
0
            LOG(WARNING) << "split obj_key error, str.size() should be less than 3,"
860
0
                         << " value = " << str.size();
861
            // clang-format on
862
0
            return -1;
863
0
        }
864
865
108
        int64_t tablet_id = atol(str[1].c_str());
866
108
        if (tablet_id <= 0) {
867
0
            LOG(WARNING) << "failed to parse tablet_id, key=" << obj_key;
868
0
            return -1;
869
0
        }
870
871
108
        if (!str[2].ends_with(".dat")) {
872
            // skip check not segment file
873
54
            return 0;
874
54
        }
875
876
54
        std::string rowset_id;
877
54
        if (auto pos = str.back().find('_'); pos != std::string::npos) {
878
54
            rowset_id = str.back().substr(0, pos);
879
54
        } else {
880
0
            LOG(WARNING) << "failed to parse rowset_id, key=" << obj_key;
881
0
            return -1;
882
0
        }
883
884
54
        if (tablet_rowsets_cache.tablet_id == tablet_id) {
885
7
            if (tablet_rowsets_cache.rowset_ids.contains(rowset_id)) {
886
2
                return 0;
887
5
            } else {
888
5
                LOG(WARNING) << "rowset not exists, key=" << obj_key;
889
5
                return -1;
890
5
            }
891
7
        }
892
        // Get all rowset id of this tablet
893
47
        tablet_rowsets_cache.tablet_id = tablet_id;
894
47
        tablet_rowsets_cache.rowset_ids.clear();
895
47
        std::unique_ptr<Transaction> txn;
896
47
        TxnErrorCode err = txn_kv_->create_txn(&txn);
897
47
        if (err != TxnErrorCode::TXN_OK) {
898
0
            LOG(WARNING) << "failed to create txn";
899
0
            return -1;
900
0
        }
901
47
        std::unique_ptr<RangeGetIterator> it;
902
47
        auto begin = meta_rowset_key({instance_id_, tablet_id, 0});
903
47
        auto end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
904
84
        while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
905
47
            TxnErrorCode err = txn->get(begin, end, &it);
906
47
            if (err != TxnErrorCode::TXN_OK) {
907
0
                LOG(WARNING) << "failed to get rowset kv, err=" << err;
908
0
                return -1;
909
0
            }
910
47
            if (!it->has_next()) {
911
10
                break;
912
10
            }
913
37
            while (it->has_next()) {
914
                // recycle corresponding resources
915
37
                auto [k, v] = it->next();
916
37
                doris::RowsetMetaCloudPB rowset;
917
37
                if (!rowset.ParseFromArray(v.data(), v.size())) {
918
0
                    LOG(WARNING) << "malformed rowset meta value, key=" << hex(k);
919
0
                    return -1;
920
0
                }
921
37
                tablet_rowsets_cache.rowset_ids.insert(rowset.rowset_id_v2());
922
37
                if (!it->has_next()) {
923
37
                    begin = k;
924
37
                    begin.push_back('\x00'); // Update to next smallest key for iteration
925
37
                    break;
926
37
                }
927
37
            }
928
37
        }
929
930
47
        if (!tablet_rowsets_cache.rowset_ids.contains(rowset_id)) {
931
            // Garbage data leak
932
12
            LOG(WARNING) << "rowset should be recycled, key=" << obj_key;
933
12
            return 1;
934
12
        }
935
936
35
        return 0;
937
47
    };
938
939
108
    auto check_inverted_index_file = [&](const std::string& obj_key) {
940
108
        std::vector<std::string> str;
941
108
        butil::SplitString(obj_key, '/', &str);
942
        // format v1: data/{tablet_id}/{rowset_id}_{seg_num}_{idx_id}{idx_suffix}.idx
943
        // format v2: data/{tablet_id}/{rowset_id}_{seg_num}.idx
944
108
        if (str.size() < 3) {
945
            // clang-format off
946
0
            LOG(WARNING) << "split obj_key error, str.size() should be less than 3,"
947
0
                         << " value = " << str.size();
948
            // clang-format on
949
0
            return -1;
950
0
        }
951
952
108
        int64_t tablet_id = atol(str[1].c_str());
953
108
        if (tablet_id <= 0) {
954
0
            LOG(WARNING) << "failed to parse tablet_id, key=" << obj_key;
955
0
            return -1;
956
0
        }
957
958
        // v1: {rowset_id}_{seg_num}_{idx_id}{idx_suffix}.idx
959
        // v2: {rowset_id}_{seg_num}.idx
960
108
        std::string rowset_info = str.back();
961
962
108
        if (!rowset_info.ends_with(".idx")) {
963
54
            return 0; // Not an index file
964
54
        }
965
966
54
        InvertedIndexStorageFormatPB inverted_index_storage_format =
967
54
                std::count(rowset_info.begin(), rowset_info.end(), '_') > 1
968
54
                        ? InvertedIndexStorageFormatPB::V1
969
54
                        : InvertedIndexStorageFormatPB::V2;
970
971
54
        size_t pos = rowset_info.find_last_of('_');
972
54
        if (pos == std::string::npos || pos + 1 >= str.back().size() - 4) {
973
0
            LOG(WARNING) << "Invalid index_id format, key=" << obj_key;
974
0
            return -1;
975
0
        }
976
54
        if (inverted_index_storage_format == InvertedIndexStorageFormatPB::V1) {
977
14
            return check_inverted_index_file_storage_format_v1(tablet_id, obj_key, rowset_info,
978
14
                                                               rowset_index_cache_v1);
979
40
        } else {
980
40
            return check_inverted_index_file_storage_format_v2(tablet_id, obj_key, rowset_info,
981
40
                                                               rowset_index_cache_v2);
982
40
        }
983
54
    };
984
    // so we choose to skip here.
985
5
    TEST_SYNC_POINT_RETURN_WITH_VALUE("InstanceChecker::do_inverted_check", (int)0);
986
987
3
    for (auto& [_, accessor] : accessor_map_) {
988
3
        std::unique_ptr<ListIterator> list_iter;
989
3
        int ret = accessor->list_directory("data", &list_iter);
990
3
        if (ret != 0) {
991
0
            return -1;
992
0
        }
993
994
111
        for (auto file = list_iter->next(); file.has_value(); file = list_iter->next()) {
995
108
            const auto& path = file->path;
996
108
            if (path == "data/packed_file" || path.starts_with("data/packed_file/")) {
997
0
                continue; // packed_file has dedicated check logic
998
0
            }
999
108
            ++num_scanned;
1000
108
            int ret = check_segment_file(path);
1001
108
            if (ret != 0) {
1002
17
                LOG(WARNING) << "failed to check segment file, uri=" << accessor->uri()
1003
17
                             << " path=" << path;
1004
17
                if (ret == 1) {
1005
12
                    ++num_file_leak;
1006
12
                } else {
1007
5
                    check_ret = -1;
1008
5
                }
1009
17
            }
1010
108
            ret = check_inverted_index_file(path);
1011
108
            if (ret != 0) {
1012
13
                LOG(WARNING) << "failed to check index file, uri=" << accessor->uri()
1013
13
                             << " path=" << path;
1014
13
                if (ret == 1) {
1015
13
                    ++num_file_leak;
1016
13
                } else {
1017
0
                    check_ret = -1;
1018
0
                }
1019
13
            }
1020
108
        }
1021
1022
3
        if (!list_iter->is_valid()) {
1023
0
            LOG(WARNING) << "failed to list data directory. uri=" << accessor->uri();
1024
0
            return -1;
1025
0
        }
1026
3
    }
1027
3
    return num_file_leak > 0 ? 1 : check_ret;
1028
3
}
1029
1030
3
int InstanceChecker::traverse_mow_tablet(const std::function<int(int64_t, bool)>& check_func) {
1031
3
    std::unique_ptr<RangeGetIterator> it;
1032
3
    auto begin = meta_rowset_key({instance_id_, 0, 0});
1033
3
    auto end = meta_rowset_key({instance_id_, std::numeric_limits<int64_t>::max(), 0});
1034
43
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
1035
43
        std::unique_ptr<Transaction> txn;
1036
43
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1037
43
        if (err != TxnErrorCode::TXN_OK) {
1038
0
            LOG(WARNING) << "failed to create txn";
1039
0
            return -1;
1040
0
        }
1041
43
        err = txn->get(begin, end, &it, false, 1);
1042
43
        if (err != TxnErrorCode::TXN_OK) {
1043
0
            LOG(WARNING) << "failed to get rowset kv, err=" << err;
1044
0
            return -1;
1045
0
        }
1046
43
        if (!it->has_next()) {
1047
3
            break;
1048
3
        }
1049
80
        while (it->has_next() && !stopped()) {
1050
40
            auto [k, v] = it->next();
1051
40
            std::string_view k1 = k;
1052
40
            k1.remove_prefix(1);
1053
40
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1054
40
            decode_key(&k1, &out);
1055
            // 0x01 "meta" ${instance_id} "rowset" ${tablet_id} ${version} -> RowsetMetaCloudPB
1056
40
            auto tablet_id = std::get<int64_t>(std::get<0>(out[3]));
1057
1058
40
            if (!it->has_next()) {
1059
                // Update to next smallest key for iteration
1060
                // scan for next tablet in this instance
1061
40
                begin = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1062
40
            }
1063
1064
40
            TabletMetaCloudPB tablet_meta;
1065
40
            int ret = get_tablet_meta(txn_kv_.get(), instance_id_, tablet_id, tablet_meta);
1066
40
            if (ret < 0) {
1067
0
                LOG(WARNING) << fmt::format(
1068
0
                        "failed to get_tablet_meta in do_delete_bitmap_integrity_check(), "
1069
0
                        "instance_id={}, tablet_id={}",
1070
0
                        instance_id_, tablet_id);
1071
0
                return ret;
1072
0
            }
1073
1074
40
            if (tablet_meta.enable_unique_key_merge_on_write()) {
1075
                // only check merge-on-write table
1076
30
                bool has_sequence_col = tablet_meta.schema().has_sequence_col_idx() &&
1077
30
                                        tablet_meta.schema().sequence_col_idx() != -1;
1078
30
                int ret = check_func(tablet_id, has_sequence_col);
1079
30
                if (ret < 0) {
1080
                    // return immediately when encounter unexpected error,
1081
                    // otherwise, we continue to check the next tablet
1082
0
                    return ret;
1083
0
                }
1084
30
            }
1085
40
        }
1086
40
    }
1087
3
    return 0;
1088
3
}
1089
1090
int InstanceChecker::traverse_rowset_delete_bitmaps(
1091
        int64_t tablet_id, std::string rowset_id,
1092
0
        const std::function<int(int64_t, std::string_view, int64_t, int64_t)>& callback) {
1093
0
    std::unique_ptr<RangeGetIterator> it;
1094
0
    auto begin = meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id, 0, 0});
1095
0
    auto end = meta_delete_bitmap_key({instance_id_, tablet_id, rowset_id,
1096
0
                                       std::numeric_limits<int64_t>::max(),
1097
0
                                       std::numeric_limits<int64_t>::max()});
1098
0
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
1099
0
        std::unique_ptr<Transaction> txn;
1100
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1101
0
        if (err != TxnErrorCode::TXN_OK) {
1102
0
            LOG(WARNING) << "failed to create txn";
1103
0
            return -1;
1104
0
        }
1105
0
        err = txn->get(begin, end, &it);
1106
0
        if (err != TxnErrorCode::TXN_OK) {
1107
0
            LOG(WARNING) << "failed to get rowset kv, err=" << err;
1108
0
            return -1;
1109
0
        }
1110
0
        if (!it->has_next()) {
1111
0
            break;
1112
0
        }
1113
0
        while (it->has_next() && !stopped()) {
1114
0
            auto [k, v] = it->next();
1115
0
            std::string_view k1 = k;
1116
0
            k1.remove_prefix(1);
1117
0
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1118
0
            decode_key(&k1, &out);
1119
            // 0x01 "meta" ${instance_id} "delete_bitmap" ${tablet_id} ${rowset_id} ${version} ${segment_id} -> roaringbitmap
1120
0
            auto version = std::get<std::int64_t>(std::get<0>(out[5]));
1121
0
            auto segment_id = std::get<std::int64_t>(std::get<0>(out[6]));
1122
1123
0
            int ret = callback(tablet_id, rowset_id, version, segment_id);
1124
0
            if (ret != 0) {
1125
0
                return ret;
1126
0
            }
1127
1128
0
            if (!it->has_next()) {
1129
0
                begin = k;
1130
0
                begin.push_back('\x00'); // Update to next smallest key for iteration
1131
0
                break;
1132
0
            }
1133
0
        }
1134
0
    }
1135
1136
0
    return 0;
1137
0
}
1138
1139
int InstanceChecker::collect_tablet_rowsets(
1140
53
        int64_t tablet_id, const std::function<void(const doris::RowsetMetaCloudPB&)>& collect_cb) {
1141
53
    std::unique_ptr<Transaction> txn;
1142
53
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1143
53
    if (err != TxnErrorCode::TXN_OK) {
1144
0
        LOG(WARNING) << "failed to create txn";
1145
0
        return -1;
1146
0
    }
1147
53
    std::unique_ptr<RangeGetIterator> it;
1148
53
    auto begin = meta_rowset_key({instance_id_, tablet_id, 0});
1149
53
    auto end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1150
1151
53
    int64_t rowsets_num {0};
1152
103
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
1153
53
        TxnErrorCode err = txn->get(begin, end, &it);
1154
53
        if (err != TxnErrorCode::TXN_OK) {
1155
0
            LOG(WARNING) << "failed to get rowset kv, err=" << err;
1156
0
            return -1;
1157
0
        }
1158
53
        if (!it->has_next()) {
1159
3
            break;
1160
3
        }
1161
394
        while (it->has_next() && !stopped()) {
1162
394
            auto [k, v] = it->next();
1163
394
            doris::RowsetMetaCloudPB rowset;
1164
394
            if (!rowset.ParseFromArray(v.data(), v.size())) {
1165
0
                LOG(WARNING) << "malformed rowset meta value, key=" << hex(k);
1166
0
                return -1;
1167
0
            }
1168
1169
394
            ++rowsets_num;
1170
394
            collect_cb(rowset);
1171
1172
394
            if (!it->has_next()) {
1173
50
                begin = k;
1174
50
                begin.push_back('\x00'); // Update to next smallest key for iteration
1175
50
                break;
1176
50
            }
1177
394
        }
1178
50
    }
1179
1180
53
    LOG(INFO) << fmt::format(
1181
53
            "[delete bitmap checker] successfully collect rowsets for instance_id={}, "
1182
53
            "tablet_id={}, rowsets_num={}",
1183
53
            instance_id_, tablet_id, rowsets_num);
1184
53
    return 0;
1185
53
}
1186
1187
5
int InstanceChecker::do_delete_bitmap_inverted_check() {
1188
5
    LOG(INFO) << fmt::format(
1189
5
            "[delete bitmap checker] begin to do_delete_bitmap_inverted_check for instance_id={}",
1190
5
            instance_id_);
1191
1192
    // number of delete bitmap keys being scanned
1193
5
    int64_t total_delete_bitmap_keys {0};
1194
    // number of delete bitmaps which belongs to non mow tablet
1195
5
    int64_t abnormal_delete_bitmaps {0};
1196
    // number of delete bitmaps which doesn't have corresponding rowset in MS
1197
5
    int64_t leaked_delete_bitmaps {0};
1198
1199
5
    auto start_time = std::chrono::steady_clock::now();
1200
5
    DORIS_CLOUD_DEFER {
1201
5
        g_bvar_inverted_checker_leaked_delete_bitmaps.put(instance_id_, leaked_delete_bitmaps);
1202
5
        g_bvar_inverted_checker_abnormal_delete_bitmaps.put(instance_id_, abnormal_delete_bitmaps);
1203
5
        g_bvar_inverted_checker_delete_bitmaps_scanned.put(instance_id_, total_delete_bitmap_keys);
1204
1205
5
        auto cost = std::chrono::duration_cast<std::chrono::milliseconds>(
1206
5
                            std::chrono::steady_clock::now() - start_time)
1207
5
                            .count();
1208
5
        if (leaked_delete_bitmaps > 0 || abnormal_delete_bitmaps > 0) {
1209
3
            LOG(WARNING) << fmt::format(
1210
3
                    "[delete bitmap check fails] delete bitmap inverted check for instance_id={}, "
1211
3
                    "cost={} ms, total_delete_bitmap_keys={}, leaked_delete_bitmaps={}, "
1212
3
                    "abnormal_delete_bitmaps={}",
1213
3
                    instance_id_, cost, total_delete_bitmap_keys, leaked_delete_bitmaps,
1214
3
                    abnormal_delete_bitmaps);
1215
3
        } else {
1216
2
            LOG(INFO) << fmt::format(
1217
2
                    "[delete bitmap checker] delete bitmap inverted check for instance_id={}, "
1218
2
                    "passed. cost={} ms, total_delete_bitmap_keys={}",
1219
2
                    instance_id_, cost, total_delete_bitmap_keys);
1220
2
        }
1221
5
    };
1222
1223
5
    struct TabletsRowsetsCache {
1224
5
        int64_t tablet_id {-1};
1225
5
        bool enable_merge_on_write {false};
1226
5
        std::unordered_set<std::string> rowsets {};
1227
5
        std::unordered_set<std::string> pending_delete_bitmaps {};
1228
5
    } tablet_rowsets_cache {};
1229
1230
5
    std::unordered_map<int64_t, std::unordered_set<std::string>> unexpired_tmp_rowsets;
1231
5
    if (int ret = collect_unexpired_job_tmp_rowsets(unexpired_tmp_rowsets); ret < 0) {
1232
0
        return ret;
1233
0
    }
1234
1235
5
    std::unique_ptr<RangeGetIterator> it;
1236
5
    auto begin = meta_delete_bitmap_key({instance_id_, 0, "", 0, 0});
1237
5
    auto end =
1238
5
            meta_delete_bitmap_key({instance_id_, std::numeric_limits<int64_t>::max(), "", 0, 0});
1239
10
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
1240
5
        std::unique_ptr<Transaction> txn;
1241
5
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1242
5
        if (err != TxnErrorCode::TXN_OK) {
1243
0
            LOG(WARNING) << "failed to create txn";
1244
0
            return -1;
1245
0
        }
1246
5
        err = txn->get(begin, end, &it);
1247
5
        if (err != TxnErrorCode::TXN_OK) {
1248
0
            LOG(WARNING) << "failed to get rowset kv, err=" << err;
1249
0
            return -1;
1250
0
        }
1251
5
        if (!it->has_next()) {
1252
0
            break;
1253
0
        }
1254
508
        while (it->has_next() && !stopped()) {
1255
503
            auto [k, v] = it->next();
1256
503
            std::string_view k1 = k;
1257
503
            k1.remove_prefix(1);
1258
503
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1259
503
            decode_key(&k1, &out);
1260
            // 0x01 "meta" ${instance_id} "delete_bitmap" ${tablet_id} ${rowset_id} ${version} ${segment_id} -> roaringbitmap
1261
503
            auto tablet_id = std::get<int64_t>(std::get<0>(out[3]));
1262
503
            auto rowset_id = std::get<std::string>(std::get<0>(out[4]));
1263
503
            auto version = std::get<std::int64_t>(std::get<0>(out[5]));
1264
503
            auto segment_id = std::get<std::int64_t>(std::get<0>(out[6]));
1265
1266
503
            ++total_delete_bitmap_keys;
1267
1268
503
            if (!it->has_next()) {
1269
5
                begin = k;
1270
5
                begin.push_back('\x00'); // Update to next smallest key for iteration
1271
5
            }
1272
1273
503
            if (tablet_rowsets_cache.tablet_id == -1 ||
1274
503
                tablet_rowsets_cache.tablet_id != tablet_id) {
1275
33
                if (tablet_rowsets_cache.tablet_id != -1) {
1276
28
                    unexpired_tmp_rowsets.erase(tablet_rowsets_cache.tablet_id);
1277
28
                }
1278
33
                TabletMetaCloudPB tablet_meta;
1279
33
                int ret = get_tablet_meta(txn_kv_.get(), instance_id_, tablet_id, tablet_meta);
1280
33
                if (ret < 0) {
1281
0
                    LOG(WARNING) << fmt::format(
1282
0
                            "[delete bitmap checker] failed to get_tablet_meta in "
1283
0
                            "do_delete_bitmap_inverted_check(), instance_id={}, tablet_id={}",
1284
0
                            instance_id_, tablet_id);
1285
0
                    return ret;
1286
0
                }
1287
1288
33
                tablet_rowsets_cache.tablet_id = tablet_id;
1289
33
                tablet_rowsets_cache.enable_merge_on_write =
1290
33
                        tablet_meta.enable_unique_key_merge_on_write();
1291
33
                tablet_rowsets_cache.rowsets.clear();
1292
33
                tablet_rowsets_cache.pending_delete_bitmaps.clear();
1293
1294
33
                if (tablet_rowsets_cache.enable_merge_on_write) {
1295
                    // only collect rowsets for merge-on-write tablet
1296
23
                    auto collect_cb =
1297
199
                            [&tablet_rowsets_cache](const doris::RowsetMetaCloudPB& rowset) {
1298
199
                                tablet_rowsets_cache.rowsets.insert(rowset.rowset_id_v2());
1299
199
                            };
1300
23
                    ret = collect_tablet_rowsets(tablet_id, collect_cb);
1301
23
                    if (ret < 0) {
1302
0
                        return ret;
1303
0
                    }
1304
                    // get pending delete bitmaps
1305
23
                    ret = get_pending_delete_bitmap_keys(
1306
23
                            tablet_id, tablet_rowsets_cache.pending_delete_bitmaps);
1307
23
                    if (ret < 0) {
1308
0
                        return ret;
1309
0
                    }
1310
23
                }
1311
33
            }
1312
503
            DCHECK_EQ(tablet_id, tablet_rowsets_cache.tablet_id);
1313
1314
503
            if (!tablet_rowsets_cache.enable_merge_on_write) {
1315
                // clang-format off
1316
40
                TEST_SYNC_POINT_CALLBACK(
1317
40
                        "InstanceChecker::do_delete_bitmap_inverted_check.get_abnormal_delete_bitmap",
1318
40
                        &tablet_id, &rowset_id, &version, &segment_id);
1319
                // clang-format on
1320
40
                ++abnormal_delete_bitmaps;
1321
                // log an error and continue to check the next delete bitmap
1322
40
                LOG(WARNING) << fmt::format(
1323
40
                        "[delete bitmap check fails] find a delete bitmap belongs to tablet "
1324
40
                        "which is not a merge-on-write table! instance_id={}, tablet_id={}, "
1325
40
                        "version={}, segment_id={}",
1326
40
                        instance_id_, tablet_id, version, segment_id);
1327
40
                continue;
1328
40
            }
1329
1330
463
            bool belongs_to_unexpired_tmp_rowset = false;
1331
463
            auto tmp_rowsets_it = unexpired_tmp_rowsets.find(tablet_id);
1332
463
            if (tmp_rowsets_it != unexpired_tmp_rowsets.end()) {
1333
1
                belongs_to_unexpired_tmp_rowset = tmp_rowsets_it->second.contains(rowset_id);
1334
1
            }
1335
1336
463
            if (!tablet_rowsets_cache.rowsets.contains(rowset_id) &&
1337
463
                !tablet_rowsets_cache.pending_delete_bitmaps.contains(std::string(k)) &&
1338
463
                !belongs_to_unexpired_tmp_rowset) {
1339
172
                TEST_SYNC_POINT_CALLBACK(
1340
172
                        "InstanceChecker::do_delete_bitmap_inverted_check.get_leaked_delete_bitmap",
1341
172
                        &tablet_id, &rowset_id, &version, &segment_id);
1342
172
                ++leaked_delete_bitmaps;
1343
                // log an error and continue to check the next delete bitmap
1344
172
                LOG(WARNING) << fmt::format(
1345
172
                        "[delete bitmap check fails] can't find corresponding rowset for delete "
1346
172
                        "bitmap instance_id={}, tablet_id={}, rowset_id={}, version={}, "
1347
172
                        "segment_id={}",
1348
172
                        instance_id_, tablet_id, rowset_id, version, segment_id);
1349
172
            }
1350
463
        }
1351
5
    }
1352
1353
5
    return (leaked_delete_bitmaps > 0 || abnormal_delete_bitmaps > 0) ? 1 : 0;
1354
5
}
1355
1356
int InstanceChecker::collect_unexpired_job_tmp_rowsets(
1357
5
        std::unordered_map<int64_t, std::unordered_set<std::string>>& tmp_rowsets) {
1358
5
    static constexpr int64_t max_unexpired_tmp_rowsets = 1000;
1359
5
    auto begin = meta_rowset_tmp_key({instance_id_, 0, 0});
1360
5
    auto end = meta_rowset_tmp_key({instance_id_, INT64_MAX, 0});
1361
5
    std::unique_ptr<RangeGetIterator> it;
1362
5
    int64_t num_scanned = 0;
1363
5
    int64_t num_non_job = 0;
1364
5
    int64_t num_skipped_non_job_txns = 0;
1365
5
    int64_t num_unexpired = 0;
1366
5
    int64_t num_expired = 0;
1367
5
    int64_t last_txn_id = -1;
1368
5
    int64_t current_time = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
1369
1370
8
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
1371
6
        std::unique_ptr<Transaction> txn;
1372
6
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1373
6
        if (err != TxnErrorCode::TXN_OK) {
1374
0
            LOG(WARNING) << "failed to create txn";
1375
0
            return -1;
1376
0
        }
1377
6
        err = txn->get(begin, end, &it);
1378
6
        if (err != TxnErrorCode::TXN_OK) {
1379
0
            LOG(WARNING) << "failed to get tmp rowset kv, err=" << err;
1380
0
            return -1;
1381
0
        }
1382
6
        if (!it->has_next()) {
1383
3
            break;
1384
3
        }
1385
5
        while (it->has_next() && !stopped()) {
1386
3
            auto [k, v] = it->next();
1387
3
            ++num_scanned;
1388
1389
3
            std::string_view k1 = k;
1390
3
            k1.remove_prefix(1);
1391
3
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1392
3
            if (decode_key(&k1, &out) != 0 || out.size() < 5) {
1393
0
                LOG(WARNING) << "malformed tmp rowset key, key=" << hex(k);
1394
0
                return -1;
1395
0
            }
1396
            // 0x01 "meta" ${instance_id} "rowset_tmp" ${txn_id} ${tablet_id} -> RowsetMetaCloudPB
1397
3
            auto txn_id = std::get<int64_t>(std::get<0>(out[3]));
1398
3
            bool is_first_rowset_of_txn = last_txn_id != txn_id;
1399
3
            last_txn_id = txn_id;
1400
1401
3
            doris::RowsetMetaCloudPB rowset;
1402
3
            if (!rowset.ParseFromArray(v.data(), v.size())) {
1403
0
                LOG(WARNING) << "malformed tmp rowset meta, key=" << hex(k);
1404
0
                return -1;
1405
0
            }
1406
3
            if (!rowset.has_job_id() || rowset.job_id().empty()) {
1407
1
                ++num_non_job;
1408
1
                if (is_first_rowset_of_txn) {
1409
1
                    ++num_skipped_non_job_txns;
1410
1
                    if (txn_id == INT64_MAX) {
1411
0
                        begin = end;
1412
1
                    } else {
1413
1
                        begin = meta_rowset_tmp_key({instance_id_, txn_id + 1, 0});
1414
1
                    }
1415
1
                    it.reset();
1416
1
                    break;
1417
1
                }
1418
0
                if (!it->has_next()) {
1419
0
                    begin = k;
1420
0
                    begin.push_back('\x00');
1421
0
                }
1422
0
                continue;
1423
1
            }
1424
1425
            // Must use the same threshold as the recycler so that a delete bitmap is never
1426
            // reported as leaked while its tmp rowset is still alive from the recycler's view.
1427
            // `earlest_ts` is a local sentinel initialized to 0 on purpose: it keeps the value
1428
            // below any real expiration so the helper never updates the recycler's
1429
            // earliest-ts bvar (the checker must not touch the recycler's metrics).
1430
2
            int64_t earlest_ts = 0;
1431
2
            int64_t expiration =
1432
2
                    calculate_tmp_rowset_expired_time(instance_id_, rowset, &earlest_ts);
1433
2
            if (current_time < expiration) {
1434
1
                tmp_rowsets[rowset.tablet_id()].insert(rowset.rowset_id_v2());
1435
1
                ++num_unexpired;
1436
1
                if (num_unexpired >= max_unexpired_tmp_rowsets) {
1437
0
                    LOG(WARNING)
1438
0
                            << "collect unexpired tmp rowsets for delete bitmap checker reached "
1439
0
                            << "limit, remaining tmp rowsets will not be considered and may cause "
1440
0
                            << "false positives, instance_id=" << instance_id_
1441
0
                            << ", num_scanned=" << num_scanned << ", num_non_job=" << num_non_job
1442
0
                            << ", num_skipped_non_job_txns=" << num_skipped_non_job_txns
1443
0
                            << ", num_unexpired=" << num_unexpired
1444
0
                            << ", num_expired=" << num_expired
1445
0
                            << ", limit=" << max_unexpired_tmp_rowsets;
1446
0
                    return 0;
1447
0
                }
1448
1
            } else {
1449
1
                ++num_expired;
1450
1
            }
1451
1452
2
            if (!it->has_next()) {
1453
2
                begin = k;
1454
2
                begin.push_back('\x00');
1455
2
            }
1456
2
        }
1457
3
    }
1458
1459
5
    LOG(INFO) << "collect unexpired tmp rowsets for delete bitmap checker finished, instance_id="
1460
5
              << instance_id_ << ", num_scanned=" << num_scanned << ", num_non_job=" << num_non_job
1461
5
              << ", num_skipped_non_job_txns=" << num_skipped_non_job_txns
1462
5
              << ", num_unexpired=" << num_unexpired << ", num_expired=" << num_expired;
1463
5
    return 0;
1464
5
}
1465
1466
int InstanceChecker::get_pending_delete_bitmap_keys(
1467
53
        int64_t tablet_id, std::unordered_set<std::string>& pending_delete_bitmaps) {
1468
53
    std::unique_ptr<Transaction> txn;
1469
53
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1470
53
    if (err != TxnErrorCode::TXN_OK) {
1471
0
        LOG(WARNING) << "failed to create txn";
1472
0
        return -1;
1473
0
    }
1474
53
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
1475
53
    std::string pending_val;
1476
53
    err = txn->get(pending_key, &pending_val);
1477
53
    if (err != TxnErrorCode::TXN_OK && err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1478
0
        LOG(WARNING) << "failed to get pending delete bitmap kv, err=" << err;
1479
0
        return -1;
1480
0
    }
1481
53
    if (err == TxnErrorCode::TXN_OK) {
1482
2
        PendingDeleteBitmapPB pending_info;
1483
2
        if (!pending_info.ParseFromString(pending_val)) [[unlikely]] {
1484
0
            LOG(WARNING) << "failed to parse PendingDeleteBitmapPB, tablet=" << tablet_id;
1485
0
            return -1;
1486
0
        }
1487
12
        for (auto& delete_bitmap_key : pending_info.delete_bitmap_keys()) {
1488
12
            pending_delete_bitmaps.emplace(std::string(delete_bitmap_key));
1489
12
        }
1490
2
    }
1491
53
    return 0;
1492
53
}
1493
1494
int InstanceChecker::check_inverted_index_file_storage_format_v1(
1495
        int64_t tablet_id, const std::string& file_path, const std::string& rowset_info,
1496
14
        RowsetIndexesFormatV1& rowset_index_cache_v1) {
1497
    // format v1: data/{tablet_id}/{rowset_id}_{seg_num}_{idx_id}{idx_suffix}.idx
1498
14
    std::string rowset_id;
1499
14
    int64_t segment_id;
1500
14
    std::string index_id_with_suffix_name;
1501
    // {rowset_id}_{seg_num}_{idx_id}{idx_suffix}.idx
1502
14
    std::vector<std::string> str;
1503
14
    butil::SplitString(rowset_info.substr(0, rowset_info.size() - 4), '_', &str);
1504
14
    if (str.size() < 3) {
1505
0
        LOG(WARNING) << "Split rowset info with '_' error, str size < 3, rowset_info = "
1506
0
                     << rowset_info;
1507
0
        return -1;
1508
0
    }
1509
14
    rowset_id = str[0];
1510
14
    segment_id = std::atoll(str[1].c_str());
1511
14
    index_id_with_suffix_name = str[2];
1512
1513
14
    if (rowset_index_cache_v1.rowset_id == rowset_id) {
1514
0
        if (rowset_index_cache_v1.segment_ids.contains(segment_id)) {
1515
0
            if (auto it = rowset_index_cache_v1.index_ids.find(index_id_with_suffix_name);
1516
0
                it == rowset_index_cache_v1.index_ids.end()) {
1517
                // clang-format off
1518
0
                LOG(WARNING) << fmt::format("index_id with suffix name not found, rowset_info = {}, obj_key = {}", rowset_info, file_path);
1519
                // clang-format on
1520
0
                return -1;
1521
0
            }
1522
0
        } else {
1523
            // clang-format off
1524
0
            LOG(WARNING) << fmt::format("segment id not found, rowset_info = {}, obj_key = {}", rowset_info, file_path);
1525
            // clang-format on
1526
0
            return -1;
1527
0
        }
1528
0
    }
1529
1530
14
    rowset_index_cache_v1.rowset_id = rowset_id;
1531
14
    rowset_index_cache_v1.segment_ids.clear();
1532
14
    rowset_index_cache_v1.index_ids.clear();
1533
1534
14
    std::unique_ptr<Transaction> txn;
1535
14
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1536
14
    if (err != TxnErrorCode::TXN_OK) {
1537
0
        LOG(WARNING) << "failed to create txn";
1538
0
        return -1;
1539
0
    }
1540
14
    std::unique_ptr<RangeGetIterator> it;
1541
14
    auto begin = meta_rowset_key({instance_id_, tablet_id, 0});
1542
14
    auto end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
1543
20
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
1544
14
        TxnErrorCode err = txn->get(begin, end, &it);
1545
14
        if (err != TxnErrorCode::TXN_OK) {
1546
0
            LOG(WARNING) << "failed to get rowset kv, err=" << err;
1547
0
            return -1;
1548
0
        }
1549
14
        if (!it->has_next()) {
1550
8
            break;
1551
8
        }
1552
6
        while (it->has_next()) {
1553
            // recycle corresponding resources
1554
6
            auto [k, v] = it->next();
1555
6
            doris::RowsetMetaCloudPB rs_meta;
1556
6
            if (!rs_meta.ParseFromArray(v.data(), v.size())) {
1557
0
                LOG(WARNING) << "malformed rowset meta value, key=" << hex(k);
1558
0
                return -1;
1559
0
            }
1560
1561
6
            TabletIndexPB tablet_index;
1562
6
            if (get_tablet_idx(txn_kv_.get(), instance_id_, rs_meta.tablet_id(), tablet_index) ==
1563
6
                -1) {
1564
0
                LOG(WARNING) << "failedt to get tablet index, tablet_id= " << rs_meta.tablet_id();
1565
0
                return -1;
1566
0
            }
1567
1568
6
            auto tablet_schema_key = meta_schema_key(
1569
6
                    {instance_id_, tablet_index.index_id(), rs_meta.schema_version()});
1570
6
            ValueBuf tablet_schema_val;
1571
6
            err = cloud::blob_get(txn.get(), tablet_schema_key, &tablet_schema_val);
1572
1573
6
            if (err != TxnErrorCode::TXN_OK) {
1574
0
                LOG(WARNING) << "failed to get schema, err=" << err;
1575
0
                return -1;
1576
0
            }
1577
1578
6
            auto* schema = rs_meta.mutable_tablet_schema();
1579
6
            if (!parse_schema_value(tablet_schema_val, schema)) {
1580
0
                LOG(WARNING) << "malformed schema value, key=" << hex(tablet_schema_key);
1581
0
                return -1;
1582
0
            }
1583
1584
12
            for (size_t i = 0; i < rs_meta.num_segments(); i++) {
1585
6
                rowset_index_cache_v1.segment_ids.insert(i);
1586
6
            }
1587
1588
6
            for (const auto& i : rs_meta.tablet_schema().index()) {
1589
6
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
1590
6
                    LOG(INFO) << fmt::format(
1591
6
                            "record index info, index_id: {}, index_suffix_name: {}", i.index_id(),
1592
6
                            i.index_suffix_name());
1593
6
                    rowset_index_cache_v1.index_ids.insert(
1594
6
                            fmt::format("{}{}", i.index_id(), i.index_suffix_name()));
1595
6
                }
1596
6
            }
1597
1598
6
            if (!it->has_next()) {
1599
6
                begin = k;
1600
6
                begin.push_back('\x00'); // Update to next smallest key for iteration
1601
6
                break;
1602
6
            }
1603
6
        }
1604
6
    }
1605
1606
14
    if (!rowset_index_cache_v1.segment_ids.contains(segment_id)) {
1607
        // Garbage data leak
1608
        // clang-format off
1609
8
        LOG(WARNING) << "rowset_index_cache_v1.segment_ids don't contains segment_id, rowset should be recycled,"
1610
8
                     << " key = " << file_path
1611
8
                     << " segment_id = " << segment_id;
1612
        // clang-format on
1613
8
        return 1;
1614
8
    }
1615
1616
6
    if (!rowset_index_cache_v1.index_ids.contains(index_id_with_suffix_name)) {
1617
        // Garbage data leak
1618
        // clang-format off
1619
0
        LOG(WARNING) << "rowset_index_cache_v1.index_ids don't contains index_id_with_suffix_name,"
1620
0
                     << " rowset with inde meta should be recycled, key=" << file_path
1621
0
                     << " index_id_with_suffix_name=" << index_id_with_suffix_name;
1622
        // clang-format on
1623
0
        return 1;
1624
0
    }
1625
1626
6
    return 0;
1627
6
}
1628
1629
int InstanceChecker::check_inverted_index_file_storage_format_v2(
1630
        int64_t tablet_id, const std::string& file_path, const std::string& rowset_info,
1631
40
        RowsetIndexesFormatV2& rowset_index_cache_v2) {
1632
40
    std::string rowset_id;
1633
40
    int64_t segment_id;
1634
    // {rowset_id}_{seg_num}.idx
1635
40
    std::vector<std::string> str;
1636
40
    butil::SplitString(rowset_info.substr(0, rowset_info.size() - 4), '_', &str);
1637
40
    if (str.size() < 2) {
1638
        // clang-format off
1639
0
        LOG(WARNING) << "Split rowset info with '_' error, str size < 2, rowset_info = " << rowset_info;
1640
        // clang-format on
1641
0
        return -1;
1642
0
    }
1643
40
    rowset_id = str[0];
1644
40
    segment_id = std::atoll(str[1].c_str());
1645
1646
40
    if (rowset_index_cache_v2.rowset_id == rowset_id) {
1647
0
        if (!rowset_index_cache_v2.segment_ids.contains(segment_id)) {
1648
            // clang-format off
1649
0
            LOG(WARNING) << fmt::format("index file not found, rowset_info = {}, obj_key = {}", rowset_info, file_path);
1650
            // clang-format on
1651
0
            return -1;
1652
0
        }
1653
0
    }
1654
1655
40
    rowset_index_cache_v2.rowset_id = rowset_id;
1656
40
    rowset_index_cache_v2.segment_ids.clear();
1657
1658
40
    std::unique_ptr<Transaction> txn;
1659
40
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1660
40
    if (err != TxnErrorCode::TXN_OK) {
1661
0
        LOG(WARNING) << "failed to create txn";
1662
0
        return -1;
1663
0
    }
1664
40
    std::unique_ptr<RangeGetIterator> it;
1665
40
    auto begin = meta_rowset_key({instance_id_, tablet_id, 0});
1666
40
    auto end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
1667
75
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
1668
40
        TxnErrorCode err = txn->get(begin, end, &it);
1669
40
        if (err != TxnErrorCode::TXN_OK) {
1670
0
            LOG(WARNING) << "failed to get rowset kv, err=" << err;
1671
0
            return -1;
1672
0
        }
1673
40
        if (!it->has_next()) {
1674
5
            break;
1675
5
        }
1676
35
        while (it->has_next()) {
1677
            // recycle corresponding resources
1678
35
            auto [k, v] = it->next();
1679
35
            doris::RowsetMetaCloudPB rs_meta;
1680
35
            if (!rs_meta.ParseFromArray(v.data(), v.size())) {
1681
0
                LOG(WARNING) << "malformed rowset meta value, key=" << hex(k);
1682
0
                return -1;
1683
0
            }
1684
1685
70
            for (size_t i = 0; i < rs_meta.num_segments(); i++) {
1686
35
                rowset_index_cache_v2.segment_ids.insert(i);
1687
35
            }
1688
1689
35
            if (!it->has_next()) {
1690
35
                begin = k;
1691
35
                begin.push_back('\x00'); // Update to next smallest key for iteration
1692
35
                break;
1693
35
            }
1694
35
        }
1695
35
    }
1696
1697
40
    if (!rowset_index_cache_v2.segment_ids.contains(segment_id)) {
1698
        // Garbage data leak
1699
5
        LOG(WARNING) << "rowset with index meta should be recycled, key=" << file_path;
1700
5
        return 1;
1701
5
    }
1702
1703
35
    return 0;
1704
40
}
1705
1706
int InstanceChecker::check_delete_bitmap_storage_optimize_v2(
1707
        int64_t tablet_id, bool has_sequence_col,
1708
30
        int64_t& rowsets_with_useless_delete_bitmap_version) {
1709
    // end_version: create_time
1710
30
    std::map<int64_t, int64_t> tablet_rowsets_map {};
1711
    // rowset_id: {start_version, end_version}
1712
30
    std::map<std::string, std::pair<int64_t, int64_t>> rowset_version_map;
1713
    // Get all visible rowsets of this tablet
1714
195
    auto collect_cb = [&](const doris::RowsetMetaCloudPB& rowset) {
1715
195
        if (rowset.start_version() == 0 && rowset.end_version() == 1) {
1716
            // ignore dummy rowset [0-1]
1717
0
            return;
1718
0
        }
1719
195
        tablet_rowsets_map[rowset.end_version()] = rowset.creation_time();
1720
195
        rowset_version_map[rowset.rowset_id_v2()] =
1721
195
                std::make_pair(rowset.start_version(), rowset.end_version());
1722
195
    };
1723
30
    if (int ret = collect_tablet_rowsets(tablet_id, collect_cb); ret != 0) {
1724
0
        return ret;
1725
0
    }
1726
1727
30
    std::unordered_set<std::string> pending_delete_bitmaps;
1728
30
    if (auto ret = get_pending_delete_bitmap_keys(tablet_id, pending_delete_bitmaps); ret < 0) {
1729
0
        return ret;
1730
0
    }
1731
1732
30
    std::unique_ptr<RangeGetIterator> it;
1733
30
    auto begin = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
1734
30
    auto end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
1735
30
    std::string last_rowset_id = "";
1736
30
    int64_t last_version = 0;
1737
30
    int64_t last_failed_version = 0;
1738
30
    std::vector<int64_t> failed_versions;
1739
30
    auto print_failed_versions = [&]() {
1740
4
        TEST_SYNC_POINT_CALLBACK(
1741
4
                "InstanceChecker::check_delete_bitmap_storage_optimize_v2.get_abnormal_"
1742
4
                "rowset",
1743
4
                &tablet_id, &last_rowset_id);
1744
4
        rowsets_with_useless_delete_bitmap_version++;
1745
        // some versions are continuous, such as [8, 9, 10, 11, 13, 17, 18]
1746
        // print as [8-11, 13, 17-18]
1747
4
        int64_t last_start_version = -1;
1748
4
        int64_t last_end_version = -1;
1749
4
        std::stringstream ss;
1750
4
        ss << "[";
1751
9
        for (int64_t version : failed_versions) {
1752
9
            if (last_start_version == -1) {
1753
4
                last_start_version = version;
1754
4
                last_end_version = version;
1755
4
                continue;
1756
4
            }
1757
5
            if (last_end_version + 1 == version) {
1758
2
                last_end_version = version;
1759
3
            } else {
1760
3
                if (last_start_version == last_end_version) {
1761
3
                    ss << last_start_version << ", ";
1762
3
                } else {
1763
0
                    ss << last_start_version << "-" << last_end_version << ", ";
1764
0
                }
1765
3
                last_start_version = version;
1766
3
                last_end_version = version;
1767
3
            }
1768
5
        }
1769
4
        if (last_start_version == last_end_version) {
1770
3
            ss << last_start_version;
1771
3
        } else {
1772
1
            ss << last_start_version << "-" << last_end_version;
1773
1
        }
1774
4
        ss << "]";
1775
4
        std::stringstream version_str;
1776
4
        auto it = rowset_version_map.find(last_rowset_id);
1777
4
        if (it != rowset_version_map.end()) {
1778
4
            version_str << "[" << it->second.first << "-" << it->second.second << "]";
1779
4
        }
1780
4
        LOG(WARNING) << fmt::format(
1781
4
                "[delete bitmap check fails] delete bitmap storage optimize v2 check fail "
1782
4
                "for instance_id={}, tablet_id={}, rowset_id={}, version={} found delete "
1783
4
                "bitmap with versions={}, size={}",
1784
4
                instance_id_, tablet_id, last_rowset_id, version_str.str(), ss.str(),
1785
4
                failed_versions.size());
1786
4
    };
1787
30
    using namespace std::chrono;
1788
30
    int64_t now = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
1789
60
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
1790
30
        std::unique_ptr<Transaction> txn;
1791
30
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1792
30
        if (err != TxnErrorCode::TXN_OK) {
1793
0
            LOG(WARNING) << "failed to create txn";
1794
0
            return -1;
1795
0
        }
1796
30
        err = txn->get(begin, end, &it);
1797
30
        if (err != TxnErrorCode::TXN_OK) {
1798
0
            LOG(WARNING) << "failed to get delete bitmap kv, err=" << err;
1799
0
            return -1;
1800
0
        }
1801
30
        if (!it->has_next()) {
1802
0
            break;
1803
0
        }
1804
771
        while (it->has_next() && !stopped()) {
1805
741
            auto [k, v] = it->next();
1806
741
            std::string_view k1 = k;
1807
741
            k1.remove_prefix(1);
1808
741
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1809
741
            decode_key(&k1, &out);
1810
            // 0x01 "meta" ${instance_id} "delete_bitmap" ${tablet_id} ${rowset_id} ${version} ${segment_id} -> roaringbitmap
1811
741
            auto rowset_id = std::get<std::string>(std::get<0>(out[4]));
1812
741
            auto version = std::get<std::int64_t>(std::get<0>(out[5]));
1813
741
            if (!it->has_next()) {
1814
30
                begin = k;
1815
30
                begin.push_back('\x00'); // Update to next smallest key for iteration
1816
30
            }
1817
741
            if (rowset_id == last_rowset_id && version == last_version) {
1818
                // skip the same rowset and version
1819
167
                continue;
1820
167
            }
1821
574
            if (rowset_id != last_rowset_id && !failed_versions.empty()) {
1822
3
                print_failed_versions();
1823
3
                last_failed_version = 0;
1824
3
                failed_versions.clear();
1825
3
            }
1826
574
            last_rowset_id = rowset_id;
1827
574
            last_version = version;
1828
574
            if (tablet_rowsets_map.find(version) != tablet_rowsets_map.end()) {
1829
548
                continue;
1830
548
            }
1831
26
            auto version_it = rowset_version_map.find(rowset_id);
1832
26
            if (version_it == rowset_version_map.end()) {
1833
                // checked in do_delete_bitmap_inverted_check
1834
1
                continue;
1835
1
            }
1836
25
            if (pending_delete_bitmaps.contains(std::string(k))) {
1837
3
                continue;
1838
3
            }
1839
22
            if (has_sequence_col && version >= version_it->second.first &&
1840
22
                version <= version_it->second.second) {
1841
5
                continue;
1842
5
            }
1843
            // there may be an interval in this situation:
1844
            // 1. finish compaction job; 2. checker; 3. finish agg and remove delete bitmap to ms
1845
17
            auto rowset_it = tablet_rowsets_map.upper_bound(version);
1846
17
            if (rowset_it == tablet_rowsets_map.end()) {
1847
1
                if (version != last_failed_version) {
1848
1
                    failed_versions.push_back(version);
1849
1
                }
1850
1
                last_failed_version = version;
1851
1
                continue;
1852
1
            }
1853
16
            if (rowset_it->second + config::delete_bitmap_storage_optimize_v2_check_skip_seconds >=
1854
16
                now) {
1855
8
                continue;
1856
8
            }
1857
8
            if (version != last_failed_version) {
1858
8
                failed_versions.push_back(version);
1859
8
            }
1860
8
            last_failed_version = version;
1861
8
        }
1862
30
    }
1863
30
    if (!failed_versions.empty()) {
1864
1
        print_failed_versions();
1865
1
    }
1866
30
    LOG(INFO) << fmt::format(
1867
30
            "[delete bitmap checker] finish check delete bitmap storage optimize v2 for "
1868
30
            "instance_id={}, tablet_id={}, rowsets_num={}, "
1869
30
            "rowsets_with_useless_delete_bitmap_version={}",
1870
30
            instance_id_, tablet_id, tablet_rowsets_map.size(),
1871
30
            rowsets_with_useless_delete_bitmap_version);
1872
30
    return (rowsets_with_useless_delete_bitmap_version > 1 ? 1 : 0);
1873
30
}
1874
1875
3
int InstanceChecker::do_delete_bitmap_storage_optimize_check(int version) {
1876
3
    if (version != 2) {
1877
0
        return -1;
1878
0
    }
1879
3
    int64_t total_tablets_num {0};
1880
3
    int64_t failed_tablets_num {0};
1881
1882
    // for v2 check
1883
3
    int64_t max_rowsets_with_useless_delete_bitmap_version = 0;
1884
3
    int64_t tablet_id_with_max_rowsets_with_useless_delete_bitmap_version = 0;
1885
1886
    // check that for every visible rowset, there exists at least delete one bitmap in MS
1887
30
    int ret = traverse_mow_tablet([&](int64_t tablet_id, bool has_sequence_col) {
1888
30
        ++total_tablets_num;
1889
30
        int64_t rowsets_with_useless_delete_bitmap_version = 0;
1890
30
        int res = check_delete_bitmap_storage_optimize_v2(
1891
30
                tablet_id, has_sequence_col, rowsets_with_useless_delete_bitmap_version);
1892
30
        if (rowsets_with_useless_delete_bitmap_version >
1893
30
            max_rowsets_with_useless_delete_bitmap_version) {
1894
1
            max_rowsets_with_useless_delete_bitmap_version =
1895
1
                    rowsets_with_useless_delete_bitmap_version;
1896
1
            tablet_id_with_max_rowsets_with_useless_delete_bitmap_version = tablet_id;
1897
1
        }
1898
30
        failed_tablets_num += (res != 0);
1899
30
        return res;
1900
30
    });
1901
1902
3
    if (ret < 0) {
1903
0
        return ret;
1904
0
    }
1905
1906
3
    g_bvar_max_rowsets_with_useless_delete_bitmap_version.put(
1907
3
            instance_id_, max_rowsets_with_useless_delete_bitmap_version);
1908
1909
3
    std::stringstream ss;
1910
3
    ss << "[delete bitmap checker] check delete bitmap storage optimize v" << version
1911
3
       << " for instance_id=" << instance_id_ << ", total_tablets_num=" << total_tablets_num
1912
3
       << ", failed_tablets_num=" << failed_tablets_num
1913
3
       << ". max_rowsets_with_useless_delete_bitmap_version="
1914
3
       << max_rowsets_with_useless_delete_bitmap_version
1915
3
       << ", tablet_id=" << tablet_id_with_max_rowsets_with_useless_delete_bitmap_version;
1916
3
    LOG(INFO) << ss.str();
1917
1918
3
    return (failed_tablets_num > 0) ? 1 : 0;
1919
3
}
1920
1921
3
int InstanceChecker::do_mow_job_key_check() {
1922
3
    std::unique_ptr<RangeGetIterator> it;
1923
3
    std::string begin = mow_tablet_job_key({instance_id_, 0, 0});
1924
3
    std::string end = mow_tablet_job_key({instance_id_, INT64_MAX, 0});
1925
3
    MowTabletJobPB mow_tablet_job;
1926
4
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
1927
3
        std::unique_ptr<Transaction> txn;
1928
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1929
3
        if (err != TxnErrorCode::TXN_OK) {
1930
0
            LOG(WARNING) << "failed to create txn";
1931
0
            return -1;
1932
0
        }
1933
3
        err = txn->get(begin, end, &it);
1934
3
        if (err != TxnErrorCode::TXN_OK) {
1935
0
            LOG(WARNING) << "failed to get mow tablet job key, err=" << err;
1936
0
            return -1;
1937
0
        }
1938
3
        int64_t now = duration_cast<std::chrono::seconds>(
1939
3
                              std::chrono::system_clock::now().time_since_epoch())
1940
3
                              .count();
1941
3
        while (it->has_next() && !stopped()) {
1942
2
            auto [k, v] = it->next();
1943
2
            std::string_view k1 = k;
1944
2
            k1.remove_prefix(1);
1945
2
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1946
2
            decode_key(&k1, &out);
1947
            // 0x01 "meta" ${instance_id} "mow_tablet_job" ${table_id} ${initiator}
1948
2
            auto table_id = std::get<int64_t>(std::get<0>(out[3]));
1949
2
            auto initiator = std::get<int64_t>(std::get<0>(out[4]));
1950
2
            if (!mow_tablet_job.ParseFromArray(v.data(), v.size())) [[unlikely]] {
1951
0
                LOG(WARNING) << "failed to parse MowTabletJobPB";
1952
0
                return -1;
1953
0
            }
1954
2
            int64_t expiration = mow_tablet_job.expiration();
1955
            // check job key failed should meet both following two condition:
1956
            // 1. job key is expired
1957
            // 2. table lock key is not found or key is not expired
1958
2
            if (expiration < now - config::mow_job_key_check_expiration_diff_seconds) {
1959
2
                std::string lock_key =
1960
2
                        meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
1961
2
                std::string lock_val;
1962
2
                err = txn->get(lock_key, &lock_val);
1963
2
                std::string reason = "";
1964
2
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1965
0
                    reason = "table lock key not found";
1966
1967
2
                } else {
1968
2
                    DeleteBitmapUpdateLockPB lock_info;
1969
2
                    if (!lock_info.ParseFromString(lock_val)) [[unlikely]] {
1970
0
                        LOG(WARNING) << "failed to parse DeleteBitmapUpdateLockPB";
1971
0
                        return -1;
1972
0
                    }
1973
2
                    if (lock_info.expiration() > now || lock_info.lock_id() != -1) {
1974
2
                        reason = "table lock is not expired,lock_id=" +
1975
2
                                 std::to_string(lock_info.lock_id());
1976
2
                    }
1977
2
                }
1978
2
                if (reason != "") {
1979
2
                    LOG(WARNING) << fmt::format(
1980
2
                            "[compaction key check fails] mow job key check fail for "
1981
2
                            "instance_id={}, table_id={}, initiator={}, expiration={}, now={}, "
1982
2
                            "reason={}",
1983
2
                            instance_id_, table_id, initiator, expiration, now, reason);
1984
2
                    return -1;
1985
2
                }
1986
2
            }
1987
2
        }
1988
1
        begin = it->next_begin_key(); // Update to next smallest key for iteration
1989
1
    }
1990
1
    return 0;
1991
3
}
1992
4
int InstanceChecker::do_tablet_stats_key_check() {
1993
4
    int ret = 0;
1994
1995
4
    int64_t nums_leak = 0;
1996
4
    int64_t nums_loss = 0;
1997
4
    int64_t nums_scanned = 0;
1998
4
    int64_t nums_abnormal = 0;
1999
2000
4
    std::string begin = meta_tablet_key({instance_id_, 0, 0, 0, 0});
2001
4
    std::string end = meta_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
2002
    // inverted check tablet exists
2003
4
    LOG(INFO) << "begin inverted check stats_tablet_key";
2004
4
    ret = scan_and_handle_kv(begin, end, [&](std::string_view key, std::string_view value) {
2005
4
        int ret = check_stats_tablet_key_exists(key, value);
2006
4
        nums_scanned++;
2007
4
        if (ret == 1) {
2008
1
            nums_loss++;
2009
1
        }
2010
4
        return ret;
2011
4
    });
2012
4
    if (ret == -1) {
2013
0
        LOG(WARNING) << "failed to inverted check if stats tablet key exists";
2014
0
        return -1;
2015
4
    } else if (ret == 1) {
2016
1
        LOG(WARNING) << "stats_tablet_key loss, nums_scanned=" << nums_scanned
2017
1
                     << ", nums_loss=" << nums_loss;
2018
1
        return 1;
2019
1
    }
2020
3
    LOG(INFO) << "finish inverted check stats_tablet_key, nums_scanned=" << nums_scanned
2021
3
              << ", nums_loss=" << nums_loss;
2022
2023
3
    begin = stats_tablet_key({instance_id_, 0, 0, 0, 0});
2024
3
    end = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
2025
3
    nums_scanned = 0;
2026
    // check tablet exists
2027
3
    LOG(INFO) << "begin check stats_tablet_key leaked";
2028
4
    ret = scan_and_handle_kv(begin, end, [&](std::string_view key, std::string_view value) {
2029
4
        int ret = check_stats_tablet_key_leaked(key, value);
2030
4
        nums_scanned++;
2031
4
        if (ret == 1) {
2032
1
            nums_leak++;
2033
1
        }
2034
4
        return ret;
2035
4
    });
2036
3
    if (ret == -1) {
2037
0
        LOG(WARNING) << "failed to check if stats tablet key exists";
2038
0
        return -1;
2039
3
    } else if (ret == 1) {
2040
1
        LOG(WARNING) << "stats_tablet_key leaked, nums_scanned=" << nums_scanned
2041
1
                     << ", nums_leak=" << nums_leak;
2042
1
        return 1;
2043
1
    }
2044
2
    LOG(INFO) << "finish check stats_tablet_key leaked, nums_scanned=" << nums_scanned
2045
2
              << ", nums_leak=" << nums_leak;
2046
2047
2
    begin = stats_tablet_key({instance_id_, 0, 0, 0, 0});
2048
2
    end = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
2049
2
    nums_scanned = 0;
2050
    // check if key is normal
2051
2
    LOG(INFO) << "begin check stats_tablet_key abnormal";
2052
2
    ret = scan_and_handle_kv(begin, end, [&](std::string_view key, std::string_view value) {
2053
2
        int ret = check_stats_tablet_key(key, value);
2054
2
        nums_scanned++;
2055
2
        if (ret == 1) {
2056
1
            nums_abnormal++;
2057
1
        }
2058
2
        return ret;
2059
2
    });
2060
2
    if (ret == -1) {
2061
0
        LOG(WARNING) << "failed to check if stats tablet key exists";
2062
0
        return -1;
2063
2
    } else if (ret == 1) {
2064
1
        LOG(WARNING) << "stats_tablet_key abnormal, nums_scanned=" << nums_scanned
2065
1
                     << ", nums_abnormal=" << nums_abnormal;
2066
1
        return 1;
2067
1
    }
2068
1
    LOG(INFO) << "finish check stats_tablet_key, nums_scanned=" << nums_scanned
2069
1
              << ", nums_abnormal=" << nums_abnormal;
2070
1
    return 0;
2071
2
}
2072
2073
4
int InstanceChecker::check_stats_tablet_key_exists(std::string_view key, std::string_view value) {
2074
4
    std::string_view k1 = key;
2075
4
    k1.remove_prefix(1);
2076
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2077
4
    decode_key(&k1, &out);
2078
    // 0x01 "meta" ${instance_id} "tablet" ${table_id} ${index_id} ${partition_id} ${tablet_id}
2079
4
    auto table_id = std::get<int64_t>(std::get<0>(out[3]));
2080
4
    auto index_id = std::get<int64_t>(std::get<0>(out[4]));
2081
4
    auto partition_id = std::get<int64_t>(std::get<0>(out[5]));
2082
4
    auto tablet_id = std::get<int64_t>(std::get<0>(out[6]));
2083
4
    std::string tablet_stats_key =
2084
4
            stats_tablet_key({instance_id_, table_id, index_id, partition_id, tablet_id});
2085
4
    int ret = key_exist(txn_kv_.get(), tablet_stats_key);
2086
4
    if (ret == 1) {
2087
        // clang-format off
2088
1
        LOG(WARNING) << "stats tablet key's tablet key loss,"
2089
1
                    << " stats tablet key=" << hex(tablet_stats_key)
2090
1
                    << " meta tablet key=" << hex(key);
2091
        // clang-format on
2092
1
        return 1;
2093
3
    } else if (ret == -1) {
2094
0
        LOG(WARNING) << "failed to check key exists, key=" << hex(tablet_stats_key);
2095
0
        return -1;
2096
0
    }
2097
3
    LOG(INFO) << "check stats_tablet_key_exists ok, key=" << hex(key);
2098
3
    return 0;
2099
4
}
2100
2101
4
int InstanceChecker::check_stats_tablet_key_leaked(std::string_view key, std::string_view value) {
2102
4
    std::string_view k1 = key;
2103
4
    k1.remove_prefix(1);
2104
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2105
4
    decode_key(&k1, &out);
2106
    // 0x01 "stats" ${instance_id} "tablet" ${table_id} ${index_id} ${partition_id} ${tablet_id}
2107
4
    auto table_id = std::get<int64_t>(std::get<0>(out[3]));
2108
4
    auto index_id = std::get<int64_t>(std::get<0>(out[4]));
2109
4
    auto partition_id = std::get<int64_t>(std::get<0>(out[5]));
2110
4
    auto tablet_id = std::get<int64_t>(std::get<0>(out[6]));
2111
4
    std::string tablet_key =
2112
4
            meta_tablet_key({instance_id_, table_id, index_id, partition_id, tablet_id});
2113
4
    int ret = key_exist(txn_kv_.get(), tablet_key);
2114
4
    if (ret == 1) {
2115
        // clang-format off
2116
1
        LOG(WARNING) << "stats tablet key's tablet key leak,"
2117
1
                    << " stats tablet key=" << hex(key)
2118
1
                    << " meta tablet key=" << hex(tablet_key);
2119
        // clang-format on
2120
1
        return 1;
2121
3
    } else if (ret == -1) {
2122
0
        LOG(WARNING) << "failed to check key exists, key=" << hex(tablet_key);
2123
0
        return -1;
2124
0
    }
2125
3
    LOG(INFO) << "check stats_tablet_key_leaked ok, key=" << hex(key);
2126
3
    return 0;
2127
4
}
2128
2129
2
int InstanceChecker::check_stats_tablet_key(std::string_view key, std::string_view value) {
2130
2
    TabletStatsPB tablet_stats_pb;
2131
2
    std::string_view k1 = key;
2132
2
    k1.remove_prefix(1);
2133
2
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2134
2
    decode_key(&k1, &out);
2135
    // 0x01 "stats" ${instance_id} "tablet" ${table_id} ${index_id} ${partition_id} ${tablet_id}
2136
2
    auto tablet_id = std::get<int64_t>(std::get<0>(out[6]));
2137
2
    std::unique_ptr<Transaction> txn;
2138
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2139
2
    if (err != TxnErrorCode::TXN_OK) {
2140
0
        LOG_WARNING("failed to recycle tablet ")
2141
0
                .tag("tablet id", tablet_id)
2142
0
                .tag("instance_id", instance_id_)
2143
0
                .tag("reason", "failed to create txn");
2144
0
        return -1;
2145
0
    }
2146
2
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id_, tablet_id});
2147
2
    std::string tablet_idx_val;
2148
2
    TabletIndexPB tablet_idx;
2149
2
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2150
2
    if (err != TxnErrorCode::TXN_OK) {
2151
        // clang-format off
2152
0
        LOG(WARNING) << "failed to get tablet index key,"
2153
0
                        << " key=" << hex(tablet_idx_key)
2154
0
                        << " code=" << err;
2155
        // clang-format on
2156
0
        return -1;
2157
0
    }
2158
2
    tablet_idx.ParseFromString(tablet_idx_val);
2159
2
    MetaServiceCode code = MetaServiceCode::OK;
2160
2
    std::string msg;
2161
2
    internal_get_tablet_stats(code, msg, txn.get(), instance_id_, tablet_idx, tablet_stats_pb);
2162
2
    if (code != MetaServiceCode::OK) {
2163
        // clang-format off
2164
0
        LOG(WARNING) << "failed to get tablet stats,"
2165
0
                        << " code=" << code 
2166
0
                        << " msg=" << msg;
2167
        // clang-format on
2168
0
        return -1;
2169
0
    }
2170
2171
2
    GetRowsetResponse resp;
2172
    // get rowsets in tablet
2173
2
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
2174
2
                        tablet_id, code, msg, &resp);
2175
2
    if (code != MetaServiceCode::OK) {
2176
0
        LOG_WARNING("failed to get rowsets of tablet when check stats tablet key")
2177
0
                .tag("tablet id", tablet_id)
2178
0
                .tag("msg", msg)
2179
0
                .tag("code", code)
2180
0
                .tag("instance id", instance_id_);
2181
0
        return -1;
2182
0
    }
2183
2
    int64_t num_rows = 0;
2184
2
    int64_t num_rowsets = 0;
2185
2
    int64_t num_segments = 0;
2186
2
    int64_t total_data_size = 0;
2187
2
    for (const auto& rs_meta : resp.rowset_meta()) {
2188
2
        num_rows += rs_meta.num_rows();
2189
2
        num_rowsets++;
2190
2
        num_segments += rs_meta.num_segments();
2191
2
        total_data_size += rs_meta.total_disk_size();
2192
2
    }
2193
2
    int ret = 0;
2194
2
    if (tablet_stats_pb.data_size() != total_data_size) {
2195
1
        ret = 1;
2196
        // clang-format off
2197
1
        LOG(WARNING) << " tablet_stats_pb's data size is not same with all rowset total data size,"
2198
1
                        << " tablet_stats_pb's data size=" << tablet_stats_pb.data_size()
2199
1
                        << " all rowset total data size=" << total_data_size
2200
1
                        << " stats tablet meta=" << tablet_stats_pb.ShortDebugString();
2201
        // clang-format on
2202
1
    } else if (tablet_stats_pb.num_rows() != num_rows) {
2203
0
        ret = 1;
2204
        // clang-format off
2205
0
        LOG(WARNING) << " tablet_stats_pb's num_rows is not same with all rowset total num_rows,"
2206
0
                        << " tablet_stats_pb's num_rows=" << tablet_stats_pb.num_rows()
2207
0
                        << " all rowset total num_rows=" << num_rows
2208
0
                        << " stats tablet meta=" << tablet_stats_pb.ShortDebugString();
2209
        // clang-format on
2210
1
    } else if (tablet_stats_pb.num_rowsets() != num_rowsets) {
2211
0
        ret = 1;
2212
        // clang-format off
2213
0
        LOG(WARNING) << " tablet_stats_pb's num_rowsets is not same with all rowset nums,"
2214
0
                        << " tablet_stats_pb's num_rowsets=" << tablet_stats_pb.num_rowsets()
2215
0
                        << " all rowset nums=" << num_rowsets
2216
0
                        << " stats tablet meta=" << tablet_stats_pb.ShortDebugString();
2217
        // clang-format on
2218
1
    } else if (tablet_stats_pb.num_segments() != num_segments) {
2219
0
        ret = 1;
2220
        // clang-format off
2221
0
        LOG(WARNING) << " tablet_stats_pb's num_segments is not same with all rowset total num_segments,"
2222
0
                        << " tablet_stats_pb's num_segments=" << tablet_stats_pb.num_segments()
2223
0
                        << " all rowset total num_segments=" << num_segments
2224
0
                        << " stats tablet meta=" << tablet_stats_pb.ShortDebugString();
2225
        // clang-format on
2226
0
    }
2227
2228
2
    return ret;
2229
2
}
2230
2231
int InstanceChecker::scan_and_handle_kv(
2232
        std::string& start_key, const std::string& end_key,
2233
12
        std::function<int(std::string_view, std::string_view)> handle_kv) {
2234
12
    std::unique_ptr<Transaction> txn;
2235
12
    int ret = 0;
2236
12
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2237
12
    if (err != TxnErrorCode::TXN_OK) {
2238
0
        LOG(WARNING) << "failed to init txn";
2239
0
        return -1;
2240
0
    }
2241
12
    std::unique_ptr<RangeGetIterator> it;
2242
12
    int limit = 10000;
2243
12
    TEST_SYNC_POINT_CALLBACK("InstanceChecker:scan_and_handle_kv:limit", &limit);
2244
25
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
2245
13
        err = txn->get(start_key, end_key, &it, false, limit);
2246
13
        TEST_SYNC_POINT_CALLBACK("InstanceChecker:scan_and_handle_kv:get_err", &err);
2247
13
        if (err == TxnErrorCode::TXN_TOO_OLD) {
2248
1
            LOG(WARNING) << "failed to get range kv, err=txn too old, "
2249
1
                         << " now fallback to non snapshot scan";
2250
1
            err = txn_kv_->create_txn(&txn);
2251
1
            if (err == TxnErrorCode::TXN_OK) {
2252
1
                err = txn->get(start_key, end_key, &it);
2253
1
            }
2254
1
        }
2255
13
        if (err != TxnErrorCode::TXN_OK) {
2256
0
            LOG(WARNING) << "internal error, failed to get range kv, err=" << err;
2257
0
            return -1;
2258
0
        }
2259
2260
229
        while (it->has_next() && !stopped()) {
2261
216
            auto [k, v] = it->next();
2262
2263
216
            int handle_ret = handle_kv(k, v);
2264
216
            if (handle_ret == -1) {
2265
0
                return -1;
2266
216
            } else {
2267
216
                ret = std::max(ret, handle_ret);
2268
216
            }
2269
216
            if (!it->has_next()) {
2270
13
                start_key = k;
2271
13
            }
2272
216
        }
2273
13
        start_key = it->next_begin_key();
2274
13
    }
2275
12
    return ret;
2276
12
}
2277
2278
2
int InstanceChecker::do_version_key_check() {
2279
2
    std::unique_ptr<RangeGetIterator> table_it;
2280
2
    std::string begin = table_version_key({instance_id_, 0, 0});
2281
2
    std::string end = table_version_key({instance_id_, INT64_MAX, 0});
2282
2
    bool check_res = true;
2283
4
    while (table_it == nullptr /* may be not init */ || (table_it->more() && !stopped())) {
2284
2
        std::unique_ptr<Transaction> txn;
2285
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2286
2
        if (err != TxnErrorCode::TXN_OK) {
2287
0
            LOG(WARNING) << "failed to create txn";
2288
0
            return -1;
2289
0
        }
2290
2
        err = txn->get(begin, end, &table_it);
2291
2
        if (err != TxnErrorCode::TXN_OK) {
2292
0
            LOG(WARNING) << "failed to get mow tablet job key, err=" << err;
2293
0
            return -1;
2294
0
        }
2295
4
        while (table_it->has_next() && !stopped()) {
2296
2
            auto [k, v] = table_it->next();
2297
2
            std::string_view k1 = k;
2298
2
            k1.remove_prefix(1);
2299
2
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2300
2
            decode_key(&k1, &out);
2301
2
            int64_t table_version = -1;
2302
            // 0x01 "version" ${instance_id} "table" ${db_id} ${tbl_id}
2303
2
            if (!txn->decode_atomic_int(v, &table_version)) {
2304
0
                LOG(WARNING) << "malformed table version value";
2305
0
                return -1;
2306
0
            }
2307
2
            auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2308
2
            auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2309
2
            std::string partition_version_key_begin =
2310
2
                    partition_version_key({instance_id_, db_id, table_id, 0});
2311
2
            std::string partition_version_key_end =
2312
2
                    partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2313
2
            VersionPB partition_version_pb;
2314
2315
2
            std::unique_ptr<RangeGetIterator> part_it;
2316
4
            while (part_it == nullptr /* may be not init */ || (part_it->more() && !stopped())) {
2317
2
                std::unique_ptr<Transaction> txn;
2318
2
                TxnErrorCode err = txn_kv_->create_txn(&txn);
2319
2
                if (err != TxnErrorCode::TXN_OK) {
2320
0
                    LOG(WARNING) << "failed to create txn";
2321
0
                    return -1;
2322
0
                }
2323
2
                err = txn->get(partition_version_key_begin, partition_version_key_end, &part_it);
2324
2
                if (err != TxnErrorCode::TXN_OK) {
2325
0
                    LOG(WARNING) << "failed to get mow tablet job key, err=" << err;
2326
0
                    return -1;
2327
0
                }
2328
13
                while (part_it->has_next() && !stopped()) {
2329
11
                    auto [k, v] = part_it->next();
2330
                    // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2331
11
                    std::string_view k1 = k;
2332
11
                    k1.remove_prefix(1);
2333
11
                    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2334
11
                    decode_key(&k1, &out);
2335
11
                    if (!partition_version_pb.ParseFromArray(v.data(), v.size())) [[unlikely]] {
2336
0
                        LOG(WARNING) << "failed to parse partition VersionPB";
2337
0
                        return -1;
2338
0
                    }
2339
11
                    auto partition_id = std::get<int64_t>(std::get<0>(out[5]));
2340
11
                    int64_t partition_version = partition_version_pb.version();
2341
11
                    if (table_version < partition_version) {
2342
3
                        check_res = false;
2343
3
                        LOG(WARNING)
2344
3
                                << "table version is less than partition version,"
2345
3
                                << " table_id: " << table_id << "tablet_version: " << table_version
2346
3
                                << " partition_id: " << partition_id
2347
3
                                << " partition_version: " << partition_version;
2348
3
                    }
2349
11
                }
2350
2
                partition_version_key_begin = part_it->next_begin_key();
2351
2
            }
2352
2
        }
2353
2
        begin = table_it->next_begin_key(); // Update to next smallest key for iteration
2354
2
    }
2355
2
    return check_res ? 0 : -1;
2356
2
}
2357
2358
1
int InstanceChecker::do_restore_job_check() {
2359
1
    int64_t num_prepared = 0;
2360
1
    int64_t num_committed = 0;
2361
1
    int64_t num_dropped = 0;
2362
1
    int64_t num_completed = 0;
2363
1
    int64_t num_recycling = 0;
2364
1
    int64_t num_cost_many_time = 0;
2365
1
    const int64_t COST_MANY_THRESHOLD = 3600;
2366
2367
1
    using namespace std::chrono;
2368
1
    auto start_time = steady_clock::now();
2369
1
    DORIS_CLOUD_DEFER {
2370
1
        g_bvar_checker_restore_job_prepared_state.put(instance_id_, num_prepared);
2371
1
        g_bvar_checker_restore_job_committed_state.put(instance_id_, num_committed);
2372
1
        g_bvar_checker_restore_job_dropped_state.put(instance_id_, num_dropped);
2373
1
        g_bvar_checker_restore_job_completed_state.put(instance_id_, num_completed);
2374
1
        g_bvar_checker_restore_job_recycling_state.put(instance_id_, num_recycling);
2375
1
        g_bvar_checker_restore_job_cost_many_time.put(instance_id_, num_cost_many_time);
2376
1
        auto cost_ms =
2377
1
                duration_cast<std::chrono::milliseconds>(steady_clock::now() - start_time).count();
2378
1
        LOG(INFO) << "check instance restore jobs finished, cost=" << cost_ms
2379
1
                  << "ms. instance_id=" << instance_id_ << " num_prepared=" << num_prepared
2380
1
                  << " num_committed=" << num_committed << " num_dropped=" << num_dropped
2381
1
                  << " num_completed=" << num_completed << " num_recycling=" << num_recycling
2382
1
                  << " num_cost_many_time=" << num_cost_many_time;
2383
1
    };
2384
2385
1
    LOG_INFO("begin to check restore jobs").tag("instance_id", instance_id_);
2386
2387
1
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
2388
1
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
2389
1
    std::string begin;
2390
1
    std::string end;
2391
1
    job_restore_tablet_key(restore_job_key_info0, &begin);
2392
1
    job_restore_tablet_key(restore_job_key_info1, &end);
2393
1
    std::unique_ptr<RangeGetIterator> it;
2394
2
    while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
2395
1
        std::unique_ptr<Transaction> txn;
2396
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2397
1
        if (err != TxnErrorCode::TXN_OK) {
2398
0
            LOG(WARNING) << "failed to create txn";
2399
0
            return -1;
2400
0
        }
2401
1
        err = txn->get(begin, end, &it);
2402
1
        if (err != TxnErrorCode::TXN_OK) {
2403
0
            LOG(WARNING) << "failed to get mow tablet job key, err=" << err;
2404
0
            return -1;
2405
0
        }
2406
2407
1
        if (!it->has_next()) {
2408
0
            break;
2409
0
        }
2410
3
        while (it->has_next()) {
2411
3
            auto [k, v] = it->next();
2412
3
            RestoreJobCloudPB restore_job_pb;
2413
3
            if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
2414
0
                LOG_WARNING("malformed restore job value").tag("key", hex(k));
2415
0
                return -1;
2416
0
            }
2417
2418
3
            switch (restore_job_pb.state()) {
2419
1
            case RestoreJobCloudPB::PREPARED:
2420
1
                ++num_prepared;
2421
1
                break;
2422
1
            case RestoreJobCloudPB::COMMITTED:
2423
1
                ++num_committed;
2424
1
                break;
2425
0
            case RestoreJobCloudPB::DROPPED:
2426
0
                ++num_dropped;
2427
0
                break;
2428
1
            case RestoreJobCloudPB::COMPLETED:
2429
1
                ++num_completed;
2430
1
                break;
2431
0
            case RestoreJobCloudPB::RECYCLING:
2432
0
                ++num_recycling;
2433
0
                break;
2434
0
            default:
2435
0
                break;
2436
3
            }
2437
2438
3
            int64_t current_time = ::time(nullptr);
2439
3
            if ((restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
2440
3
                 restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) &&
2441
3
                current_time > restore_job_pb.ctime_s() + COST_MANY_THRESHOLD) {
2442
                // restore job run more than 1 hour
2443
1
                ++num_cost_many_time;
2444
1
                LOG_WARNING("restore job cost too many time")
2445
1
                        .tag("key", hex(k))
2446
1
                        .tag("tablet_id", restore_job_pb.tablet_id())
2447
1
                        .tag("state", restore_job_pb.state())
2448
1
                        .tag("ctime_s", restore_job_pb.ctime_s())
2449
1
                        .tag("mtime_s", restore_job_pb.mtime_s());
2450
1
            }
2451
2452
3
            if (!it->has_next()) {
2453
1
                begin = k;
2454
1
                begin.push_back('\x00'); // Update to next smallest key for iteration
2455
1
                break;
2456
1
            }
2457
3
        }
2458
1
    }
2459
1
    return 0;
2460
1
}
2461
2462
3
int InstanceChecker::check_txn_info_key(std::string_view key, std::string_view value) {
2463
3
    std::unordered_map<int64_t, std::string> txn_info_;
2464
3
    TxnLabelPB txn_label_pb;
2465
2466
6
    auto handle_check_txn_label_key = [&](std::string_view key, std::string_view value) -> int {
2467
6
        TxnInfoPB txn_info_pb;
2468
6
        std::string_view k1 = key;
2469
6
        k1.remove_prefix(1);
2470
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2471
6
        decode_key(&k1, &out);
2472
        // 0x01 "txn" ${instance_id} "txn_info" ${db_id} ${txn_id}
2473
6
        if (!txn_info_pb.ParseFromArray(value.data(), value.size())) {
2474
0
            LOG(WARNING) << "failed to parse TxnInfoPB";
2475
0
            return -1;
2476
0
        }
2477
6
        auto txn_id = std::get<int64_t>(std::get<0>(out[4]));
2478
6
        auto it = txn_info_.find(txn_id);
2479
6
        if (it == txn_info_.end()) {
2480
0
            return 0;
2481
6
        } else {
2482
6
            if (it->second != txn_info_pb.label()) {
2483
1
                LOG(WARNING) << "txn_info_pb's txn_label not same with txn_label_pb's txn_label,"
2484
1
                             << " txn_info_pb's txn_label: " << txn_info_pb.label()
2485
1
                             << " txn_label_pb meta: " << txn_label_pb.ShortDebugString();
2486
1
                return 1;
2487
1
            }
2488
6
        }
2489
5
        return 0;
2490
6
    };
2491
3
    std::string_view k1 = key;
2492
3
    k1.remove_prefix(1);
2493
3
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2494
3
    decode_key(&k1, &out);
2495
    // 0x01 "txn" ${instance_id} "txn_label" ${db_id} ${label}
2496
3
    if (!txn_label_pb.ParseFromArray(value.data(), value.size() - VERSION_STAMP_LEN)) {
2497
1
        LOG(WARNING) << "failed to parse TxnLabelPB";
2498
1
        return -1;
2499
1
    }
2500
2
    auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2501
2
    auto label = std::get<std::string>(std::get<0>(out[4]));
2502
    // txn_id -> txn_label
2503
6
    for (const auto& txn_id : txn_label_pb.txn_ids()) {
2504
6
        txn_info_.insert({txn_id, label});
2505
6
    }
2506
2
    std::string txn_info_key_begin = txn_info_key({instance_id_, db_id, 0});
2507
2
    std::string txn_info_key_end = txn_info_key({instance_id_, db_id, INT64_MAX});
2508
2
    return scan_and_handle_kv(txn_info_key_begin, txn_info_key_end,
2509
6
                              [&](std::string_view k, std::string_view v) -> int {
2510
6
                                  return handle_check_txn_label_key(k, v);
2511
6
                              });
2512
3
}
2513
2514
6
int InstanceChecker::check_txn_label_key(std::string_view key, std::string_view value) {
2515
6
    TxnInfoPB txn_info_pb;
2516
6
    std::string_view k1 = key;
2517
6
    k1.remove_prefix(1);
2518
6
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2519
6
    decode_key(&k1, &out);
2520
    // 0x01 "txn" ${instance_id} "txn_info" ${db_id} ${txn_id}
2521
6
    if (!txn_info_pb.ParseFromArray(value.data(), value.size())) {
2522
1
        LOG(WARNING) << "failed to parse TxnInfoPB";
2523
1
        return -1;
2524
1
    }
2525
5
    auto txn_id = std::get<int64_t>(std::get<0>(out[4]));
2526
5
    auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2527
5
    auto label = txn_info_pb.label();
2528
5
    std::string txn_label = txn_label_key({instance_id_, db_id, label});
2529
5
    std::string txn_label_val;
2530
5
    TxnLabelPB txn_label_pb;
2531
5
    std::unique_ptr<Transaction> txn;
2532
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2533
5
    if (err != TxnErrorCode::TXN_OK) {
2534
0
        LOG(WARNING) << "failed to init txn";
2535
0
        return -1;
2536
0
    }
2537
5
    if (txn->get(txn_label, &txn_label_val) != TxnErrorCode::TXN_OK) {
2538
1
        LOG(WARNING) << "failed to get txn label key, key=" << hex(txn_label);
2539
1
        return -1;
2540
1
    }
2541
4
    txn_label_pb.ParseFromString(txn_label_val);
2542
4
    auto txn_ids = txn_label_pb.txn_ids();
2543
4
    if (!std::count(txn_ids.begin(), txn_ids.end(), txn_id)) {
2544
        // clang-format off txn_info_pb
2545
1
        LOG(WARNING) << "txn_info_pb's txn_id not found in txn_label_pb info,"
2546
1
                     << " txn_id: " << txn_id
2547
1
                     << " txn_label_pb meta: " << txn_label_pb.ShortDebugString();
2548
        // clang-format on
2549
1
        return 1;
2550
1
    }
2551
3
    return 0;
2552
4
}
2553
2554
4
int InstanceChecker::check_txn_index_key(std::string_view key, std::string_view value) {
2555
4
    TxnInfoPB txn_info_pb;
2556
4
    std::string_view k1 = key;
2557
4
    k1.remove_prefix(1);
2558
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2559
4
    decode_key(&k1, &out);
2560
    // 0x01 "txn" ${instance_id} "txn_info" ${db_id} ${txn_id}
2561
4
    if (!txn_info_pb.ParseFromArray(value.data(), value.size())) {
2562
1
        LOG(WARNING) << "failed to parse TxnInfoPB";
2563
1
        return -1;
2564
1
    }
2565
3
    auto txn_id = std::get<int64_t>(std::get<0>(out[4]));
2566
3
    auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2567
    /// get tablet id
2568
3
    std::string txn_index = txn_index_key({instance_id_, txn_id});
2569
3
    std::string txn_index_val;
2570
3
    TxnIndexPB txn_index_pb;
2571
3
    std::unique_ptr<Transaction> txn;
2572
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2573
3
    if (err != TxnErrorCode::TXN_OK) {
2574
0
        LOG(WARNING) << "failed to init txn";
2575
0
        return -1;
2576
0
    }
2577
3
    if (txn->get(txn_index, &txn_index_val) != TxnErrorCode::TXN_OK) {
2578
1
        LOG(WARNING) << "failed to get txn label key, key=" << hex(txn_index);
2579
1
        return -1;
2580
1
    }
2581
2
    txn_index_pb.ParseFromString(txn_index_val);
2582
2
    if (txn_index_pb.tablet_index().db_id() != db_id) {
2583
        // clang-format off txn_info_pb
2584
1
        LOG(WARNING) << "txn_index_pb's db_id not same with txn_info_pb's db_id,"
2585
1
                     << " txn_index_pb meta: " << txn_index_pb.ShortDebugString()
2586
1
                     << " txn_info_pb meta: " << txn_info_pb.ShortDebugString();
2587
        // clang-format on
2588
1
        return 1;
2589
1
    }
2590
1
    return 0;
2591
2
}
2592
2593
3
int InstanceChecker::check_txn_running_key(std::string_view key, std::string_view value) {
2594
3
    TxnRunningPB txn_running_pb;
2595
3
    int64_t current_time =
2596
3
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
2597
3
    if (!txn_running_pb.ParseFromArray(value.data(), value.size())) {
2598
1
        LOG(WARNING) << "failed to parse TxnRunningPB";
2599
1
        return -1;
2600
1
    }
2601
2
    if (txn_running_pb.timeout_time() <= current_time) {
2602
1
        LOG(WARNING) << "txn_running_pb.timeout_time() is less than current_time,"
2603
1
                     << " but txn_running_key exists, "
2604
1
                     << " txn_running_pb meta: " << txn_running_pb.ShortDebugString();
2605
1
        return 1;
2606
1
    }
2607
1
    return 0;
2608
2
}
2609
2610
0
int InstanceChecker::do_txn_key_check() {
2611
0
    int ret = 0;
2612
2613
    // check txn info key depend on txn label key
2614
0
    std::string begin = txn_label_key({instance_id_, 0, ""});
2615
0
    std::string end = txn_label_key({instance_id_, INT64_MAX, ""});
2616
0
    int64_t num_scanned = 0;
2617
0
    int64_t num_abnormal = 0;
2618
0
    LOG(INFO) << "begin check txn_label_key and txn_info_key";
2619
0
    ret = scan_and_handle_kv(begin, end, [&, this](std::string_view k, std::string_view v) -> int {
2620
0
        num_scanned++;
2621
0
        int ret = check_txn_info_key(k, v);
2622
0
        if (ret == 1) {
2623
0
            num_abnormal++;
2624
0
        }
2625
0
        return ret;
2626
0
    });
2627
2628
0
    if (ret == 1) {
2629
0
        LOG(WARNING) << "failed to check txn_info_key depending on txn_label_key, num_scanned="
2630
0
                     << num_scanned << ", num_abnormal=" << num_abnormal;
2631
0
        return 1;
2632
0
    } else if (ret == -1) {
2633
0
        LOG(WARNING) << "failed to check txn label key and txn info key";
2634
0
        return -1;
2635
0
    }
2636
2637
    // check txn label key depend on txn info key
2638
0
    begin = txn_info_key({instance_id_, 0, 0});
2639
0
    end = txn_info_key({instance_id_, INT64_MAX, 0});
2640
0
    num_scanned = 0;
2641
0
    num_abnormal = 0;
2642
0
    LOG(INFO) << "begin check txn_label_key and txn_info_key";
2643
0
    ret = scan_and_handle_kv(begin, end, [&, this](std::string_view k, std::string_view v) -> int {
2644
0
        num_scanned++;
2645
0
        int ret = check_txn_label_key(k, v);
2646
0
        if (ret == 1) {
2647
0
            num_abnormal++;
2648
0
        }
2649
0
        return ret;
2650
0
    });
2651
0
    if (ret == 1) {
2652
0
        LOG(WARNING) << "failed to check txn_label_key depending on txn_info_key, num_scanned="
2653
0
                     << num_scanned << ", num_abnormal=" << num_abnormal;
2654
0
        return 1;
2655
0
    } else if (ret == -1) {
2656
0
        LOG(WARNING) << "failed to inverted check txn label key and txn info key";
2657
0
        return -1;
2658
0
    }
2659
0
    LOG(INFO) << "finish check txn_label_key and txn_info_key, num_scanned=" << num_scanned
2660
0
              << ", num_abnormal=" << num_abnormal;
2661
2662
    // check txn index key depend on txn info key
2663
0
    begin = txn_info_key({instance_id_, 0, 0});
2664
0
    end = txn_info_key({instance_id_, INT64_MAX, 0});
2665
0
    num_scanned = 0;
2666
0
    num_abnormal = 0;
2667
0
    LOG(INFO) << "begin check txn_index_key and txn_info_key";
2668
0
    ret = scan_and_handle_kv(begin, end, [&, this](std::string_view k, std::string_view v) -> int {
2669
0
        num_scanned++;
2670
0
        int ret = check_txn_index_key(k, v);
2671
0
        if (ret == 1) {
2672
0
            num_abnormal++;
2673
0
        }
2674
0
        return ret;
2675
0
    });
2676
0
    if (ret == 1) {
2677
0
        LOG(WARNING) << "failed to check txn_idx_key depending on txn_info_key, num_scanned="
2678
0
                     << num_scanned << ", num_abnormal=" << num_abnormal;
2679
0
        return 1;
2680
0
    } else if (ret == -1) {
2681
0
        LOG(WARNING) << "failed to check txn index key";
2682
0
        return -1;
2683
0
    }
2684
0
    LOG(INFO) << "finish check txn_index_key and txn_info_key, num_scanned=" << num_scanned
2685
0
              << ", num_abnormal=" << num_abnormal;
2686
2687
    // check txn running key
2688
0
    begin = txn_running_key({instance_id_, 0, 0});
2689
0
    end = txn_running_key({instance_id_, INT64_MAX, 0});
2690
0
    num_scanned = 0;
2691
0
    num_abnormal = 0;
2692
0
    LOG(INFO) << "begin check txn_running_key";
2693
0
    ret = scan_and_handle_kv(begin, end, [&, this](std::string_view k, std::string_view v) -> int {
2694
0
        num_scanned++;
2695
0
        int ret = check_txn_running_key(k, v);
2696
0
        if (ret == 1) {
2697
0
            num_abnormal++;
2698
0
        }
2699
0
        return ret;
2700
0
    });
2701
0
    if (ret == 1) {
2702
0
        LOG(WARNING) << "failed to check txn_running_key, num_scanned=" << num_scanned
2703
0
                     << ", num_abnormal=" << num_abnormal;
2704
0
        return 1;
2705
0
    } else if (ret == -1) {
2706
0
        LOG(WARNING) << "failed to check txn running key";
2707
0
        return -1;
2708
0
    }
2709
0
    LOG(INFO) << "finish check txn_running_key, num_scanned=" << num_scanned
2710
0
              << ", num_abnormal=" << num_abnormal;
2711
0
    return 0;
2712
0
}
2713
2714
2
int InstanceChecker::check_meta_tmp_rowset_key(std::string_view key, std::string_view value) {
2715
2
    TxnInfoPB txn_info_pb;
2716
2
    std::string_view k1 = key;
2717
2
    k1.remove_prefix(1);
2718
2
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2719
2
    decode_key(&k1, &out);
2720
    // 0x01 "txn" ${instance_id} "txn_info" ${db_id} ${txn_id}
2721
2
    if (!txn_info_pb.ParseFromArray(value.data(), value.size())) {
2722
0
        LOG(WARNING) << "failed to parse TxnInfoPB";
2723
0
        return -1;
2724
0
    }
2725
    /// get tablet id
2726
2
    auto txn_id = std::get<int64_t>(std::get<0>(out[4]));
2727
2
    std::string txn_index = txn_index_key({instance_id_, txn_id});
2728
2
    std::string txn_index_val;
2729
2
    TxnIndexPB txn_index_pb;
2730
2
    std::unique_ptr<Transaction> txn;
2731
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2732
2
    if (err != TxnErrorCode::TXN_OK) {
2733
0
        LOG(WARNING) << "failed to init txn";
2734
0
        return -1;
2735
0
    }
2736
2
    if (txn->get(txn_index, &txn_index_val) != TxnErrorCode::TXN_OK) {
2737
0
        LOG(WARNING) << "failed to get txn index key, key=" << txn_index;
2738
0
        return -1;
2739
0
    }
2740
2
    txn_index_pb.ParseFromString(txn_index_val);
2741
2
    auto tablet_id = txn_index_pb.tablet_index().tablet_id();
2742
2
    std::string meta_tmp_rowset_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
2743
2
    int is_key_exist = key_exist(txn_kv_.get(), meta_tmp_rowset_key);
2744
2
    if (is_key_exist == 1) {
2745
0
        if (txn_info_pb.status() != TxnStatusPB::TXN_STATUS_VISIBLE) {
2746
            // clang-format off
2747
0
            LOG(INFO) << "meta tmp rowset key not exist but txn status != TXN_STATUS_VISIBLE"
2748
0
                        << "meta tmp rowset key=" << meta_tmp_rowset_key
2749
0
                        << "txn_info=" << txn_info_pb.ShortDebugString();
2750
            // clang-format on
2751
0
            return 1;
2752
0
        }
2753
2
    } else if (is_key_exist == 0) {
2754
2
        if (txn_info_pb.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2755
            // clang-format off
2756
1
            LOG(INFO) << "meta tmp rowset key exist but txn status != TXN_STATUS_PREPARED"
2757
1
                        << "meta tmp rowset key=" << meta_tmp_rowset_key
2758
1
                        << "txn_info=" << txn_info_pb.ShortDebugString();
2759
            // clang-format on
2760
1
            return 1;
2761
1
        }
2762
2
    } else {
2763
0
        LOG(WARNING) << "failed to get key, key=" << meta_tmp_rowset_key;
2764
0
        return -1;
2765
0
    }
2766
1
    return 0;
2767
2
}
2768
2769
2
int InstanceChecker::check_meta_rowset_key(std::string_view key, std::string_view value) {
2770
2
    RowsetMetaCloudPB meta_rowset_pb;
2771
2
    if (!meta_rowset_pb.ParseFromArray(value.data(), value.size())) {
2772
0
        LOG(WARNING) << "failed to parse RowsetMetaCloudPB";
2773
0
        return -1;
2774
0
    }
2775
2
    std::string tablet_index_key = meta_tablet_idx_key({instance_id_, meta_rowset_pb.tablet_id()});
2776
2
    if (key_exist(txn_kv_.get(), tablet_index_key) == 1) {
2777
1
        LOG(WARNING) << "rowset's tablet id not found in fdb"
2778
1
                     << "tablet_index_key: " << tablet_index_key
2779
1
                     << "rowset meta: " << meta_rowset_pb.ShortDebugString();
2780
1
        return 1;
2781
1
    }
2782
1
    return 0;
2783
2
}
2784
2785
0
int InstanceChecker::do_meta_rowset_key_check() {
2786
0
    int ret = 0;
2787
2788
0
    std::string begin = meta_rowset_key({instance_id_, 0, 0});
2789
0
    std::string end = meta_rowset_key({instance_id_, INT64_MAX, 0});
2790
0
    int64_t num_scanned = 0;
2791
0
    int64_t num_loss = 0;
2792
2793
0
    ret = scan_and_handle_kv(begin, end, [&](std::string_view k, std::string_view v) {
2794
0
        num_scanned++;
2795
0
        int ret = check_meta_rowset_key(k, v);
2796
0
        if (ret == 1) {
2797
0
            num_loss++;
2798
0
        }
2799
0
        return ret;
2800
0
    });
2801
0
    if (ret == -1) {
2802
0
        LOG(WARNING) << "failed to check meta rowset key,";
2803
0
        return -1;
2804
0
    } else if (ret == 1) {
2805
0
        LOG(WARNING) << "meta rowset key may be loss, num_scanned=" << num_scanned
2806
0
                     << ", num_loss=" << num_loss;
2807
0
    }
2808
0
    LOG(INFO) << "meta rowset key check finish, num_scanned=" << num_scanned
2809
0
              << ", num_loss=" << num_loss;
2810
2811
0
    begin = txn_info_key({instance_id_, 0, 0});
2812
0
    end = txn_info_key({instance_id_, INT64_MAX, 0});
2813
0
    num_scanned = 0;
2814
0
    num_loss = 0;
2815
2816
0
    ret = scan_and_handle_kv(begin, end, [&](std::string_view k, std::string_view v) {
2817
0
        num_scanned++;
2818
0
        int ret = check_meta_tmp_rowset_key(k, v);
2819
0
        if (ret == 1) {
2820
0
            num_loss++;
2821
0
        }
2822
0
        return ret;
2823
0
    });
2824
0
    if (ret == -1) {
2825
0
        LOG(WARNING) << "failed to check tmp meta rowset key";
2826
0
        return -1;
2827
0
    } else if (ret == 1) {
2828
0
        LOG(WARNING) << "meta tmp rowset key may be loss, num_scanned=" << num_scanned
2829
0
                     << ", num_loss=" << num_loss;
2830
0
    }
2831
0
    LOG(INFO) << "meta tmp rowset key check finish, num_scanned=" << num_scanned
2832
0
              << ", num_loss=" << num_loss;
2833
2834
0
    return ret;
2835
0
}
2836
2837
0
StorageVaultAccessor* InstanceChecker::get_accessor(const std::string& id) {
2838
0
    auto it = accessor_map_.find(id);
2839
0
    if (it == accessor_map_.end()) {
2840
0
        return nullptr;
2841
0
    }
2842
0
    return it->second.get();
2843
0
}
2844
2845
0
void InstanceChecker::get_all_accessor(std::vector<StorageVaultAccessor*>* accessors) {
2846
0
    for (const auto& [_, accessor] : accessor_map_) {
2847
0
        accessors->push_back(accessor.get());
2848
0
    }
2849
0
}
2850
2851
0
int InstanceChecker::do_packed_file_check() {
2852
0
    LOG(INFO) << "begin to check packed files, instance_id=" << instance_id_;
2853
0
    int check_ret = 0;
2854
0
    long num_scanned_rowsets = 0;
2855
0
    long num_scanned_packed_files = 0;
2856
0
    long num_packed_file_loss = 0;
2857
0
    long num_packed_file_leak = 0;
2858
0
    long num_ref_count_mismatch = 0;
2859
0
    long num_small_file_ref_mismatch = 0;
2860
0
    using namespace std::chrono;
2861
0
    auto start_time = steady_clock::now();
2862
0
    DORIS_CLOUD_DEFER {
2863
0
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2864
0
        LOG(INFO) << "check packed files finished, cost=" << cost
2865
0
                  << "s. instance_id=" << instance_id_
2866
0
                  << " num_scanned_rowsets=" << num_scanned_rowsets
2867
0
                  << " num_scanned_packed_files=" << num_scanned_packed_files
2868
0
                  << " num_packed_file_loss=" << num_packed_file_loss
2869
0
                  << " num_packed_file_leak=" << num_packed_file_leak
2870
0
                  << " num_ref_count_mismatch=" << num_ref_count_mismatch
2871
0
                  << " num_small_file_ref_mismatch=" << num_small_file_ref_mismatch;
2872
0
    };
2873
2874
    // Map to track expected reference count for each packed file
2875
    // packed_file_path -> expected_ref_count (from rowset metas)
2876
0
    std::unordered_map<std::string, int64_t> expected_ref_counts;
2877
    // Map to track small files referenced in packed files
2878
    // packed_file_path -> set of small_file_paths
2879
0
    std::unordered_map<std::string, std::unordered_set<std::string>> packed_file_small_files;
2880
2881
    // Step 1: Scan all rowset metas to collect packed_slice_locations references
2882
    // Use efficient range scan instead of iterating through each tablet_id
2883
0
    auto collect_packed_refs = [&](const doris::RowsetMetaCloudPB& rs_meta) {
2884
0
        const auto& index_map = rs_meta.packed_slice_locations();
2885
0
        for (const auto& [small_file_path, index_pb] : index_map) {
2886
0
            if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
2887
0
                continue;
2888
0
            }
2889
0
            const std::string& packed_file_path = index_pb.packed_file_path();
2890
0
            expected_ref_counts[packed_file_path]++;
2891
0
            packed_file_small_files[packed_file_path].insert(small_file_path);
2892
0
        }
2893
0
    };
2894
2895
0
    {
2896
0
        std::string start_key = meta_rowset_key({instance_id_, 0, 0});
2897
0
        std::string end_key = meta_rowset_key({instance_id_, INT64_MAX, 0});
2898
2899
0
        std::unique_ptr<RangeGetIterator> it;
2900
0
        while (it == nullptr /* may be not init */ || (it->more() && !stopped())) {
2901
0
            if (stopped()) {
2902
0
                return -1;
2903
0
            }
2904
2905
0
            std::unique_ptr<Transaction> txn;
2906
0
            TxnErrorCode err = txn_kv_->create_txn(&txn);
2907
0
            if (err != TxnErrorCode::TXN_OK) {
2908
0
                LOG(WARNING) << "failed to create txn for packed file check";
2909
0
                return -1;
2910
0
            }
2911
2912
0
            err = txn->get(start_key, end_key, &it);
2913
0
            if (err != TxnErrorCode::TXN_OK) {
2914
0
                LOG(WARNING) << "failed to scan rowset metas, err=" << err;
2915
0
                check_ret = -1;
2916
0
                break;
2917
0
            }
2918
2919
0
            while (it->has_next() && !stopped()) {
2920
0
                auto [k, v] = it->next();
2921
0
                if (!it->has_next()) {
2922
0
                    start_key = k;
2923
0
                }
2924
2925
0
                doris::RowsetMetaCloudPB rs_meta;
2926
0
                if (!rs_meta.ParseFromArray(v.data(), v.size())) {
2927
0
                    LOG(WARNING) << "malformed rowset meta, key=" << hex(k);
2928
0
                    check_ret = -1;
2929
0
                    continue;
2930
0
                }
2931
2932
0
                num_scanned_rowsets++;
2933
2934
0
                collect_packed_refs(rs_meta);
2935
0
            }
2936
0
            start_key.push_back('\x00'); // Update to next smallest key for iteration
2937
0
        }
2938
0
    }
2939
2940
    // Rowsets in recycle keys may still hold packed file references while ref count
2941
    // updates are pending, so include them when calculating expected references.
2942
0
    {
2943
0
        std::string start_key = recycle_rowset_key({instance_id_, 0, ""});
2944
0
        std::string end_key = recycle_rowset_key({instance_id_, INT64_MAX, "\xff"});
2945
2946
0
        std::unique_ptr<RangeGetIterator> it;
2947
0
        while (it == nullptr /* may be not init */ || it->more()) {
2948
0
            if (stopped()) {
2949
0
                return -1;
2950
0
            }
2951
0
            std::unique_ptr<Transaction> txn;
2952
0
            TxnErrorCode err = txn_kv_->create_txn(&txn);
2953
0
            if (err != TxnErrorCode::TXN_OK) {
2954
0
                LOG(WARNING) << "failed to create txn for recycle rowset scan in packed file check";
2955
0
                return -1;
2956
0
            }
2957
2958
0
            err = txn->get(start_key, end_key, &it);
2959
0
            if (err != TxnErrorCode::TXN_OK) {
2960
0
                LOG(WARNING) << "failed to scan recycle rowset metas, err=" << err;
2961
0
                check_ret = -1;
2962
0
                break;
2963
0
            }
2964
2965
0
            while (it->has_next() && !stopped()) {
2966
0
                auto [k, v] = it->next();
2967
0
                if (!it->has_next()) {
2968
0
                    start_key = k;
2969
0
                }
2970
2971
0
                RecycleRowsetPB recycle_rowset;
2972
0
                if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
2973
0
                    LOG(WARNING) << "malformed recycle rowset, key=" << hex(k);
2974
0
                    check_ret = -1;
2975
0
                    continue;
2976
0
                }
2977
2978
0
                if (!recycle_rowset.has_rowset_meta()) {
2979
0
                    continue;
2980
0
                }
2981
2982
0
                num_scanned_rowsets++;
2983
0
                collect_packed_refs(recycle_rowset.rowset_meta());
2984
0
            }
2985
0
            start_key.push_back('\x00'); // Update to next smallest key for iteration
2986
0
        }
2987
0
    }
2988
2989
    // Step 2: Scan all packed file metadata and verify
2990
    // Also collect all packed file paths from metadata for Step 3
2991
    // Map: resource_id -> set of packed_file_paths
2992
0
    std::unordered_map<std::string, std::unordered_set<std::string>> packed_files_in_metadata;
2993
0
    std::string begin = packed_file_key({instance_id_, ""});
2994
0
    std::string end = packed_file_key({instance_id_, "\xff"});
2995
0
    std::string scan_begin = begin;
2996
2997
0
    while (true) {
2998
0
        if (stopped()) {
2999
0
            return -1;
3000
0
        }
3001
3002
0
        std::unique_ptr<Transaction> txn;
3003
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
3004
0
        if (err != TxnErrorCode::TXN_OK) {
3005
0
            LOG(WARNING) << "failed to create txn for scanning packed files";
3006
0
            return -1;
3007
0
        }
3008
3009
0
        std::unique_ptr<RangeGetIterator> it;
3010
0
        err = txn->get(scan_begin, end, &it);
3011
0
        if (err != TxnErrorCode::TXN_OK) {
3012
0
            LOG(WARNING) << "failed to scan packed file keys, err=" << err;
3013
0
            return -1;
3014
0
        }
3015
0
        if (!it->has_next()) {
3016
0
            break;
3017
0
        }
3018
3019
0
        std::string last_key;
3020
0
        while (it->has_next()) {
3021
0
            auto [k, v] = it->next();
3022
0
            last_key.assign(k.data(), k.size());
3023
0
            num_scanned_packed_files++;
3024
3025
0
            std::string packed_file_path;
3026
0
            if (!InstanceRecycler::decode_packed_file_key(k, &packed_file_path)) {
3027
0
                LOG(WARNING) << "failed to decode packed file key, key=" << hex(k);
3028
0
                check_ret = -1;
3029
0
                continue;
3030
0
            }
3031
3032
0
            cloud::PackedFileInfoPB packed_info;
3033
0
            if (!packed_info.ParseFromArray(v.data(), v.size())) {
3034
0
                LOG(WARNING) << "failed to parse packed file info, packed_file_path="
3035
0
                             << packed_file_path;
3036
0
                check_ret = -1;
3037
0
                continue;
3038
0
            }
3039
3040
            // Step 2.1: Verify packed file exists in storage
3041
0
            if (!packed_info.resource_id().empty()) {
3042
                // Collect packed file path for Step 3
3043
0
                packed_files_in_metadata[packed_info.resource_id()].insert(packed_file_path);
3044
3045
0
                auto* accessor = get_accessor(packed_info.resource_id());
3046
0
                if (accessor == nullptr) {
3047
0
                    LOG(WARNING) << "accessor not found for packed file, resource_id="
3048
0
                                 << packed_info.resource_id()
3049
0
                                 << ", packed_file_path=" << packed_file_path;
3050
0
                    check_ret = -1;
3051
0
                    continue;
3052
0
                }
3053
3054
0
                int ret = accessor->exists(packed_file_path);
3055
0
                if (ret < 0) {
3056
0
                    LOG(WARNING) << "failed to check packed file existence, packed_file_path="
3057
0
                                 << packed_file_path << ", ret=" << ret;
3058
0
                    check_ret = -1;
3059
0
                    continue;
3060
0
                }
3061
3062
0
                if (ret != 0) {
3063
                    // ret == 1 means file not found, ret > 1 means other error
3064
                    // When packed file doesn't exist in storage, ref_cnt must be 0 and state must be RECYCLING
3065
0
                    bool ref_cnt_valid = (packed_info.ref_cnt() == 0);
3066
0
                    bool state_valid = (packed_info.state() == cloud::PackedFileInfoPB::RECYCLING);
3067
0
                    if (!ref_cnt_valid || !state_valid) {
3068
0
                        LOG(WARNING) << "packed file not found in storage but metadata is invalid, "
3069
0
                                        "packed_file_path="
3070
0
                                     << packed_file_path << ", ref_cnt=" << packed_info.ref_cnt()
3071
0
                                     << " (expected=0), state=" << packed_info.state()
3072
0
                                     << " (expected=RECYCLING), ret=" << ret;
3073
0
                        num_packed_file_loss++;
3074
0
                        check_ret = 1; // Data inconsistency identified
3075
0
                    }
3076
                    // If ref_cnt == 0 and state == RECYCLING, this is expected (file is being recycled)
3077
0
                }
3078
                // ret == 0 means file exists, which is expected
3079
0
            }
3080
3081
            // Step 2.2: Verify reference count matches expected count
3082
0
            int64_t expected_ref = expected_ref_counts[packed_file_path];
3083
0
            if (packed_info.ref_cnt() != expected_ref) {
3084
0
                LOG(WARNING) << "packed file ref count mismatch, packed_file_path="
3085
0
                             << packed_file_path << ", expected=" << expected_ref
3086
0
                             << ", actual=" << packed_info.ref_cnt();
3087
0
                num_ref_count_mismatch++;
3088
0
                check_ret = 1; // Data inconsistency identified
3089
0
            }
3090
3091
            // Step 2.3: Verify small files in packed_info match rowset references
3092
0
            std::unordered_set<std::string> small_files_in_meta;
3093
0
            for (const auto& small_file : packed_info.slices()) {
3094
0
                if (!small_file.deleted()) {
3095
0
                    small_files_in_meta.insert(small_file.path());
3096
0
                }
3097
0
            }
3098
3099
0
            const auto& expected_small_files = packed_file_small_files[packed_file_path];
3100
0
            if (small_files_in_meta != expected_small_files) {
3101
                // Check for missing small files
3102
0
                for (const auto& expected_path : expected_small_files) {
3103
0
                    if (small_files_in_meta.find(expected_path) == small_files_in_meta.end()) {
3104
0
                        LOG(WARNING) << "small file missing in packed file info, packed_file_path="
3105
0
                                     << packed_file_path << ", small_file_path=" << expected_path;
3106
0
                        num_small_file_ref_mismatch++;
3107
0
                        check_ret = 1;
3108
0
                    }
3109
0
                }
3110
                // Check for extra small files (may be deleted, so less critical)
3111
0
                for (const auto& meta_path : small_files_in_meta) {
3112
0
                    if (expected_small_files.find(meta_path) == expected_small_files.end()) {
3113
0
                        LOG(INFO) << "small file in packed file info not found in rowset metas, "
3114
0
                                     "may be deleted, packed_file_path="
3115
0
                                  << packed_file_path << ", small_file_path=" << meta_path;
3116
0
                    }
3117
0
                }
3118
0
            }
3119
0
        }
3120
3121
0
        if (!it->more()) {
3122
0
            break;
3123
0
        }
3124
0
        scan_begin = last_key;
3125
0
        scan_begin.push_back('\x00');
3126
0
    }
3127
3128
    // Step 3: Check for leaked packed files (exist in storage but not in metadata)
3129
    // Scan all storage vaults to find packed files and verify they are in metadata
3130
0
    {
3131
0
        std::vector<StorageVaultAccessor*> accessors;
3132
0
        get_all_accessor(&accessors);
3133
3134
0
        for (StorageVaultAccessor* accessor : accessors) {
3135
0
            if (stopped()) {
3136
0
                return -1;
3137
0
            }
3138
3139
            // Find resource_id for this accessor
3140
0
            std::string resource_id;
3141
0
            for (const auto& [id, acc] : accessor_map_) {
3142
0
                if (acc.get() == accessor) {
3143
0
                    resource_id = id;
3144
0
                    break;
3145
0
                }
3146
0
            }
3147
3148
0
            if (resource_id.empty()) {
3149
0
                continue;
3150
0
            }
3151
3152
            // List all files under data/packed_file/ directory
3153
0
            std::unique_ptr<ListIterator> list_it;
3154
0
            int ret = accessor->list_directory("data/packed_file", &list_it);
3155
0
            if (ret != 0) {
3156
                // Directory may not exist, which is fine
3157
0
                if (ret < 0) {
3158
0
                    LOG(WARNING) << "failed to list packed_file directory, resource_id="
3159
0
                                 << resource_id << ", ret=" << ret;
3160
0
                    check_ret = -1;
3161
0
                }
3162
0
                continue;
3163
0
            }
3164
3165
0
            const auto& expected_packed_files = packed_files_in_metadata[resource_id];
3166
0
            while (list_it->has_next()) {
3167
0
                if (stopped()) {
3168
0
                    return -1;
3169
0
                }
3170
3171
0
                auto file_meta = list_it->next();
3172
0
                if (!file_meta.has_value()) {
3173
0
                    break;
3174
0
                }
3175
3176
0
                const std::string& file_path = file_meta->path;
3177
                // Only check files (not directories), and ensure it's a packed file
3178
                // Skip directories (paths ending with '/') and non-packed-file paths
3179
0
                if (file_path.empty() || file_path.back() == '/' ||
3180
0
                    !file_path.starts_with("data/packed_file/")) {
3181
0
                    continue;
3182
0
                }
3183
3184
                // Check if this packed file is in metadata
3185
0
                if (expected_packed_files.find(file_path) == expected_packed_files.end()) {
3186
0
                    LOG(WARNING) << "packed file found in storage but not in metadata, "
3187
0
                                    "resource_id="
3188
0
                                 << resource_id << ", packed_file_path=" << file_path;
3189
0
                    num_packed_file_leak++;
3190
0
                    check_ret = 1; // Data leak identified
3191
0
                }
3192
0
            }
3193
0
        }
3194
0
    }
3195
3196
0
    if (num_packed_file_loss > 0 || num_packed_file_leak > 0 || num_ref_count_mismatch > 0 ||
3197
0
        num_small_file_ref_mismatch > 0) {
3198
0
        return 1; // Data loss or inconsistency identified
3199
0
    }
3200
3201
0
    if (check_ret < 0) {
3202
0
        return check_ret; // Temporary error
3203
0
    }
3204
3205
0
    return 0; // Success
3206
0
}
3207
} // namespace doris::cloud