Coverage Report

Created: 2026-08-15 01:38

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