Coverage Report

Created: 2025-12-27 14:35

/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.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
102
                               [&]() { 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
27
int key_exist(TxnKv* txn_kv, std::string_view key) {
448
27
    std::unique_ptr<Transaction> txn;
449
27
    TxnErrorCode err = txn_kv->create_txn(&txn);
450
27
    if (err != TxnErrorCode::TXN_OK) {
451
0
        LOG(WARNING) << "failed to init txn, err=" << err;
452
0
        return -1;
453
0
    }
454
27
    std::string val;
455
27
    switch (txn->get(key, &val)) {
456
24
    case TxnErrorCode::TXN_OK:
457
24
        return 0;
458
3
    case TxnErrorCode::TXN_KEY_NOT_FOUND:
459
3
        return 1;
460
0
    default:
461
0
        return -1;
462
27
    }
463
27
}
464
465
InstanceChecker::InstanceChecker(std::shared_ptr<TxnKv> txn_kv, const std::string& instance_id)
466
97
        : txn_kv_(txn_kv), instance_id_(instance_id) {
467
97
    snapshot_manager_ = std::make_shared<SnapshotManager>(txn_kv);
468
97
    resource_mgr_ = std::make_shared<ResourceManager>(std::move(txn_kv));
469
97
    resource_mgr_->init();
470
97
}
471
472
97
int InstanceChecker::init(const InstanceInfoPB& instance) {
473
97
    int ret = init_obj_store_accessors(instance);
474
97
    if (ret != 0) {
475
0
        return ret;
476
0
    }
477
478
97
    return init_storage_vault_accessors(instance);
479
97
}
480
481
97
int InstanceChecker::init_obj_store_accessors(const InstanceInfoPB& instance) {
482
97
    for (const auto& obj_info : instance.obj_info()) {
483
97
#ifdef UNIT_TEST
484
97
        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
97
        accessor_map_.emplace(obj_info.id(), std::move(accessor));
502
97
    }
503
504
97
    return 0;
505
97
}
506
507
97
int InstanceChecker::init_storage_vault_accessors(const InstanceInfoPB& instance) {
508
97
    if (instance.resource_ids().empty()) {
509
97
        return 0;
510
97
    }
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
33
                LOG(INFO) << "segment file is" << (segment_file_loss ? "" : " not") << " loss, "
614
33
                          << "index file is" << (index_file_loss ? "" : " not") << " loss, "
615
33
                          << "rowset.tablet_id = " << rs_meta.tablet_id();
616
33
                num_rowset_loss++;
617
33
            }
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
15
            if (1 == key_exist(txn_kv_.get(), key)) {
667
                // Rowset has been deleted instead of data loss
668
0
                break;
669
0
            }
670
15
            data_loss = true;
671
15
            segment_file_loss = true;
672
15
            TEST_SYNC_POINT_CALLBACK("InstanceChecker.do_check1", &path);
673
15
            LOG(WARNING) << "object not exist, path=" << path
674
15
                         << ", rs_meta=" << rs_meta.ShortDebugString() << " key=" << hex(key);
675
15
        }
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
16
    do {
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
    } while (it->more() && !stopped());
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
47
        do {
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
        } while (it->more() && !stopped());
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
    do {
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
    } while (it->more() && !stopped());
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
    do {
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
    } while (it->more() && !stopped());
1135
1136
0
    return 0;
