Coverage Report

Created: 2026-10-20 12:20

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