Coverage Report

Created: 2026-08-21 15:00

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