1137
0
}
1138
1139
int InstanceChecker::collect_tablet_rowsets(
1140
50
        int64_t tablet_id, const std::function<void(const doris::RowsetMetaCloudPB&)>& collect_cb) {
1141
50
    std::unique_ptr<Transaction> txn;
1142
50
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1143
50
    if (err != TxnErrorCode::TXN_OK) {
1144
0
        LOG(WARNING) << "failed to create txn";
1145
0
        return -1;
1146
0
    }
1147
50
    std::unique_ptr<RangeGetIterator> it;
1148
50
    auto begin = meta_rowset_key({instance_id_, tablet_id, 0});
1149
50
    auto end = meta_rowset_key({instance_id_, tablet_id + 1, 0});
1150
1151
50
    int64_t rowsets_num {0};
1152
50
    do {
1153
50
        TxnErrorCode err = txn->get(begin, end, &it);
1154
50
        if (err != TxnErrorCode::TXN_OK) {
1155
0
            LOG(WARNING) << "failed to get rowset kv, err=" << err;
1156
0
            return -1;
1157
0
        }
1158
50
        if (!it->has_next()) {
1159
0
            break;
1160
0
        }
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
    } while (it->more() && !stopped());
1179
1180
50
    LOG(INFO) << fmt::format(
1181
50
            "[delete bitmap checker] successfully collect rowsets for instance_id={}, "
1182
50
            "tablet_id={}, rowsets_num={}",
1183
50
            instance_id_, tablet_id, rowsets_num);
1184
50
    return 0;
1185
50
}
1186
1187
2
int InstanceChecker::do_delete_bitmap_inverted_check() {
1188
2
    LOG(INFO) << fmt::format(
1189
2
            "[delete bitmap checker] begin to do_delete_bitmap_inverted_check for instance_id={}",
1190
2
            instance_id_);
1191
1192
    // number of delete bitmap keys being scanned
1193
2
    int64_t total_delete_bitmap_keys {0};
1194
    // number of delete bitmaps which belongs to non mow tablet
1195
2
    int64_t abnormal_delete_bitmaps {0};
1196
    // number of delete bitmaps which doesn't have corresponding rowset in MS
1197
2
    int64_t leaked_delete_bitmaps {0};
1198
1199
2
    auto start_time = std::chrono::steady_clock::now();
1200
2
    DORIS_CLOUD_DEFER {
1201
2
        g_bvar_inverted_checker_leaked_delete_bitmaps.put(instance_id_, leaked_delete_bitmaps);
1202
2
        g_bvar_inverted_checker_abnormal_delete_bitmaps.put(instance_id_, abnormal_delete_bitmaps);
1203
2
        g_bvar_inverted_checker_delete_bitmaps_scanned.put(instance_id_, total_delete_bitmap_keys);
1204
1205
2
        auto cost = std::chrono::duration_cast<std::chrono::milliseconds>(
1206
2
                            std::chrono::steady_clock::now() - start_time)
1207
2
                            .count();
1208
2
        if (leaked_delete_bitmaps > 0 || abnormal_delete_bitmaps > 0) {
1209
1
            LOG(WARNING) << fmt::format(
1210
1
                    "[delete bitmap check fails] delete bitmap inverted check for instance_id={}, "
1211
1
                    "cost={} ms, total_delete_bitmap_keys={}, leaked_delete_bitmaps={}, "
1212
1
                    "abnormal_delete_bitmaps={}",
1213
1
                    instance_id_, cost, total_delete_bitmap_keys, leaked_delete_bitmaps,
1214
1
                    abnormal_delete_bitmaps);
1215
1
        } else {
1216
1
            LOG(INFO) << fmt::format(
1217
1
                    "[delete bitmap checker] delete bitmap inverted check for instance_id={}, "
1218
1
                    "passed. cost={} ms, total_delete_bitmap_keys={}",
1219
1
                    instance_id_, cost, total_delete_bitmap_keys);
1220
1
        }
1221
2
    };
1222
1223
2
    struct TabletsRowsetsCache {
1224
2
        int64_t tablet_id {-1};
1225
2
        bool enable_merge_on_write {false};
1226
2
        std::unordered_set<std::string> rowsets {};
1227
2
        std::unordered_set<std::string> pending_delete_bitmaps {};
1228
2
    } tablet_rowsets_cache {};
1229
1230
2
    std::unique_ptr<RangeGetIterator> it;
1231
2
    auto begin = meta_delete_bitmap_key({instance_id_, 0, "", 0, 0});
1232
2
    auto end =
1233
2
            meta_delete_bitmap_key({instance_id_, std::numeric_limits<int64_t>::max(), "", 0, 0});
1234
2
    do {
1235
2
        std::unique_ptr<Transaction> txn;
1236
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1237
2
        if (err != TxnErrorCode::TXN_OK) {
1238
0
            LOG(WARNING) << "failed to create txn";
1239
0
            return -1;
1240
0
        }
1241
2
        err = txn->get(begin, end, &it);
1242
2
        if (err != TxnErrorCode::TXN_OK) {
1243
0
            LOG(WARNING) << "failed to get rowset kv, err=" << err;
1244
0
            return -1;
1245
0
        }
1246
2
        if (!it->has_next()) {
1247
0
            break;
1248
0
        }
1249
502
        while (it->has_next() && !stopped()) {
1250
500
            auto [k, v] = it->next();
1251
500
            std::string_view k1 = k;
1252
500
            k1.remove_prefix(1);
1253
500
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1254
500
            decode_key(&k1, &out);
1255
            // 0x01 "meta" ${instance_id} "delete_bitmap" ${tablet_id} ${rowset_id} ${version} ${segment_id} -> roaringbitmap
1256
500
            auto tablet_id = std::get<int64_t>(std::get<0>(out[3]));
1257
500
            auto rowset_id = std::get<std::string>(std::get<0>(out[4]));
1258
500
            auto version = std::get<std::int64_t>(std::get<0>(out[5]));
1259
500
            auto segment_id = std::get<std::int64_t>(std::get<0>(out[6]));
1260
1261
500
            ++total_delete_bitmap_keys;
1262
1263
500
            if (!it->has_next()) {
1264
2
                begin = k;
1265
2
                begin.push_back('\x00'); // Update to next smallest key for iteration
1266
2
            }
1267
1268
500
            if (tablet_rowsets_cache.tablet_id == -1 ||
1269
500
                tablet_rowsets_cache.tablet_id != tablet_id) {
1270
30
                TabletMetaCloudPB tablet_meta;
1271
30
                int ret = get_tablet_meta(txn_kv_.get(), instance_id_, tablet_id, tablet_meta);
1272
30
                if (ret < 0) {
1273
0
                    LOG(WARNING) << fmt::format(
1274
0
                            "[delete bitmap checker] failed to get_tablet_meta in "
1275
0
                            "do_delete_bitmap_inverted_check(), instance_id={}, tablet_id={}",
1276
0
                            instance_id_, tablet_id);
1277
0
                    return ret;
1278
0
                }
1279
1280
30
                tablet_rowsets_cache.tablet_id = tablet_id;
1281
30
                tablet_rowsets_cache.enable_merge_on_write =
1282
30
                        tablet_meta.enable_unique_key_merge_on_write();
1283
30
                tablet_rowsets_cache.rowsets.clear();
1284
30
                tablet_rowsets_cache.pending_delete_bitmaps.clear();
1285
1286
30
                if (tablet_rowsets_cache.enable_merge_on_write) {
1287
                    // only collect rowsets for merge-on-write tablet
1288
20
                    auto collect_cb =
1289
199
                            [&tablet_rowsets_cache](const doris::RowsetMetaCloudPB& rowset) {
1290
199
                                tablet_rowsets_cache.rowsets.insert(rowset.rowset_id_v2());
1291
199
                            };
1292
20
                    ret = collect_tablet_rowsets(tablet_id, collect_cb);
1293
20
                    if (ret < 0) {
1294
0
                        return ret;
1295
0
                    }
1296
                    // get pending delete bitmaps
1297
20
                    ret = get_pending_delete_bitmap_keys(
1298
20
                            tablet_id, tablet_rowsets_cache.pending_delete_bitmaps);
1299
20
                    if (ret < 0) {
1300
0
                        return ret;
1301
0
                    }
1302
20
                }
1303
30
            }
1304
500
            DCHECK_EQ(tablet_id, tablet_rowsets_cache.tablet_id);
1305
1306
500
            if (!tablet_rowsets_cache.enable_merge_on_write) {
1307
                // clang-format off
1308
40
                TEST_SYNC_POINT_CALLBACK(
1309
40
                        "InstanceChecker::do_delete_bitmap_inverted_check.get_abnormal_delete_bitmap",
1310
40
                        &tablet_id, &rowset_id, &version, &segment_id);
1311
                // clang-format on
1312
40
                ++abnormal_delete_bitmaps;
1313
                // log an error and continue to check the next delete bitmap
1314
40
                LOG(WARNING) << fmt::format(
1315
40
                        "[delete bitmap check fails] find a delete bitmap belongs to tablet "
1316
40
                        "which is not a merge-on-write table! instance_id={}, tablet_id={}, "
1317
40
                        "version={}, segment_id={}",
1318
40
                        instance_id_, tablet_id, version, segment_id);
1319
40
                continue;
1320
40
            }
1321
1322
460
            if (!tablet_rowsets_cache.rowsets.contains(rowset_id) &&
1323
460
                !tablet_rowsets_cache.pending_delete_bitmaps.contains(std::string(k))) {
1324
170
                TEST_SYNC_POINT_CALLBACK(
1325
170
                        "InstanceChecker::do_delete_bitmap_inverted_check.get_leaked_delete_bitmap",
1326
170
                        &tablet_id, &rowset_id, &version, &segment_id);
1327
170
                ++leaked_delete_bitmaps;
1328
                // log an error and continue to check the next delete bitmap
1329
170
                LOG(WARNING) << fmt::format(
1330
170
                        "[delete bitmap check fails] can't find corresponding rowset for delete "
1331
170
                        "bitmap instance_id={}, tablet_id={}, rowset_id={}, version={}, "
1332
170
                        "segment_id={}",
1333
170
                        instance_id_, tablet_id, rowset_id, version, segment_id);
1334
170
            }
1335
460
        }
1336
2
    } while (it->more() && !stopped());
1337
1338
2
    return (leaked_delete_bitmaps > 0 || abnormal_delete_bitmaps > 0) ? 1 : 0;
1339
2
}
1340
1341
int InstanceChecker::get_pending_delete_bitmap_keys(
1342
50
        int64_t tablet_id, std::unordered_set<std::string>& pending_delete_bitmaps) {
1343
50
    std::unique_ptr<Transaction> txn;
1344
50
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1345
50
    if (err != TxnErrorCode::TXN_OK) {
1346
0
        LOG(WARNING) << "failed to create txn";
1347
0
        return -1;
1348
0
    }
1349
50
    std::string pending_key = meta_pending_delete_bitmap_key({instance_id_, tablet_id});
1350
50
    std::string pending_val;
1351
50
    err = txn->get(pending_key, &pending_val);
1352
50
    if (err != TxnErrorCode::TXN_OK && err != TxnErrorCode::TXN_KEY_NOT_FOUND) {
1353
0
        LOG(WARNING) << "failed to get pending delete bitmap kv, err=" << err;
1354
0
        return -1;
1355
0
    }
1356
50
    if (err == TxnErrorCode::TXN_OK) {
1357
2
        PendingDeleteBitmapPB pending_info;
1358
2
        if (!pending_info.ParseFromString(pending_val)) [[unlikely]] {
1359
0
            LOG(WARNING) << "failed to parse PendingDeleteBitmapPB, tablet=" << tablet_id;
1360
0
            return -1;
1361
0
        }
1362
12
        for (auto& delete_bitmap_key : pending_info.delete_bitmap_keys()) {
1363
12
            pending_delete_bitmaps.emplace(std::string(delete_bitmap_key));
1364
12
        }
1365
2
    }
1366
50
    return 0;
1367
50
}
1368
1369
int InstanceChecker::check_inverted_index_file_storage_format_v1(
1370
        int64_t tablet_id, const std::string& file_path, const std::string& rowset_info,
1371
14
        RowsetIndexesFormatV1& rowset_index_cache_v1) {
1372
    // format v1: data/{tablet_id}/{rowset_id}_{seg_num}_{idx_id}{idx_suffix}.idx
1373
14
    std::string rowset_id;
1374
14
    int64_t segment_id;
1375
14
    std::string index_id_with_suffix_name;
1376
    // {rowset_id}_{seg_num}_{idx_id}{idx_suffix}.idx
1377
14
    std::vector<std::string> str;
1378
14
    butil::SplitString(rowset_info.substr(0, rowset_info.size() - 4), '_', &str);
1379
14
    if (str.size() < 3) {
1380
0
        LOG(WARNING) << "Split rowset info with '_' error, str size < 3, rowset_info = "
1381
0
                     << rowset_info;
1382
0
        return -1;
1383
0
    }
1384
14
    rowset_id = str[0];
1385
14
    segment_id = std::atoll(str[1].c_str());
1386
14
    index_id_with_suffix_name = str[2];
1387
1388
14
    if (rowset_index_cache_v1.rowset_id == rowset_id) {
1389
0
        if (rowset_index_cache_v1.segment_ids.contains(segment_id)) {
1390
0
            if (auto it = rowset_index_cache_v1.index_ids.find(index_id_with_suffix_name);
1391
0
                it == rowset_index_cache_v1.index_ids.end()) {
1392
                // clang-format off
1393
0
                LOG(WARNING) << fmt::format("index_id with suffix name not found, rowset_info = {}, obj_key = {}", rowset_info, file_path);
1394
                // clang-format on
1395
0
                return -1;
1396
0
            }
1397
0
        } else {
1398
            // clang-format off
1399
0
            LOG(WARNING) << fmt::format("segment id not found, rowset_info = {}, obj_key = {}", rowset_info, file_path);
1400
            // clang-format on
1401
0
            return -1;
1402
0
        }
1403
0
    }
1404
1405
14
    rowset_index_cache_v1.rowset_id = rowset_id;
1406
14
    rowset_index_cache_v1.segment_ids.clear();
1407
14
    rowset_index_cache_v1.index_ids.clear();
1408
1409
14
    std::unique_ptr<Transaction> txn;
1410
14
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1411
14
    if (err != TxnErrorCode::TXN_OK) {
1412
0
        LOG(WARNING) << "failed to create txn";
1413
0
        return -1;
1414
0
    }
1415
14
    std::unique_ptr<RangeGetIterator> it;
1416
14
    auto begin = meta_rowset_key({instance_id_, tablet_id, 0});
1417
14
    auto end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
1418
14
    do {
1419
14
        TxnErrorCode err = txn->get(begin, end, &it);
1420
14
        if (err != TxnErrorCode::TXN_OK) {
1421
0
            LOG(WARNING) << "failed to get rowset kv, err=" << err;
1422
0
            return -1;
1423
0
        }
1424
14
        if (!it->has_next()) {
1425
8
            break;
1426
8
        }
1427
6
        while (it->has_next()) {
1428
            // recycle corresponding resources
1429
6
            auto [k, v] = it->next();
1430
6
            doris::RowsetMetaCloudPB rs_meta;
1431
6
            if (!rs_meta.ParseFromArray(v.data(), v.size())) {
1432
0
                LOG(WARNING) << "malformed rowset meta value, key=" << hex(k);
1433
0
                return -1;
1434
0
            }
1435
1436
6
            TabletIndexPB tablet_index;
1437
6
            if (get_tablet_idx(txn_kv_.get(), instance_id_, rs_meta.tablet_id(), tablet_index) ==
1438
6
                -1) {
1439
0
                LOG(WARNING) << "failedt to get tablet index, tablet_id= " << rs_meta.tablet_id();
1440
0
                return -1;
1441
0
            }
1442
1443
6
            auto tablet_schema_key = meta_schema_key(
1444
6
                    {instance_id_, tablet_index.index_id(), rs_meta.schema_version()});
1445
6
            ValueBuf tablet_schema_val;
1446
6
            err = cloud::blob_get(txn.get(), tablet_schema_key, &tablet_schema_val);
1447
1448
6
            if (err != TxnErrorCode::TXN_OK) {
1449
0
                LOG(WARNING) << "failed to get schema, err=" << err;
1450
0
                return -1;
1451
0
            }
1452
1453
6
            auto* schema = rs_meta.mutable_tablet_schema();
1454
6
            if (!parse_schema_value(tablet_schema_val, schema)) {
1455
0
                LOG(WARNING) << "malformed schema value, key=" << hex(tablet_schema_key);
1456
0
                return -1;
1457
0
            }
1458
1459
12
            for (size_t i = 0; i < rs_meta.num_segments(); i++) {
1460
6
                rowset_index_cache_v1.segment_ids.insert(i);
1461
6
            }
1462
1463
6
            for (const auto& i : rs_meta.tablet_schema().index()) {
1464
6
                if (i.has_index_type() && i.index_type() == IndexType::INVERTED) {
1465
6
                    LOG(INFO) << fmt::format(
1466
6
                            "record index info, index_id: {}, index_suffix_name: {}", i.index_id(),
1467
6
                            i.index_suffix_name());
1468
6
                    rowset_index_cache_v1.index_ids.insert(
1469
6
                            fmt::format("{}{}", i.index_id(), i.index_suffix_name()));
1470
6
                }
1471
6
            }
1472
1473
6
            if (!it->has_next()) {
1474
6
                begin = k;
1475
6
                begin.push_back('\x00'); // Update to next smallest key for iteration
1476
6
                break;
1477
6
            }
1478
6
        }
1479
6
    } while (it->more() && !stopped());
1480
1481
14
    if (!rowset_index_cache_v1.segment_ids.contains(segment_id)) {
1482
        // Garbage data leak
1483
        // clang-format off
1484
8
        LOG(WARNING) << "rowset_index_cache_v1.segment_ids don't contains segment_id, rowset should be recycled,"
1485
8
                     << " key = " << file_path
1486
8
                     << " segment_id = " << segment_id;
1487
        // clang-format on
1488
8
        return 1;
1489
8
    }
1490
1491
6
    if (!rowset_index_cache_v1.index_ids.contains(index_id_with_suffix_name)) {
1492
        // Garbage data leak
1493
        // clang-format off
1494
0
        LOG(WARNING) << "rowset_index_cache_v1.index_ids don't contains index_id_with_suffix_name,"
1495
0
                     << " rowset with inde meta should be recycled, key=" << file_path
1496
0
                     << " index_id_with_suffix_name=" << index_id_with_suffix_name;
1497
        // clang-format on
1498
0
        return 1;
1499
0
    }
1500
1501
6
    return 0;
1502
6
}
1503
1504
int InstanceChecker::check_inverted_index_file_storage_format_v2(
1505
        int64_t tablet_id, const std::string& file_path, const std::string& rowset_info,
1506
40
        RowsetIndexesFormatV2& rowset_index_cache_v2) {
1507
40
    std::string rowset_id;
1508
40
    int64_t segment_id;
1509
    // {rowset_id}_{seg_num}.idx
1510
40
    std::vector<std::string> str;
1511
40
    butil::SplitString(rowset_info.substr(0, rowset_info.size() - 4), '_', &str);
1512
40
    if (str.size() < 2) {
1513
        // clang-format off
1514
0
        LOG(WARNING) << "Split rowset info with '_' error, str size < 2, rowset_info = " << rowset_info;
1515
        // clang-format on
1516
0
        return -1;
1517
0
    }
1518
40
    rowset_id = str[0];
1519
40
    segment_id = std::atoll(str[1].c_str());
1520
1521
40
    if (rowset_index_cache_v2.rowset_id == rowset_id) {
1522
0
        if (!rowset_index_cache_v2.segment_ids.contains(segment_id)) {
1523
            // clang-format off
1524
0
            LOG(WARNING) << fmt::format("index file not found, rowset_info = {}, obj_key = {}", rowset_info, file_path);
1525
            // clang-format on
1526
0
            return -1;
1527
0
        }
1528
0
    }
1529
1530
40
    rowset_index_cache_v2.rowset_id = rowset_id;
1531
40
    rowset_index_cache_v2.segment_ids.clear();
1532
1533
40
    std::unique_ptr<Transaction> txn;
1534
40
    TxnErrorCode err = txn_kv_->create_txn(&txn);
1535
40
    if (err != TxnErrorCode::TXN_OK) {
1536
0
        LOG(WARNING) << "failed to create txn";
1537
0
        return -1;
1538
0
    }
1539
40
    std::unique_ptr<RangeGetIterator> it;
1540
40
    auto begin = meta_rowset_key({instance_id_, tablet_id, 0});
1541
40
    auto end = meta_rowset_key({instance_id_, tablet_id, INT64_MAX});
1542
40
    do {
1543
40
        TxnErrorCode err = txn->get(begin, end, &it);
1544
40
        if (err != TxnErrorCode::TXN_OK) {
1545
0
            LOG(WARNING) << "failed to get rowset kv, err=" << err;
1546
0
            return -1;
1547
0
        }
1548
40
        if (!it->has_next()) {
1549
5
            break;
1550
5
        }
1551
35
        while (it->has_next()) {
1552
            // recycle corresponding resources
1553
35
            auto [k, v] = it->next();
1554
35
            doris::RowsetMetaCloudPB rs_meta;
1555
35
            if (!rs_meta.ParseFromArray(v.data(), v.size())) {
1556
0
                LOG(WARNING) << "malformed rowset meta value, key=" << hex(k);
1557
0
                return -1;
1558
0
            }
1559
1560
70
            for (size_t i = 0; i < rs_meta.num_segments(); i++) {
1561
35
                rowset_index_cache_v2.segment_ids.insert(i);
1562
35
            }
1563
1564
35
            if (!it->has_next()) {
1565
35
                begin = k;
1566
35
                begin.push_back('\x00'); // Update to next smallest key for iteration
1567
35
                break;
1568
35
            }
1569
35
        }
1570
35
    } while (it->more() && !stopped());
1571
1572
40
    if (!rowset_index_cache_v2.segment_ids.contains(segment_id)) {
1573
        // Garbage data leak
1574
5
        LOG(WARNING) << "rowset with index meta should be recycled, key=" << file_path;
1575
5
        return 1;
1576
5
    }
1577
1578
35
    return 0;
1579
40
}
1580
1581
int InstanceChecker::check_delete_bitmap_storage_optimize_v2(
1582
        int64_t tablet_id, bool has_sequence_col,
1583
30
        int64_t& rowsets_with_useless_delete_bitmap_version) {
1584
    // end_version: create_time
1585
30
    std::map<int64_t, int64_t> tablet_rowsets_map {};
1586
    // rowset_id: {start_version, end_version}
1587
30
    std::map<std::string, std::pair<int64_t, int64_t>> rowset_version_map;
1588
    // Get all visible rowsets of this tablet
1589
195
    auto collect_cb = [&](const doris::RowsetMetaCloudPB& rowset) {
1590
195
        if (rowset.start_version() == 0 && rowset.end_version() == 1) {
1591
            // ignore dummy rowset [0-1]
1592
0
            return;
1593
0
        }
1594
195
        tablet_rowsets_map[rowset.end_version()] = rowset.creation_time();
1595
195
        rowset_version_map[rowset.rowset_id_v2()] =
1596
195
                std::make_pair(rowset.start_version(), rowset.end_version());
1597
195
    };
1598
30
    if (int ret = collect_tablet_rowsets(tablet_id, collect_cb); ret != 0) {
1599
0
        return ret;
1600
0
    }
1601
1602
30
    std::unordered_set<std::string> pending_delete_bitmaps;
1603
30
    if (auto ret = get_pending_delete_bitmap_keys(tablet_id, pending_delete_bitmaps); ret < 0) {
1604
0
        return ret;
1605
0
    }
1606
1607
30
    std::unique_ptr<RangeGetIterator> it;
1608
30
    auto begin = meta_delete_bitmap_key({instance_id_, tablet_id, "", 0, 0});
1609
30
    auto end = meta_delete_bitmap_key({instance_id_, tablet_id + 1, "", 0, 0});
1610
30
    std::string last_rowset_id = "";
1611
30
    int64_t last_version = 0;
1612
30
    int64_t last_failed_version = 0;
1613
30
    std::vector<int64_t> failed_versions;
1614
30
    auto print_failed_versions = [&]() {
1615
4
        TEST_SYNC_POINT_CALLBACK(
1616
4
                "InstanceChecker::check_delete_bitmap_storage_optimize_v2.get_abnormal_"
1617
4
                "rowset",
1618
4
                &tablet_id, &last_rowset_id);
1619
4
        rowsets_with_useless_delete_bitmap_version++;
1620
        // some versions are continuous, such as [8, 9, 10, 11, 13, 17, 18]
1621
        // print as [8-11, 13, 17-18]
1622
4
        int64_t last_start_version = -1;
1623
4
        int64_t last_end_version = -1;
1624
4
        std::stringstream ss;
1625
4
        ss << "[";
1626
9
        for (int64_t version : failed_versions) {
1627
9
            if (last_start_version == -1) {
1628
4
                last_start_version = version;
1629
4
                last_end_version = version;
1630
4
                continue;
1631
4
            }
1632
5
            if (last_end_version + 1 == version) {
1633
2
                last_end_version = version;
1634
3
            } else {
1635
3
                if (last_start_version == last_end_version) {
1636
3
                    ss << last_start_version << ", ";
1637
3
                } else {
1638
0
                    ss << last_start_version << "-" << last_end_version << ", ";
1639
0
                }
1640
3
                last_start_version = version;
1641
3
                last_end_version = version;
1642
3
            }
1643
5
        }
1644
4
        if (last_start_version == last_end_version) {
1645
3
            ss << last_start_version;
1646
3
        } else {
1647
1
            ss << last_start_version << "-" << last_end_version;
1648
1
        }
1649
4
        ss << "]";
1650
4
        std::stringstream version_str;
1651
4
        auto it = rowset_version_map.find(last_rowset_id);
1652
4
        if (it != rowset_version_map.end()) {
1653
4
            version_str << "[" << it->second.first << "-" << it->second.second << "]";
1654
4
        }
1655
4
        LOG(WARNING) << fmt::format(
1656
4
                "[delete bitmap check fails] delete bitmap storage optimize v2 check fail "
1657
4
                "for instance_id={}, tablet_id={}, rowset_id={}, version={} found delete "
1658
4
                "bitmap with versions={}, size={}",
1659
4
                instance_id_, tablet_id, last_rowset_id, version_str.str(), ss.str(),
1660
4
                failed_versions.size());
1661
4
    };
1662
30
    using namespace std::chrono;
1663
30
    int64_t now = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
1664
30
    do {
1665
30
        std::unique_ptr<Transaction> txn;
1666
30
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1667
30
        if (err != TxnErrorCode::TXN_OK) {
1668
0
            LOG(WARNING) << "failed to create txn";
1669
0
            return -1;
1670
0
        }
1671
30
        err = txn->get(begin, end, &it);
1672
30
        if (err != TxnErrorCode::TXN_OK) {
1673
0
            LOG(WARNING) << "failed to get delete bitmap kv, err=" << err;
1674
0
            return -1;
1675
0
        }
1676
30
        if (!it->has_next()) {
1677
0
            break;
1678
0
        }
1679
771
        while (it->has_next() && !stopped()) {
1680
741
            auto [k, v] = it->next();
1681
741
            std::string_view k1 = k;
1682
741
            k1.remove_prefix(1);
1683
741
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1684
741
            decode_key(&k1, &out);
1685
            // 0x01 "meta" ${instance_id} "delete_bitmap" ${tablet_id} ${rowset_id} ${version} ${segment_id} -> roaringbitmap
1686
741
            auto rowset_id = std::get<std::string>(std::get<0>(out[4]));
1687
741
            auto version = std::get<std::int64_t>(std::get<0>(out[5]));
1688
741
            if (!it->has_next()) {
1689
30
                begin = k;
1690
30
                begin.push_back('\x00'); // Update to next smallest key for iteration
1691
30
            }
1692
741
            if (rowset_id == last_rowset_id && version == last_version) {
1693
                // skip the same rowset and version
1694
167
                continue;
1695
167
            }
1696
574
            if (rowset_id != last_rowset_id && !failed_versions.empty()) {
1697
3
                print_failed_versions();
1698
3
                last_failed_version = 0;
1699
3
                failed_versions.clear();
1700
3
            }
1701
574
            last_rowset_id = rowset_id;
1702
574
            last_version = version;
1703
574
            if (tablet_rowsets_map.find(version) != tablet_rowsets_map.end()) {
1704
548
                continue;
1705
548
            }
1706
26
            auto version_it = rowset_version_map.find(rowset_id);
1707
26
            if (version_it == rowset_version_map.end()) {
1708
                // checked in do_delete_bitmap_inverted_check
1709
1
                continue;
1710
1
            }
1711
25
            if (pending_delete_bitmaps.contains(std::string(k))) {
1712
3
                continue;
1713
3
            }
1714
22
            if (has_sequence_col && version >= version_it->second.first &&
1715
22
                version <= version_it->second.second) {
1716
5
                continue;
1717
5
            }
1718
            // there may be an interval in this situation:
1719
            // 1. finish compaction job; 2. checker; 3. finish agg and remove delete bitmap to ms
1720
17
            auto rowset_it = tablet_rowsets_map.upper_bound(version);
1721
17
            if (rowset_it == tablet_rowsets_map.end()) {
1722
1
                if (version != last_failed_version) {
1723
1
                    failed_versions.push_back(version);
1724
1
                }
1725
1
                last_failed_version = version;
1726
1
                continue;
1727
1
            }
1728
16
            if (rowset_it->second + config::delete_bitmap_storage_optimize_v2_check_skip_seconds >=
1729
16
                now) {
1730
8
                continue;
1731
8
            }
1732
8
            if (version != last_failed_version) {
1733
8
                failed_versions.push_back(version);
1734
8
            }
1735
8
            last_failed_version = version;
1736
8
        }
1737
30
    } while (it->more() && !stopped());
1738
30
    if (!failed_versions.empty()) {
1739
1
        print_failed_versions();
1740
1
    }
1741
30
    LOG(INFO) << fmt::format(
1742
30
            "[delete bitmap checker] finish check delete bitmap storage optimize v2 for "
1743
30
            "instance_id={}, tablet_id={}, rowsets_num={}, "
1744
30
            "rowsets_with_useless_delete_bitmap_version={}",
1745
30
            instance_id_, tablet_id, tablet_rowsets_map.size(),
1746
30
            rowsets_with_useless_delete_bitmap_version);
1747
30
    return (rowsets_with_useless_delete_bitmap_version > 1 ? 1 : 0);
1748
30
}
1749
1750
3
int InstanceChecker::do_delete_bitmap_storage_optimize_check(int version) {
1751
3
    if (version != 2) {
1752
0
        return -1;
1753
0
    }
1754
3
    int64_t total_tablets_num {0};
1755
3
    int64_t failed_tablets_num {0};
1756
1757
    // for v2 check
1758
3
    int64_t max_rowsets_with_useless_delete_bitmap_version = 0;
1759
3
    int64_t tablet_id_with_max_rowsets_with_useless_delete_bitmap_version = 0;
1760
1761
    // check that for every visible rowset, there exists at least delete one bitmap in MS
1762
30
    int ret = traverse_mow_tablet([&](int64_t tablet_id, bool has_sequence_col) {
1763
30
        ++total_tablets_num;
1764
30
        int64_t rowsets_with_useless_delete_bitmap_version = 0;
1765
30
        int res = check_delete_bitmap_storage_optimize_v2(
1766
30
                tablet_id, has_sequence_col, rowsets_with_useless_delete_bitmap_version);
1767
30
        if (rowsets_with_useless_delete_bitmap_version >
1768
30
            max_rowsets_with_useless_delete_bitmap_version) {
1769
1
            max_rowsets_with_useless_delete_bitmap_version =
1770
1
                    rowsets_with_useless_delete_bitmap_version;
1771
1
            tablet_id_with_max_rowsets_with_useless_delete_bitmap_version = tablet_id;
1772
1
        }
1773
30
        failed_tablets_num += (res != 0);
1774
30
        return res;
1775
30
    });
1776
1777
3
    if (ret < 0) {
1778
0
        return ret;
1779
0
    }
1780
1781
3
    g_bvar_max_rowsets_with_useless_delete_bitmap_version.put(
1782
3
            instance_id_, max_rowsets_with_useless_delete_bitmap_version);
1783
1784
3
    std::stringstream ss;
1785
3
    ss << "[delete bitmap checker] check delete bitmap storage optimize v" << version
1786
3
       << " for instance_id=" << instance_id_ << ", total_tablets_num=" << total_tablets_num
1787
3
       << ", failed_tablets_num=" << failed_tablets_num
1788
3
       << ". max_rowsets_with_useless_delete_bitmap_version="
1789
3
       << max_rowsets_with_useless_delete_bitmap_version
1790
3
       << ", tablet_id=" << tablet_id_with_max_rowsets_with_useless_delete_bitmap_version;
1791
3
    LOG(INFO) << ss.str();
1792
1793
3
    return (failed_tablets_num > 0) ? 1 : 0;
1794
3
}
1795
1796
3
int InstanceChecker::do_mow_job_key_check() {
1797
3
    std::unique_ptr<RangeGetIterator> it;
1798
3
    std::string begin = mow_tablet_job_key({instance_id_, 0, 0});
1799
3
    std::string end = mow_tablet_job_key({instance_id_, INT64_MAX, 0});
1800
3
    MowTabletJobPB mow_tablet_job;
1801
3
    do {
1802
3
        std::unique_ptr<Transaction> txn;
1803
3
        TxnErrorCode err = txn_kv_->create_txn(&txn);
1804
3
        if (err != TxnErrorCode::TXN_OK) {
1805
0
            LOG(WARNING) << "failed to create txn";
1806
0
            return -1;
1807
0
        }
1808
3
        err = txn->get(begin, end, &it);
1809
3
        if (err != TxnErrorCode::TXN_OK) {
1810
0
            LOG(WARNING) << "failed to get mow tablet job key, err=" << err;
1811
0
            return -1;
1812
0
        }
1813
3
        int64_t now = duration_cast<std::chrono::seconds>(
1814
3
                              std::chrono::system_clock::now().time_since_epoch())
1815
3
                              .count();
1816
3
        while (it->has_next() && !stopped()) {
1817
2
            auto [k, v] = it->next();
1818
2
            std::string_view k1 = k;
1819
2
            k1.remove_prefix(1);
1820
2
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1821
2
            decode_key(&k1, &out);
1822
            // 0x01 "meta" ${instance_id} "mow_tablet_job" ${table_id} ${initiator}
1823
2
            auto table_id = std::get<int64_t>(std::get<0>(out[3]));
1824
2
            auto initiator = std::get<int64_t>(std::get<0>(out[4]));
1825
2
            if (!mow_tablet_job.ParseFromArray(v.data(), v.size())) [[unlikely]] {
1826
0
                LOG(WARNING) << "failed to parse MowTabletJobPB";
1827
0
                return -1;
1828
0
            }
1829
2
            int64_t expiration = mow_tablet_job.expiration();
1830
            // check job key failed should meet both following two condition:
1831
            // 1. job key is expired
1832
            // 2. table lock key is not found or key is not expired
1833
2
            if (expiration < now - config::mow_job_key_check_expiration_diff_seconds) {
1834
2
                std::string lock_key =
1835
2
                        meta_delete_bitmap_update_lock_key({instance_id_, table_id, -1});
1836
2
                std::string lock_val;
1837
2
                err = txn->get(lock_key, &lock_val);
1838
2
                std::string reason = "";
1839
2
                if (err == TxnErrorCode::TXN_KEY_NOT_FOUND) {
1840
0
                    reason = "table lock key not found";
1841
1842
2
                } else {
1843
2
                    DeleteBitmapUpdateLockPB lock_info;
1844
2
                    if (!lock_info.ParseFromString(lock_val)) [[unlikely]] {
1845
0
                        LOG(WARNING) << "failed to parse DeleteBitmapUpdateLockPB";
1846
0
                        return -1;
1847
0
                    }
1848
2
                    if (lock_info.expiration() > now || lock_info.lock_id() != -1) {
1849
2
                        reason = "table lock is not expired,lock_id=" +
1850
2
                                 std::to_string(lock_info.lock_id());
1851
2
                    }
1852
2
                }
1853
2
                if (reason != "") {
1854
2
                    LOG(WARNING) << fmt::format(
1855
2
                            "[compaction key check fails] mow job key check fail for "
1856
2
                            "instance_id={}, table_id={}, initiator={}, expiration={}, now={}, "
1857
2
                            "reason={}",
1858
2
                            instance_id_, table_id, initiator, expiration, now, reason);
1859
2
                    return -1;
1860
2
                }
1861
2
            }
1862
2
        }
1863
1
        begin = it->next_begin_key(); // Update to next smallest key for iteration
1864
1
    } while (it->more() && !stopped());
1865
1
    return 0;
1866
3
}
1867
4
int InstanceChecker::do_tablet_stats_key_check() {
1868
4
    int ret = 0;
1869
1870
4
    int64_t nums_leak = 0;
1871
4
    int64_t nums_loss = 0;
1872
4
    int64_t nums_scanned = 0;
1873
4
    int64_t nums_abnormal = 0;
1874
1875
4
    std::string begin = meta_tablet_key({instance_id_, 0, 0, 0, 0});
1876
4
    std::string end = meta_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1877
    // inverted check tablet exists
1878
4
    LOG(INFO) << "begin inverted check stats_tablet_key";
1879
4
    ret = scan_and_handle_kv(begin, end, [&](std::string_view key, std::string_view value) {
1880
4
        int ret = check_stats_tablet_key_exists(key, value);
1881
4
        nums_scanned++;
1882
4
        if (ret == 1) {
1883
1
            nums_loss++;
1884
1
        }
1885
4
        return ret;
1886
4
    });
1887
4
    if (ret == -1) {
1888
0
        LOG(WARNING) << "failed to inverted check if stats tablet key exists";
1889
0
        return -1;
1890
4
    } else if (ret == 1) {
1891
1
        LOG(WARNING) << "stats_tablet_key loss, nums_scanned=" << nums_scanned
1892
1
                     << ", nums_loss=" << nums_loss;
1893
1
        return 1;
1894
1
    }
1895
3
    LOG(INFO) << "finish inverted check stats_tablet_key, nums_scanned=" << nums_scanned
1896
3
              << ", nums_loss=" << nums_loss;
1897
1898
3
    begin = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1899
3
    end = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1900
3
    nums_scanned = 0;
1901
    // check tablet exists
1902
3
    LOG(INFO) << "begin check stats_tablet_key leaked";
1903
4
    ret = scan_and_handle_kv(begin, end, [&](std::string_view key, std::string_view value) {
1904
4
        int ret = check_stats_tablet_key_leaked(key, value);
1905
4
        nums_scanned++;
1906
4
        if (ret == 1) {
1907
1
            nums_leak++;
1908
1
        }
1909
4
        return ret;
1910
4
    });
1911
3
    if (ret == -1) {
1912
0
        LOG(WARNING) << "failed to check if stats tablet key exists";
1913
0
        return -1;
1914
3
    } else if (ret == 1) {
1915
1
        LOG(WARNING) << "stats_tablet_key leaked, nums_scanned=" << nums_scanned
1916
1
                     << ", nums_leak=" << nums_leak;
1917
1
        return 1;
1918
1
    }
1919
2
    LOG(INFO) << "finish check stats_tablet_key leaked, nums_scanned=" << nums_scanned
1920
2
              << ", nums_leak=" << nums_leak;
1921
1922
2
    begin = stats_tablet_key({instance_id_, 0, 0, 0, 0});
1923
2
    end = stats_tablet_key({instance_id_, INT64_MAX, 0, 0, 0});
1924
2
    nums_scanned = 0;
1925
    // check if key is normal
1926
2
    LOG(INFO) << "begin check stats_tablet_key abnormal";
1927
2
    ret = scan_and_handle_kv(begin, end, [&](std::string_view key, std::string_view value) {
1928
2
        int ret = check_stats_tablet_key(key, value);
1929
2
        nums_scanned++;
1930
2
        if (ret == 1) {
1931
1
            nums_abnormal++;
1932
1
        }
1933
2
        return ret;
1934
2
    });
1935
2
    if (ret == -1) {
1936
0
        LOG(WARNING) << "failed to check if stats tablet key exists";
1937
0
        return -1;
1938
2
    } else if (ret == 1) {
1939
1
        LOG(WARNING) << "stats_tablet_key abnormal, nums_scanned=" << nums_scanned
1940
1
                     << ", nums_abnormal=" << nums_abnormal;
1941
1
        return 1;
1942
1
    }
1943
1
    LOG(INFO) << "finish check stats_tablet_key, nums_scanned=" << nums_scanned
1944
1
              << ", nums_abnormal=" << nums_abnormal;
1945
1
    return 0;
1946
2
}
1947
1948
4
int InstanceChecker::check_stats_tablet_key_exists(std::string_view key, std::string_view value) {
1949
4
    std::string_view k1 = key;
1950
4
    k1.remove_prefix(1);
1951
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1952
4
    decode_key(&k1, &out);
1953
    // 0x01 "meta" ${instance_id} "tablet" ${table_id} ${index_id} ${partition_id} ${tablet_id}
1954
4
    auto table_id = std::get<int64_t>(std::get<0>(out[3]));
1955
4
    auto index_id = std::get<int64_t>(std::get<0>(out[4]));
1956
4
    auto partition_id = std::get<int64_t>(std::get<0>(out[5]));
1957
4
    auto tablet_id = std::get<int64_t>(std::get<0>(out[6]));
1958
4
    std::string tablet_stats_key =
1959
4
            stats_tablet_key({instance_id_, table_id, index_id, partition_id, tablet_id});
1960
4
    int ret = key_exist(txn_kv_.get(), tablet_stats_key);
1961
4
    if (ret == 1) {
1962
        // clang-format off
1963
1
        LOG(WARNING) << "stats tablet key's tablet key loss,"
1964
1
                    << " stats tablet key=" << hex(tablet_stats_key)
1965
1
                    << " meta tablet key=" << hex(key);
1966
        // clang-format on
1967
1
        return 1;
1968
3
    } else if (ret == -1) {
1969
0
        LOG(WARNING) << "failed to check key exists, key=" << hex(tablet_stats_key);
1970
0
        return -1;
1971
0
    }
1972
3
    LOG(INFO) << "check stats_tablet_key_exists ok, key=" << hex(key);
1973
3
    return 0;
1974
4
}
1975
1976
4
int InstanceChecker::check_stats_tablet_key_leaked(std::string_view key, std::string_view value) {
1977
4
    std::string_view k1 = key;
1978
4
    k1.remove_prefix(1);
1979
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
1980
4
    decode_key(&k1, &out);
1981
    // 0x01 "stats" ${instance_id} "tablet" ${table_id} ${index_id} ${partition_id} ${tablet_id}
1982
4
    auto table_id = std::get<int64_t>(std::get<0>(out[3]));
1983
4
    auto index_id = std::get<int64_t>(std::get<0>(out[4]));
1984
4
    auto partition_id = std::get<int64_t>(std::get<0>(out[5]));
1985
4
    auto tablet_id = std::get<int64_t>(std::get<0>(out[6]));
1986
4
    std::string tablet_key =
1987
4
            meta_tablet_key({instance_id_, table_id, index_id, partition_id, tablet_id});
1988
4
    int ret = key_exist(txn_kv_.get(), tablet_key);
1989
4
    if (ret == 1) {
1990
        // clang-format off
1991
1
        LOG(WARNING) << "stats tablet key's tablet key leak,"
1992
1
                    << " stats tablet key=" << hex(key)
1993
1
                    << " meta tablet key=" << hex(tablet_key);
1994
        // clang-format on
1995
1
        return 1;
1996
3
    } else if (ret == -1) {
1997
0
        LOG(WARNING) << "failed to check key exists, key=" << hex(tablet_key);
1998
0
        return -1;
1999
0
    }
2000
3
    LOG(INFO) << "check stats_tablet_key_leaked ok, key=" << hex(key);
2001
3
    return 0;
2002
4
}
2003
2004
2
int InstanceChecker::check_stats_tablet_key(std::string_view key, std::string_view value) {
2005
2
    TabletStatsPB tablet_stats_pb;
2006
2
    std::string_view k1 = key;
2007
2
    k1.remove_prefix(1);
2008
2
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2009
2
    decode_key(&k1, &out);
2010
    // 0x01 "stats" ${instance_id} "tablet" ${table_id} ${index_id} ${partition_id} ${tablet_id}
2011
2
    auto tablet_id = std::get<int64_t>(std::get<0>(out[6]));
2012
2
    std::unique_ptr<Transaction> txn;
2013
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2014
2
    if (err != TxnErrorCode::TXN_OK) {
2015
0
        LOG_WARNING("failed to recycle tablet ")
2016
0
                .tag("tablet id", tablet_id)
2017
0
                .tag("instance_id", instance_id_)
2018
0
                .tag("reason", "failed to create txn");
2019
0
        return -1;
2020
0
    }
2021
2
    std::string tablet_idx_key = meta_tablet_idx_key({instance_id_, tablet_id});
2022
2
    std::string tablet_idx_val;
2023
2
    TabletIndexPB tablet_idx;
2024
2
    err = txn->get(tablet_idx_key, &tablet_idx_val);
2025
2
    if (err != TxnErrorCode::TXN_OK) {
2026
        // clang-format off
2027
0
        LOG(WARNING) << "failed to get tablet index key,"
2028
0
                        << " key=" << hex(tablet_idx_key)
2029
0
                        << " code=" << err;
2030
        // clang-format on
2031
0
        return -1;
2032
0
    }
2033
2
    tablet_idx.ParseFromString(tablet_idx_val);
2034
2
    MetaServiceCode code = MetaServiceCode::OK;
2035
2
    std::string msg;
2036
2
    internal_get_tablet_stats(code, msg, txn.get(), instance_id_, tablet_idx, tablet_stats_pb);
2037
2
    if (code != MetaServiceCode::OK) {
2038
        // clang-format off
2039
0
        LOG(WARNING) << "failed to get tablet stats,"
2040
0
                        << " code=" << code 
2041
0
                        << " msg=" << msg;
2042
        // clang-format on
2043
0
        return -1;
2044
0
    }
2045
2046
2
    GetRowsetResponse resp;
2047
    // get rowsets in tablet
2048
2
    internal_get_rowset(txn.get(), 0, std::numeric_limits<int64_t>::max() - 1, instance_id_,
2049
2
                        tablet_id, code, msg, &resp);
2050
2
    if (code != MetaServiceCode::OK) {
2051
0
        LOG_WARNING("failed to get rowsets of tablet when check stats tablet key")
2052
0
                .tag("tablet id", tablet_id)
2053
0
                .tag("msg", msg)
2054
0
                .tag("code", code)
2055
0
                .tag("instance id", instance_id_);
2056
0
        return -1;
2057
0
    }
2058
2
    int64_t num_rows = 0;
2059
2
    int64_t num_rowsets = 0;
2060
2
    int64_t num_segments = 0;
2061
2
    int64_t total_data_size = 0;
2062
2
    for (const auto& rs_meta : resp.rowset_meta()) {
2063
2
        num_rows += rs_meta.num_rows();
2064
2
        num_rowsets++;
2065
2
        num_segments += rs_meta.num_segments();
2066
2
        total_data_size += rs_meta.total_disk_size();
2067
2
    }
2068
2
    int ret = 0;
2069
2
    if (tablet_stats_pb.data_size() != total_data_size) {
2070
1
        ret = 1;
2071
        // clang-format off
2072
1
        LOG(WARNING) << " tablet_stats_pb's data size is not same with all rowset total data size,"
2073
1
                        << " tablet_stats_pb's data size=" << tablet_stats_pb.data_size()
2074
1
                        << " all rowset total data size=" << total_data_size
2075
1
                        << " stats tablet meta=" << tablet_stats_pb.ShortDebugString();
2076
        // clang-format on
2077
1
    } else if (tablet_stats_pb.num_rows() != num_rows) {
2078
0
        ret = 1;
2079
        // clang-format off
2080
0
        LOG(WARNING) << " tablet_stats_pb's num_rows is not same with all rowset total num_rows,"
2081
0
                        << " tablet_stats_pb's num_rows=" << tablet_stats_pb.num_rows()
2082
0
                        << " all rowset total num_rows=" << num_rows
2083
0
                        << " stats tablet meta=" << tablet_stats_pb.ShortDebugString();
2084
        // clang-format on
2085
1
    } else if (tablet_stats_pb.num_rowsets() != num_rowsets) {
2086
0
        ret = 1;
2087
        // clang-format off
2088
0
        LOG(WARNING) << " tablet_stats_pb's num_rowsets is not same with all rowset nums,"
2089
0
                        << " tablet_stats_pb's num_rowsets=" << tablet_stats_pb.num_rowsets()
2090
0
                        << " all rowset nums=" << num_rowsets
2091
0
                        << " stats tablet meta=" << tablet_stats_pb.ShortDebugString();
2092
        // clang-format on
2093
1
    } else if (tablet_stats_pb.num_segments() != num_segments) {
2094
0
        ret = 1;
2095
        // clang-format off
2096
0
        LOG(WARNING) << " tablet_stats_pb's num_segments is not same with all rowset total num_segments,"
2097
0
                        << " tablet_stats_pb's num_segments=" << tablet_stats_pb.num_segments()
2098
0
                        << " all rowset total num_segments=" << num_segments
2099
0
                        << " stats tablet meta=" << tablet_stats_pb.ShortDebugString();
2100
        // clang-format on
2101
0
    }
2102
2103
2
    return ret;
2104
2
}
2105
2106
int InstanceChecker::scan_and_handle_kv(
2107
        std::string& start_key, const std::string& end_key,
2108
12
        std::function<int(std::string_view, std::string_view)> handle_kv) {
2109
12
    std::unique_ptr<Transaction> txn;
2110
12
    int ret = 0;
2111
12
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2112
12
    if (err != TxnErrorCode::TXN_OK) {
2113
0
        LOG(WARNING) << "failed to init txn";
2114
0
        return -1;
2115
0
    }
2116
12
    std::unique_ptr<RangeGetIterator> it;
2117
12
    int limit = 10000;
2118
12
    TEST_SYNC_POINT_CALLBACK("InstanceChecker:scan_and_handle_kv:limit", &limit);
2119
13
    do {
2120
13
        err = txn->get(start_key, end_key, &it, false, limit);
2121
13
        TEST_SYNC_POINT_CALLBACK("InstanceChecker:scan_and_handle_kv:get_err", &err);
2122
13
        if (err == TxnErrorCode::TXN_TOO_OLD) {
2123
1
            LOG(WARNING) << "failed to get range kv, err=txn too old, "
2124
1
                         << " now fallback to non snapshot scan";
2125
1
            err = txn_kv_->create_txn(&txn);
2126
1
            if (err == TxnErrorCode::TXN_OK) {
2127
1
                err = txn->get(start_key, end_key, &it);
2128
1
            }
2129
1
        }
2130
13
        if (err != TxnErrorCode::TXN_OK) {
2131
0
            LOG(WARNING) << "internal error, failed to get range kv, err=" << err;
2132
0
            return -1;
2133
0
        }
2134
2135
229
        while (it->has_next() && !stopped()) {
2136
216
            auto [k, v] = it->next();
2137
2138
216
            int handle_ret = handle_kv(k, v);
2139
216
            if (handle_ret == -1) {
2140
0
                return -1;
2141
216
            } else {
2142
216
                ret = std::max(ret, handle_ret);
2143
216
            }
2144
216
            if (!it->has_next()) {
2145
13
                start_key = k;
2146
13
            }
2147
216
        }
2148
13
        start_key = it->next_begin_key();
2149
13
    } while (it->more() && !stopped());
2150
12
    return ret;
2151
12
}
2152
2153
2
int InstanceChecker::do_version_key_check() {
2154
2
    std::unique_ptr<RangeGetIterator> it;
2155
2
    std::string begin = table_version_key({instance_id_, 0, 0});
2156
2
    std::string end = table_version_key({instance_id_, INT64_MAX, 0});
2157
2
    bool check_res = true;
2158
2
    do {
2159
2
        std::unique_ptr<Transaction> txn;
2160
2
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2161
2
        if (err != TxnErrorCode::TXN_OK) {
2162
0
            LOG(WARNING) << "failed to create txn";
2163
0
            return -1;
2164
0
        }
2165
2
        err = txn->get(begin, end, &it);
2166
2
        if (err != TxnErrorCode::TXN_OK) {
2167
0
            LOG(WARNING) << "failed to get mow tablet job key, err=" << err;
2168
0
            return -1;
2169
0
        }
2170
4
        while (it->has_next() && !stopped()) {
2171
2
            auto [k, v] = it->next();
2172
2
            std::string_view k1 = k;
2173
2
            k1.remove_prefix(1);
2174
2
            std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2175
2
            decode_key(&k1, &out);
2176
2
            int64_t table_version = -1;
2177
            // 0x01 "version" ${instance_id} "table" ${db_id} ${tbl_id}
2178
2
            if (!txn->decode_atomic_int(v, &table_version)) {
2179
0
                LOG(WARNING) << "malformed table version value";
2180
0
                return -1;
2181
0
            }
2182
2
            auto table_id = std::get<int64_t>(std::get<0>(out[4]));
2183
2
            auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2184
2
            std::string partition_version_key_begin =
2185
2
                    partition_version_key({instance_id_, db_id, table_id, 0});
2186
2
            std::string partition_version_key_end =
2187
2
                    partition_version_key({instance_id_, db_id, table_id, INT64_MAX});
2188
2
            VersionPB partition_version_pb;
2189
2190
2
            do {
2191
2
                std::unique_ptr<Transaction> txn;
2192
2
                TxnErrorCode err = txn_kv_->create_txn(&txn);
2193
2
                if (err != TxnErrorCode::TXN_OK) {
2194
0
                    LOG(WARNING) << "failed to create txn";
2195
0
                    return -1;
2196
0
                }
2197
2
                err = txn->get(partition_version_key_begin, partition_version_key_end, &it);
2198
2
                if (err != TxnErrorCode::TXN_OK) {
2199
0
                    LOG(WARNING) << "failed to get mow tablet job key, err=" << err;
2200
0
                    return -1;
2201
0
                }
2202
13
                while (it->has_next() && !stopped()) {
2203
11
                    auto [k, v] = it->next();
2204
                    // 0x01 "version" ${instance_id} "partition" ${db_id} ${tbl_id} ${partition_id}
2205
11
                    std::string_view k1 = k;
2206
11
                    k1.remove_prefix(1);
2207
11
                    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2208
11
                    decode_key(&k1, &out);
2209
11
                    if (!partition_version_pb.ParseFromArray(v.data(), v.size())) [[unlikely]] {
2210
0
                        LOG(WARNING) << "failed to parse partition VersionPB";
2211
0
                        return -1;
2212
0
                    }
2213
11
                    auto partition_id = std::get<int64_t>(std::get<0>(out[5]));
2214
11
                    int64_t partition_version = partition_version_pb.version();
2215
11
                    if (table_version < partition_version) {
2216
3
                        check_res = false;
2217
3
                        LOG(WARNING)
2218
3
                                << "table version is less than partition version,"
2219
3
                                << " table_id: " << table_id << "tablet_version: " << table_version
2220
3
                                << " partition_id: " << partition_id
2221
3
                                << " partition_version: " << partition_version;
2222
3
                    }
2223
11
                }
2224
2
                partition_version_key_begin = it->next_begin_key();
2225
2
            } while (it->more() && !stopped());
2226
2
        }
2227
2
        begin = it->next_begin_key(); // Update to next smallest key for iteration
2228
2
    } while (it->more() && !stopped());
2229
2
    return check_res ? 0 : -1;
2230
2
}
2231
2232
1
int InstanceChecker::do_restore_job_check() {
2233
1
    int64_t num_prepared = 0;
2234
1
    int64_t num_committed = 0;
2235
1
    int64_t num_dropped = 0;
2236
1
    int64_t num_completed = 0;
2237
1
    int64_t num_recycling = 0;
2238
1
    int64_t num_cost_many_time = 0;
2239
1
    const int64_t COST_MANY_THRESHOLD = 3600;
2240
2241
1
    using namespace std::chrono;
2242
1
    auto start_time = steady_clock::now();
2243
1
    DORIS_CLOUD_DEFER {
2244
1
        g_bvar_checker_restore_job_prepared_state.put(instance_id_, num_prepared);
2245
1
        g_bvar_checker_restore_job_committed_state.put(instance_id_, num_committed);
2246
1
        g_bvar_checker_restore_job_dropped_state.put(instance_id_, num_dropped);
2247
1
        g_bvar_checker_restore_job_completed_state.put(instance_id_, num_completed);
2248
1
        g_bvar_checker_restore_job_recycling_state.put(instance_id_, num_recycling);
2249
1
        g_bvar_checker_restore_job_cost_many_time.put(instance_id_, num_cost_many_time);
2250
1
        auto cost_ms =
2251
1
                duration_cast<std::chrono::milliseconds>(steady_clock::now() - start_time).count();
2252
1
        LOG(INFO) << "check instance restore jobs finished, cost=" << cost_ms
2253
1
                  << "ms. instance_id=" << instance_id_ << " num_prepared=" << num_prepared
2254
1
                  << " num_committed=" << num_committed << " num_dropped=" << num_dropped
2255
1
                  << " num_completed=" << num_completed << " num_recycling=" << num_recycling
2256
1
                  << " num_cost_many_time=" << num_cost_many_time;
2257
1
    };
2258
2259
1
    LOG_INFO("begin to check restore jobs").tag("instance_id", instance_id_);
2260
2261
1
    JobRestoreTabletKeyInfo restore_job_key_info0 {instance_id_, 0};
2262
1
    JobRestoreTabletKeyInfo restore_job_key_info1 {instance_id_, INT64_MAX};
2263
1
    std::string begin;
2264
1
    std::string end;
2265
1
    job_restore_tablet_key(restore_job_key_info0, &begin);
2266
1
    job_restore_tablet_key(restore_job_key_info1, &end);
2267
1
    std::unique_ptr<RangeGetIterator> it;
2268
1
    do {
2269
1
        std::unique_ptr<Transaction> txn;
2270
1
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2271
1
        if (err != TxnErrorCode::TXN_OK) {
2272
0
            LOG(WARNING) << "failed to create txn";
2273
0
            return -1;
2274
0
        }
2275
1
        err = txn->get(begin, end, &it);
2276
1
        if (err != TxnErrorCode::TXN_OK) {
2277
0
            LOG(WARNING) << "failed to get mow tablet job key, err=" << err;
2278
0
            return -1;
2279
0
        }
2280
2281
1
        if (!it->has_next()) {
2282
0
            break;
2283
0
        }
2284
3
        while (it->has_next()) {
2285
3
            auto [k, v] = it->next();
2286
3
            RestoreJobCloudPB restore_job_pb;
2287
3
            if (!restore_job_pb.ParseFromArray(v.data(), v.size())) {
2288
0
                LOG_WARNING("malformed restore job value").tag("key", hex(k));
2289
0
                return -1;
2290
0
            }
2291
2292
3
            switch (restore_job_pb.state()) {
2293
1
            case RestoreJobCloudPB::PREPARED:
2294
1
                ++num_prepared;
2295
1
                break;
2296
1
            case RestoreJobCloudPB::COMMITTED:
2297
1
                ++num_committed;
2298
1
                break;
2299
0
            case RestoreJobCloudPB::DROPPED:
2300
0
                ++num_dropped;
2301
0
                break;
2302
1
            case RestoreJobCloudPB::COMPLETED:
2303
1
                ++num_completed;
2304
1
                break;
2305
0
            case RestoreJobCloudPB::RECYCLING:
2306
0
                ++num_recycling;
2307
0
                break;
2308
0
            default:
2309
0
                break;
2310
3
            }
2311
2312
3
            int64_t current_time = ::time(nullptr);
2313
3
            if ((restore_job_pb.state() == RestoreJobCloudPB::PREPARED ||
2314
3
                 restore_job_pb.state() == RestoreJobCloudPB::COMMITTED) &&
2315
3
                current_time > restore_job_pb.ctime_s() + COST_MANY_THRESHOLD) {
2316
                // restore job run more than 1 hour
2317
1
                ++num_cost_many_time;
2318
1
                LOG_WARNING("restore job cost too many time")
2319
1
                        .tag("key", hex(k))
2320
1
                        .tag("tablet_id", restore_job_pb.tablet_id())
2321
1
                        .tag("state", restore_job_pb.state())
2322
1
                        .tag("ctime_s", restore_job_pb.ctime_s())
2323
1
                        .tag("mtime_s", restore_job_pb.mtime_s());
2324
1
            }
2325
2326
3
            if (!it->has_next()) {
2327
1
                begin = k;
2328
1
                begin.push_back('\x00'); // Update to next smallest key for iteration
2329
1
                break;
2330
1
            }
2331
3
        }
2332
1
    } while (it->more() && !stopped());
2333
1
    return 0;
2334
1
}
2335
2336
3
int InstanceChecker::check_txn_info_key(std::string_view key, std::string_view value) {
2337
3
    std::unordered_map<int64_t, std::string> txn_info_;
2338
3
    TxnLabelPB txn_label_pb;
2339
2340
6
    auto handle_check_txn_label_key = [&](std::string_view key, std::string_view value) -> int {
2341
6
        TxnInfoPB txn_info_pb;
2342
6
        std::string_view k1 = key;
2343
6
        k1.remove_prefix(1);
2344
6
        std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2345
6
        decode_key(&k1, &out);
2346
        // 0x01 "txn" ${instance_id} "txn_info" ${db_id} ${txn_id}
2347
6
        if (!txn_info_pb.ParseFromArray(value.data(), value.size())) {
2348
0
            LOG(WARNING) << "failed to parse TxnInfoPB";
2349
0
            return -1;
2350
0
        }
2351
6
        auto txn_id = std::get<int64_t>(std::get<0>(out[4]));
2352
6
        auto it = txn_info_.find(txn_id);
2353
6
        if (it == txn_info_.end()) {
2354
0
            return 0;
2355
6
        } else {
2356
6
            if (it->second != txn_info_pb.label()) {
2357
1
                LOG(WARNING) << "txn_info_pb's txn_label not same with txn_label_pb's txn_label,"
2358
1
                             << " txn_info_pb's txn_label: " << txn_info_pb.label()
2359
1
                             << " txn_label_pb meta: " << txn_label_pb.ShortDebugString();
2360
1
                return 1;
2361
1
            }
2362
6
        }
2363
5
        return 0;
2364
6
    };
2365
3
    std::string_view k1 = key;
2366
3
    k1.remove_prefix(1);
2367
3
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2368
3
    decode_key(&k1, &out);
2369
    // 0x01 "txn" ${instance_id} "txn_label" ${db_id} ${label}
2370
3
    if (!txn_label_pb.ParseFromArray(value.data(), value.size() - VERSION_STAMP_LEN)) {
2371
1
        LOG(WARNING) << "failed to parse TxnLabelPB";
2372
1
        return -1;
2373
1
    }
2374
2
    auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2375
2
    auto label = std::get<std::string>(std::get<0>(out[4]));
2376
    // txn_id -> txn_label
2377
6
    for (const auto& txn_id : txn_label_pb.txn_ids()) {
2378
6
        txn_info_.insert({txn_id, label});
2379
6
    }
2380
2
    std::string txn_info_key_begin = txn_info_key({instance_id_, db_id, 0});
2381
2
    std::string txn_info_key_end = txn_info_key({instance_id_, db_id, INT64_MAX});
2382
2
    return scan_and_handle_kv(txn_info_key_begin, txn_info_key_end,
2383
6
                              [&](std::string_view k, std::string_view v) -> int {
2384
6
                                  return handle_check_txn_label_key(k, v);
2385
6
                              });
2386
3
}
2387
2388
6
int InstanceChecker::check_txn_label_key(std::string_view key, std::string_view value) {
2389
6
    TxnInfoPB txn_info_pb;
2390
6
    std::string_view k1 = key;
2391
6
    k1.remove_prefix(1);
2392
6
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2393
6
    decode_key(&k1, &out);
2394
    // 0x01 "txn" ${instance_id} "txn_info" ${db_id} ${txn_id}
2395
6
    if (!txn_info_pb.ParseFromArray(value.data(), value.size())) {
2396
1
        LOG(WARNING) << "failed to parse TxnInfoPB";
2397
1
        return -1;
2398
1
    }
2399
5
    auto txn_id = std::get<int64_t>(std::get<0>(out[4]));
2400
5
    auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2401
5
    auto label = txn_info_pb.label();
2402
5
    std::string txn_label = txn_label_key({instance_id_, db_id, label});
2403
5
    std::string txn_label_val;
2404
5
    TxnLabelPB txn_label_pb;
2405
5
    std::unique_ptr<Transaction> txn;
2406
5
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2407
5
    if (err != TxnErrorCode::TXN_OK) {
2408
0
        LOG(WARNING) << "failed to init txn";
2409
0
        return -1;
2410
0
    }
2411
5
    if (txn->get(txn_label, &txn_label_val) != TxnErrorCode::TXN_OK) {
2412
1
        LOG(WARNING) << "failed to get txn label key, key=" << hex(txn_label);
2413
1
        return -1;
2414
1
    }
2415
4
    txn_label_pb.ParseFromString(txn_label_val);
2416
4
    auto txn_ids = txn_label_pb.txn_ids();
2417
4
    if (!std::count(txn_ids.begin(), txn_ids.end(), txn_id)) {
2418
        // clang-format off txn_info_pb
2419
1
        LOG(WARNING) << "txn_info_pb's txn_id not found in txn_label_pb info,"
2420
1
                     << " txn_id: " << txn_id
2421
1
                     << " txn_label_pb meta: " << txn_label_pb.ShortDebugString();
2422
        // clang-format on
2423
1
        return 1;
2424
1
    }
2425
3
    return 0;
2426
4
}
2427
2428
4
int InstanceChecker::check_txn_index_key(std::string_view key, std::string_view value) {
2429
4
    TxnInfoPB txn_info_pb;
2430
4
    std::string_view k1 = key;
2431
4
    k1.remove_prefix(1);
2432
4
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2433
4
    decode_key(&k1, &out);
2434
    // 0x01 "txn" ${instance_id} "txn_info" ${db_id} ${txn_id}
2435
4
    if (!txn_info_pb.ParseFromArray(value.data(), value.size())) {
2436
1
        LOG(WARNING) << "failed to parse TxnInfoPB";
2437
1
        return -1;
2438
1
    }
2439
3
    auto txn_id = std::get<int64_t>(std::get<0>(out[4]));
2440
3
    auto db_id = std::get<int64_t>(std::get<0>(out[3]));
2441
    /// get tablet id
2442
3
    std::string txn_index = txn_index_key({instance_id_, txn_id});
2443
3
    std::string txn_index_val;
2444
3
    TxnIndexPB txn_index_pb;
2445
3
    std::unique_ptr<Transaction> txn;
2446
3
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2447
3
    if (err != TxnErrorCode::TXN_OK) {
2448
0
        LOG(WARNING) << "failed to init txn";
2449
0
        return -1;
2450
0
    }
2451
3
    if (txn->get(txn_index, &txn_index_val) != TxnErrorCode::TXN_OK) {
2452
1
        LOG(WARNING) << "failed to get txn label key, key=" << hex(txn_index);
2453
1
        return -1;
2454
1
    }
2455
2
    txn_index_pb.ParseFromString(txn_index_val);
2456
2
    if (txn_index_pb.tablet_index().db_id() != db_id) {
2457
        // clang-format off txn_info_pb
2458
1
        LOG(WARNING) << "txn_index_pb's db_id not same with txn_info_pb's db_id,"
2459
1
                     << " txn_index_pb meta: " << txn_index_pb.ShortDebugString()
2460
1
                     << " txn_info_pb meta: " << txn_info_pb.ShortDebugString();
2461
        // clang-format on
2462
1
        return 1;
2463
1
    }
2464
1
    return 0;
2465
2
}
2466
2467
3
int InstanceChecker::check_txn_running_key(std::string_view key, std::string_view value) {
2468
3
    TxnRunningPB txn_running_pb;
2469
3
    int64_t current_time =
2470
3
            duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
2471
3
    if (!txn_running_pb.ParseFromArray(value.data(), value.size())) {
2472
1
        LOG(WARNING) << "failed to parse TxnRunningPB";
2473
1
        return -1;
2474
1
    }
2475
2
    if (txn_running_pb.timeout_time() <= current_time) {
2476
1
        LOG(WARNING) << "txn_running_pb.timeout_time() is less than current_time,"
2477
1
                     << " but txn_running_key exists, "
2478
1
                     << " txn_running_pb meta: " << txn_running_pb.ShortDebugString();
2479
1
        return 1;
2480
1
    }
2481
1
    return 0;
2482
2
}
2483
2484
0
int InstanceChecker::do_txn_key_check() {
2485
0
    int ret = 0;
2486
2487
    // check txn info key depend on txn label key
2488
0
    std::string begin = txn_label_key({instance_id_, 0, ""});
2489
0
    std::string end = txn_label_key({instance_id_, INT64_MAX, ""});
2490
0
    int64_t num_scanned = 0;
2491
0
    int64_t num_abnormal = 0;
2492
0
    LOG(INFO) << "begin check txn_label_key and txn_info_key";
2493
0
    ret = scan_and_handle_kv(begin, end, [&, this](std::string_view k, std::string_view v) -> int {
2494
0
        num_scanned++;
2495
0
        int ret = check_txn_info_key(k, v);
2496
0
        if (ret == 1) {
2497
0
            num_abnormal++;
2498
0
        }
2499
0
        return ret;
2500
0
    });
2501
2502
0
    if (ret == 1) {
2503
0
        LOG(WARNING) << "failed to check txn_info_key depending on txn_label_key, num_scanned="
2504
0
                     << num_scanned << ", num_abnormal=" << num_abnormal;
2505
0
        return 1;
2506
0
    } else if (ret == -1) {
2507
0
        LOG(WARNING) << "failed to check txn label key and txn info key";
2508
0
        return -1;
2509
0
    }
2510
2511
    // check txn label key depend on txn info key
2512
0
    begin = txn_info_key({instance_id_, 0, 0});
2513
0
    end = txn_info_key({instance_id_, INT64_MAX, 0});
2514
0
    num_scanned = 0;
2515
0
    num_abnormal = 0;
2516
0
    LOG(INFO) << "begin check txn_label_key and txn_info_key";
2517
0
    ret = scan_and_handle_kv(begin, end, [&, this](std::string_view k, std::string_view v) -> int {
2518
0
        num_scanned++;
2519
0
        int ret = check_txn_label_key(k, v);
2520
0
        if (ret == 1) {
2521
0
            num_abnormal++;
2522
0
        }
2523
0
        return ret;
2524
0
    });
2525
0
    if (ret == 1) {
2526
0
        LOG(WARNING) << "failed to check txn_label_key depending on txn_info_key, num_scanned="
2527
0
                     << num_scanned << ", num_abnormal=" << num_abnormal;
2528
0
        return 1;
2529
0
    } else if (ret == -1) {
2530
0
        LOG(WARNING) << "failed to inverted check txn label key and txn info key";
2531
0
        return -1;
2532
0
    }
2533
0
    LOG(INFO) << "finish check txn_label_key and txn_info_key, num_scanned=" << num_scanned
2534
0
              << ", num_abnormal=" << num_abnormal;
2535
2536
    // check txn index key depend on txn info key
2537
0
    begin = txn_info_key({instance_id_, 0, 0});
2538
0
    end = txn_info_key({instance_id_, INT64_MAX, 0});
2539
0
    num_scanned = 0;
2540
0
    num_abnormal = 0;
2541
0
    LOG(INFO) << "begin check txn_index_key and txn_info_key";
2542
0
    ret = scan_and_handle_kv(begin, end, [&, this](std::string_view k, std::string_view v) -> int {
2543
0
        num_scanned++;
2544
0
        int ret = check_txn_index_key(k, v);
2545
0
        if (ret == 1) {
2546
0
            num_abnormal++;
2547
0
        }
2548
0
        return ret;
2549
0
    });
2550
0
    if (ret == 1) {
2551
0
        LOG(WARNING) << "failed to check txn_idx_key depending on txn_info_key, num_scanned="
2552
0
                     << num_scanned << ", num_abnormal=" << num_abnormal;
2553
0
        return 1;
2554
0
    } else if (ret == -1) {
2555
0
        LOG(WARNING) << "failed to check txn index key";
2556
0
        return -1;
2557
0
    }
2558
0
    LOG(INFO) << "finish check txn_index_key and txn_info_key, num_scanned=" << num_scanned
2559
0
              << ", num_abnormal=" << num_abnormal;
2560
2561
    // check txn running key
2562
0
    begin = txn_running_key({instance_id_, 0, 0});
2563
0
    end = txn_running_key({instance_id_, INT64_MAX, 0});
2564
0
    num_scanned = 0;
2565
0
    num_abnormal = 0;
2566
0
    LOG(INFO) << "begin check txn_running_key";
2567
0
    ret = scan_and_handle_kv(begin, end, [&, this](std::string_view k, std::string_view v) -> int {
2568
0
        num_scanned++;
2569
0
        int ret = check_txn_running_key(k, v);
2570
0
        if (ret == 1) {
2571
0
            num_abnormal++;
2572
0
        }
2573
0
        return ret;
2574
0
    });
2575
0
    if (ret == 1) {
2576
0
        LOG(WARNING) << "failed to check txn_running_key, num_scanned=" << num_scanned
2577
0
                     << ", num_abnormal=" << num_abnormal;
2578
0
        return 1;
2579
0
    } else if (ret == -1) {
2580
0
        LOG(WARNING) << "failed to check txn running key";
2581
0
        return -1;
2582
0
    }
2583
0
    LOG(INFO) << "finish check txn_running_key, num_scanned=" << num_scanned
2584
0
              << ", num_abnormal=" << num_abnormal;
2585
0
    return 0;
2586
0
}
2587
2588
2
int InstanceChecker::check_meta_tmp_rowset_key(std::string_view key, std::string_view value) {
2589
2
    TxnInfoPB txn_info_pb;
2590
2
    std::string_view k1 = key;
2591
2
    k1.remove_prefix(1);
2592
2
    std::vector<std::tuple<std::variant<int64_t, std::string>, int, int>> out;
2593
2
    decode_key(&k1, &out);
2594
    // 0x01 "txn" ${instance_id} "txn_info" ${db_id} ${txn_id}
2595
2
    if (!txn_info_pb.ParseFromArray(value.data(), value.size())) {
2596
0
        LOG(WARNING) << "failed to parse TxnInfoPB";
2597
0
        return -1;
2598
0
    }
2599
    /// get tablet id
2600
2
    auto txn_id = std::get<int64_t>(std::get<0>(out[4]));
2601
2
    std::string txn_index = txn_index_key({instance_id_, txn_id});
2602
2
    std::string txn_index_val;
2603
2
    TxnIndexPB txn_index_pb;
2604
2
    std::unique_ptr<Transaction> txn;
2605
2
    TxnErrorCode err = txn_kv_->create_txn(&txn);
2606
2
    if (err != TxnErrorCode::TXN_OK) {
2607
0
        LOG(WARNING) << "failed to init txn";
2608
0
        return -1;
2609
0
    }
2610
2
    if (txn->get(txn_index, &txn_index_val) != TxnErrorCode::TXN_OK) {
2611
0
        LOG(WARNING) << "failed to get txn index key, key=" << txn_index;
2612
0
        return -1;
2613
0
    }
2614
2
    txn_index_pb.ParseFromString(txn_index_val);
2615
2
    auto tablet_id = txn_index_pb.tablet_index().tablet_id();
2616
2
    std::string meta_tmp_rowset_key = meta_rowset_tmp_key({instance_id_, txn_id, tablet_id});
2617
2
    int is_key_exist = key_exist(txn_kv_.get(), meta_tmp_rowset_key);
2618
2
    if (is_key_exist == 1) {
2619
0
        if (txn_info_pb.status() != TxnStatusPB::TXN_STATUS_VISIBLE) {
2620
            // clang-format off
2621
0
            LOG(INFO) << "meta tmp rowset key not exist but txn status != TXN_STATUS_VISIBLE"
2622
0
                        << "meta tmp rowset key=" << meta_tmp_rowset_key
2623
0
                        << "txn_info=" << txn_info_pb.ShortDebugString();
2624
            // clang-format on
2625
0
            return 1;
2626
0
        }
2627
2
    } else if (is_key_exist == 0) {
2628
2
        if (txn_info_pb.status() != TxnStatusPB::TXN_STATUS_PREPARED) {
2629
            // clang-format off
2630
1
            LOG(INFO) << "meta tmp rowset key exist but txn status != TXN_STATUS_PREPARED"
2631
1
                        << "meta tmp rowset key=" << meta_tmp_rowset_key
2632
1
                        << "txn_info=" << txn_info_pb.ShortDebugString();
2633
            // clang-format on
2634
1
            return 1;
2635
1
        }
2636
2
    } else {
2637
0
        LOG(WARNING) << "failed to get key, key=" << meta_tmp_rowset_key;
2638
0
        return -1;
2639
0
    }
2640
1
    return 0;
2641
2
}
2642
2643
2
int InstanceChecker::check_meta_rowset_key(std::string_view key, std::string_view value) {
2644
2
    RowsetMetaCloudPB meta_rowset_pb;
2645
2
    if (!meta_rowset_pb.ParseFromArray(value.data(), value.size())) {
2646
0
        LOG(WARNING) << "failed to parse RowsetMetaCloudPB";
2647
0
        return -1;
2648
0
    }
2649
2
    std::string tablet_index_key = meta_tablet_idx_key({instance_id_, meta_rowset_pb.tablet_id()});
2650
2
    if (key_exist(txn_kv_.get(), tablet_index_key) == 1) {
2651
1
        LOG(WARNING) << "rowset's tablet id not found in fdb"
2652
1
                     << "tablet_index_key: " << tablet_index_key
2653
1
                     << "rowset meta: " << meta_rowset_pb.ShortDebugString();
2654
1
        return 1;
2655
1
    }
2656
1
    return 0;
2657
2
}
2658
2659
0
int InstanceChecker::do_meta_rowset_key_check() {
2660
0
    int ret = 0;
2661
2662
0
    std::string begin = meta_rowset_key({instance_id_, 0, 0});
2663
0
    std::string end = meta_rowset_key({instance_id_, INT64_MAX, 0});
2664
0
    int64_t num_scanned = 0;
2665
0
    int64_t num_loss = 0;
2666
2667
0
    ret = scan_and_handle_kv(begin, end, [&](std::string_view k, std::string_view v) {
2668
0
        num_scanned++;
2669
0
        int ret = check_meta_rowset_key(k, v);
2670
0
        if (ret == 1) {
2671
0
            num_loss++;
2672
0
        }
2673
0
        return ret;
2674
0
    });
2675
0
    if (ret == -1) {
2676
0
        LOG(WARNING) << "failed to check meta rowset key,";
2677
0
        return -1;
2678
0
    } else if (ret == 1) {
2679
0
        LOG(WARNING) << "meta rowset key may be loss, num_scanned=" << num_scanned
2680
0
                     << ", num_loss=" << num_loss;
2681
0
    }
2682
0
    LOG(INFO) << "meta rowset key check finish, num_scanned=" << num_scanned
2683
0
              << ", num_loss=" << num_loss;
2684
2685
0
    begin = txn_info_key({instance_id_, 0, 0});
2686
0
    end = txn_info_key({instance_id_, INT64_MAX, 0});
2687
0
    num_scanned = 0;
2688
0
    num_loss = 0;
2689
2690
0
    ret = scan_and_handle_kv(begin, end, [&](std::string_view k, std::string_view v) {
2691
0
        num_scanned++;
2692
0
        int ret = check_meta_tmp_rowset_key(k, v);
2693
0
        if (ret == 1) {
2694
0
            num_loss++;
2695
0
        }
2696
0
        return ret;
2697
0
    });
2698
0
    if (ret == -1) {
2699
0
        LOG(WARNING) << "failed to check tmp meta rowset key";
2700
0
        return -1;
2701
0
    } else if (ret == 1) {
2702
0
        LOG(WARNING) << "meta tmp rowset key may be loss, num_scanned=" << num_scanned
2703
0
                     << ", num_loss=" << num_loss;
2704
0
    }
2705
0
    LOG(INFO) << "meta tmp rowset key check finish, num_scanned=" << num_scanned
2706
0
              << ", num_loss=" << num_loss;
2707
2708
0
    return ret;
2709
0
}
2710
2711
0
StorageVaultAccessor* InstanceChecker::get_accessor(const std::string& id) {
2712
0
    auto it = accessor_map_.find(id);
2713
0
    if (it == accessor_map_.end()) {
2714
0
        return nullptr;
2715
0
    }
2716
0
    return it->second.get();
2717
0
}
2718
2719
0
void InstanceChecker::get_all_accessor(std::vector<StorageVaultAccessor*>* accessors) {
2720
0
    for (const auto& [_, accessor] : accessor_map_) {
2721
0
        accessors->push_back(accessor.get());
2722
0
    }
2723
0
}
2724
2725
0
int InstanceChecker::do_packed_file_check() {
2726
0
    LOG(INFO) << "begin to check packed files, instance_id=" << instance_id_;
2727
0
    int check_ret = 0;
2728
0
    long num_scanned_rowsets = 0;
2729
0
    long num_scanned_packed_files = 0;
2730
0
    long num_packed_file_loss = 0;
2731
0
    long num_packed_file_leak = 0;
2732
0
    long num_ref_count_mismatch = 0;
2733
0
    long num_small_file_ref_mismatch = 0;
2734
0
    using namespace std::chrono;
2735
0
    auto start_time = steady_clock::now();
2736
0
    DORIS_CLOUD_DEFER {
2737
0
        auto cost = duration<float>(steady_clock::now() - start_time).count();
2738
0
        LOG(INFO) << "check packed files finished, cost=" << cost
2739
0
                  << "s. instance_id=" << instance_id_
2740
0
                  << " num_scanned_rowsets=" << num_scanned_rowsets
2741
0
                  << " num_scanned_packed_files=" << num_scanned_packed_files
2742
0
                  << " num_packed_file_loss=" << num_packed_file_loss
2743
0
                  << " num_packed_file_leak=" << num_packed_file_leak
2744
0
                  << " num_ref_count_mismatch=" << num_ref_count_mismatch
2745
0
                  << " num_small_file_ref_mismatch=" << num_small_file_ref_mismatch;
2746
0
    };
2747
2748
    // Map to track expected reference count for each packed file
2749
    // packed_file_path -> expected_ref_count (from rowset metas)
2750
0
    std::unordered_map<std::string, int64_t> expected_ref_counts;
2751
    // Map to track small files referenced in packed files
2752
    // packed_file_path -> set of small_file_paths
2753
0
    std::unordered_map<std::string, std::unordered_set<std::string>> packed_file_small_files;
2754
2755
    // Step 1: Scan all rowset metas to collect packed_slice_locations references
2756
    // Use efficient range scan instead of iterating through each tablet_id
2757
0
    auto collect_packed_refs = [&](const doris::RowsetMetaCloudPB& rs_meta) {
2758
0
        const auto& index_map = rs_meta.packed_slice_locations();
2759
0
        for (const auto& [small_file_path, index_pb] : index_map) {
2760
0
            if (!index_pb.has_packed_file_path() || index_pb.packed_file_path().empty()) {
2761
0
                continue;
2762
0
            }
2763
0
            const std::string& packed_file_path = index_pb.packed_file_path();
2764
0
            expected_ref_counts[packed_file_path]++;
2765
0
            packed_file_small_files[packed_file_path].insert(small_file_path);
2766
0
        }
2767
0
    };
2768
2769
0
    {
2770
0
        std::string start_key = meta_rowset_key({instance_id_, 0, 0});
2771
0
        std::string end_key = meta_rowset_key({instance_id_, INT64_MAX, 0});
2772
2773
0
        std::unique_ptr<RangeGetIterator> it;
2774
0
        do {
2775
0
            if (stopped()) {
2776
0
                return -1;
2777
0
            }
2778
2779
0
            std::unique_ptr<Transaction> txn;
2780
0
            TxnErrorCode err = txn_kv_->create_txn(&txn);
2781
0
            if (err != TxnErrorCode::TXN_OK) {
2782
0
                LOG(WARNING) << "failed to create txn for packed file check";
2783
0
                return -1;
2784
0
            }
2785
2786
0
            err = txn->get(start_key, end_key, &it);
2787
0
            if (err != TxnErrorCode::TXN_OK) {
2788
0
                LOG(WARNING) << "failed to scan rowset metas, err=" << err;
2789
0
                check_ret = -1;
2790
0
                break;
2791
0
            }
2792
2793
0
            while (it->has_next() && !stopped()) {
2794
0
                auto [k, v] = it->next();
2795
0
                if (!it->has_next()) {
2796
0
                    start_key = k;
2797
0
                }
2798
2799
0
                doris::RowsetMetaCloudPB rs_meta;
2800
0
                if (!rs_meta.ParseFromArray(v.data(), v.size())) {
2801
0
                    LOG(WARNING) << "malformed rowset meta, key=" << hex(k);
2802
0
                    check_ret = -1;
2803
0
                    continue;
2804
0
                }
2805
2806
0
                num_scanned_rowsets++;
2807
2808
0
                collect_packed_refs(rs_meta);
2809
0
            }
2810
0
            start_key.push_back('\x00'); // Update to next smallest key for iteration
2811
0
        } while (it->more() && !stopped());
2812
0
    }
2813
2814
    // Rowsets in recycle keys may still hold packed file references while ref count
2815
    // updates are pending, so include them when calculating expected references.
2816
0
    {
2817
0
        std::string start_key = recycle_rowset_key({instance_id_, 0, ""});
2818
0
        std::string end_key = recycle_rowset_key({instance_id_, INT64_MAX, "\xff"});
2819
2820
0
        std::unique_ptr<RangeGetIterator> it;
2821
0
        do {
2822
0
            if (stopped()) {
2823
0
                return -1;
2824
0
            }
2825
2826
0
            std::unique_ptr<Transaction> txn;
2827
0
            TxnErrorCode err = txn_kv_->create_txn(&txn);
2828
0
            if (err != TxnErrorCode::TXN_OK) {
2829
0
                LOG(WARNING) << "failed to create txn for recycle rowset scan in packed file check";
2830
0
                return -1;
2831
0
            }
2832
2833
0
            err = txn->get(start_key, end_key, &it);
2834
0
            if (err != TxnErrorCode::TXN_OK) {
2835
0
                LOG(WARNING) << "failed to scan recycle rowset metas, err=" << err;
2836
0
                check_ret = -1;
2837
0
                break;
2838
0
            }
2839
2840
0
            while (it->has_next() && !stopped()) {
2841
0
                auto [k, v] = it->next();
2842
0
                if (!it->has_next()) {
2843
0
                    start_key = k;
2844
0
                }
2845
2846
0
                RecycleRowsetPB recycle_rowset;
2847
0
                if (!recycle_rowset.ParseFromArray(v.data(), v.size())) {
2848
0
                    LOG(WARNING) << "malformed recycle rowset, key=" << hex(k);
2849
0
                    check_ret = -1;
2850
0
                    continue;
2851
0
                }
2852
2853
0
                if (!recycle_rowset.has_rowset_meta()) {
2854
0
                    continue;
2855
0
                }
2856
2857
0
                num_scanned_rowsets++;
2858
0
                collect_packed_refs(recycle_rowset.rowset_meta());
2859
0
            }
2860
0
            start_key.push_back('\x00'); // Update to next smallest key for iteration
2861
0
        } while (it->more() && !stopped());
2862
0
    }
2863
2864
    // Step 2: Scan all packed file metadata and verify
2865
    // Also collect all packed file paths from metadata for Step 3
2866
    // Map: resource_id -> set of packed_file_paths
2867
0
    std::unordered_map<std::string, std::unordered_set<std::string>> packed_files_in_metadata;
2868
0
    std::string begin = packed_file_key({instance_id_, ""});
2869
0
    std::string end = packed_file_key({instance_id_, "\xff"});
2870
0
    std::string scan_begin = begin;
2871
2872
0
    while (true) {
2873
0
        if (stopped()) {
2874
0
            return -1;
2875
0
        }
2876
2877
0
        std::unique_ptr<Transaction> txn;
2878
0
        TxnErrorCode err = txn_kv_->create_txn(&txn);
2879
0
        if (err != TxnErrorCode::TXN_OK) {
2880
0
            LOG(WARNING) << "failed to create txn for scanning packed files";
2881
0
            return -1;
2882
0
        }
2883
2884
0
        std::unique_ptr<RangeGetIterator> it;
2885
0
        err = txn->get(scan_begin, end, &it);
2886
0
        if (err != TxnErrorCode::TXN_OK) {
2887
0
            LOG(WARNING) << "failed to scan packed file keys, err=" << err;
2888
0
            return -1;
2889
0
        }
2890
0
        if (!it->has_next()) {
2891
0
            break;
2892
0
        }
2893
2894
0
        std::string last_key;
2895
0
        while (it->has_next()) {
2896
0
            auto [k, v] = it->next();
2897
0
            last_key.assign(k.data(), k.size());
2898
0
            num_scanned_packed_files++;
2899
2900
0
            std::string packed_file_path;
2901
0
            if (!InstanceRecycler::decode_packed_file_key(k, &packed_file_path)) {
2902
0
                LOG(WARNING) << "failed to decode packed file key, key=" << hex(k);
2903
0
                check_ret = -1;
2904
0
                continue;
2905
0
            }
2906
2907
0
            cloud::PackedFileInfoPB packed_info;
2908
0
            if (!packed_info.ParseFromArray(v.data(), v.size())) {
2909
0
                LOG(WARNING) << "failed to parse packed file info, packed_file_path="
2910
0
                             << packed_file_path;
2911
0
                check_ret = -1;
2912
0
                continue;
2913
0
            }
2914
2915
            // Step 2.1: Verify packed file exists in storage
2916
0
            if (!packed_info.resource_id().empty()) {
2917
                // Collect packed file path for Step 3
2918
0
                packed_files_in_metadata[packed_info.resource_id()].insert(packed_file_path);
2919
2920
0
                auto* accessor = get_accessor(packed_info.resource_id());
2921
0
                if (accessor == nullptr) {
2922
0
                    LOG(WARNING) << "accessor not found for packed file, resource_id="
2923
0
                                 << packed_info.resource_id()
2924
0
                                 << ", packed_file_path=" << packed_file_path;
2925
0
                    check_ret = -1;
2926
0
                    continue;
2927
0
                }
2928
2929
0
                int ret = accessor->exists(packed_file_path);
2930
0
                if (ret < 0) {
2931
0
                    LOG(WARNING) << "failed to check packed file existence, packed_file_path="
2932
0
                                 << packed_file_path << ", ret=" << ret;
2933
0
                    check_ret = -1;
2934
0
                    continue;
2935
0
                }
2936
2937
0
                if (ret != 0) {
2938
                    // ret == 1 means file not found, ret > 1 means other error
2939
                    // When packed file doesn't exist in storage, ref_cnt must be 0 and state must be RECYCLING
2940
0
                    bool ref_cnt_valid = (packed_info.ref_cnt() == 0);
2941
0
                    bool state_valid = (packed_info.state() == cloud::PackedFileInfoPB::RECYCLING);
2942
0
                    if (!ref_cnt_valid || !state_valid) {
2943
0
                        LOG(WARNING) << "packed file not found in storage but metadata is invalid, "
2944
0
                                        "packed_file_path="
2945
0
                                     << packed_file_path << ", ref_cnt=" << packed_info.ref_cnt()
2946
0
                                     << " (expected=0), state=" << packed_info.state()
2947
0
                                     << " (expected=RECYCLING), ret=" << ret;
2948
0
                        num_packed_file_loss++;
2949
0
                        check_ret = 1; // Data inconsistency identified
2950
0
                    }
2951
                    // If ref_cnt == 0 and state == RECYCLING, this is expected (file is being recycled)
2952
0
                }
2953
                // ret == 0 means file exists, which is expected
2954
0
            }
2955
2956
            // Step 2.2: Verify reference count matches expected count
2957
0
            int64_t expected_ref = expected_ref_counts[packed_file_path];
2958
0
            if (packed_info.ref_cnt() != expected_ref) {
2959
0
                LOG(WARNING) << "packed file ref count mismatch, packed_file_path="
2960
0
                             << packed_file_path << ", expected=" << expected_ref
2961
0
                             << ", actual=" << packed_info.ref_cnt();
2962
0
                num_ref_count_mismatch++;
2963
0
                check_ret = 1; // Data inconsistency identified
2964
0
            }
2965
2966
            // Step 2.3: Verify small files in packed_info match rowset references
2967
0
            std::unordered_set<std::string> small_files_in_meta;
2968
0
            for (const auto& small_file : packed_info.slices()) {
2969
0
                if (!small_file.deleted()) {
2970
0
                    small_files_in_meta.insert(small_file.path());
2971
0
                }
2972
0
            }
2973
2974
0
            const auto& expected_small_files = packed_file_small_files[packed_file_path];
2975
0
            if (small_files_in_meta != expected_small_files) {
2976
                // Check for missing small files
2977
0
                for (const auto& expected_path : expected_small_files) {
2978
0
                    if (small_files_in_meta.find(expected_path) == small_files_in_meta.end()) {
2979
0
                        LOG(WARNING) << "small file missing in packed file info, packed_file_path="
2980
0
                                     << packed_file_path << ", small_file_path=" << expected_path;
2981
0
                        num_small_file_ref_mismatch++;
2982
0
                        check_ret = 1;
2983
0
                    }
2984
0
                }
2985
                // Check for extra small files (may be deleted, so less critical)
2986
0
                for (const auto& meta_path : small_files_in_meta) {
2987
0
                    if (expected_small_files.find(meta_path) == expected_small_files.end()) {
2988
0
                        LOG(INFO) << "small file in packed file info not found in rowset metas, "
2989
0
                                     "may be deleted, packed_file_path="
2990
0
                                  << packed_file_path << ", small_file_path=" << meta_path;
2991
0
                    }
2992
0
                }
2993
0
            }
2994
0
        }
2995
2996
0
        if (!it->more()) {
2997
0
            break;
2998
0
        }
2999
0
        scan_begin = last_key;
3000
0
        scan_begin.push_back('\x00');
3001
0
    }
3002
3003
    // Step 3: Check for leaked packed files (exist in storage but not in metadata)
3004
    // Scan all storage vaults to find packed files and verify they are in metadata
3005
0
    {
3006
0
        std::vector<StorageVaultAccessor*> accessors;
3007
0
        get_all_accessor(&accessors);
3008
3009
0
        for (StorageVaultAccessor* accessor : accessors) {
3010
0
            if (stopped()) {
3011
0
                return -1;
3012
0
            }
3013
3014
            // Find resource_id for this accessor
3015
0
            std::string resource_id;
3016
0
            for (const auto& [id, acc] : accessor_map_) {
3017
0
                if (acc.get() == accessor) {
3018
0
                    resource_id = id;
3019
0
                    break;
3020
0
                }
3021
0
            }
3022
3023
0
            if (resource_id.empty()) {
3024
0
                continue;
3025
0
            }
3026
3027
            // List all files under data/packed_file/ directory
3028
0
            std::unique_ptr<ListIterator> list_it;
3029
0
            int ret = accessor->list_directory("data/packed_file", &list_it);
3030
0
            if (ret != 0) {
3031
                // Directory may not exist, which is fine
3032
0
                if (ret < 0) {
3033
0
                    LOG(WARNING) << "failed to list packed_file directory, resource_id="
3034
0
                                 << resource_id << ", ret=" << ret;
3035
0
                    check_ret = -1;
3036
0
                }
3037
0
                continue;
3038
0
            }
3039
3040
0
            const auto& expected_packed_files = packed_files_in_metadata[resource_id];
3041
0
            while (list_it->has_next()) {
3042
0
                if (stopped()) {
3043
0
                    return -1;
3044
0
                }
3045
3046
0
                auto file_meta = list_it->next();
3047
0
                if (!file_meta.has_value()) {
3048
0
                    break;
3049
0
                }
3050
3051
0
                const std::string& file_path = file_meta->path;
3052
                // Only check files (not directories), and ensure it's a packed file
3053
                // Skip directories (paths ending with '/') and non-packed-file paths
3054
0
                if (file_path.empty() || file_path.back() == '/' ||
3055
0
                    !file_path.starts_with("data/packed_file/")) {
3056
0
                    continue;
3057
0
                }
3058
3059
                // Check if this packed file is in metadata
3060
0
                if (expected_packed_files.find(file_path) == expected_packed_files.end()) {
3061
0
                    LOG(WARNING) << "packed file found in storage but not in metadata, "
3062
0
                                    "resource_id="
3063
0
                                 << resource_id << ", packed_file_path=" << file_path;
3064
0
                    num_packed_file_leak++;
3065
0
                    check_ret = 1; // Data leak identified
3066
0
                }
3067
0
            }
3068
0
        }
3069
0
    }
3070
3071
0
    if (num_packed_file_loss > 0 || num_packed_file_leak > 0 || num_ref_count_mismatch > 0 ||
3072
0
        num_small_file_ref_mismatch > 0) {
3073
0
        return 1; // Data loss or inconsistency identified
3074
0
    }
3075
3076
0
    if (check_ret < 0) {
3077
0
        return check_ret; // Temporary error
3078
0
    }
3079
3080
0
    return 0; // Success
3081
0
}
3082
} // namespace doris::cloud