test_snapshot.cpp 73.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under the License.

#include <fiu-control.h>
13
#include <fiu/fiu-local.h>
14 15 16
#include <gtest/gtest.h>

#include <string>
X
XuPeng-SH 已提交
17
#include <set>
18
#include <algorithm>
19

G
groot 已提交
20
#include "db/utils.h"
21
#include "db/snapshot/HandlerFactory.h"
22

23 24 25 26 27 28 29 30 31 32 33
Status
GetFirstCollectionID(ID_TYPE& result_id) {
    std::vector<ID_TYPE> ids;
    auto status = Snapshots::GetInstance().GetCollectionIds(ids);
    if (status.ok()) {
        result_id = ids.at(0);
    }

    return status;
}

34 35 36
TEST_F(SnapshotTest, ResourcesTest) {
    int nprobe = 16;
    milvus::json params = {{"nprobe", nprobe}};
37 38
    ParamsField p_field(params);
    ASSERT_EQ(params, p_field.GetParams());
39

40
    auto nprobe_real = p_field.GetParams().at("nprobe").get<int>();
41
    ASSERT_EQ(nprobe, nprobe_real);
42
}
43 44 45 46 47 48 49 50

TEST_F(SnapshotTest, ReferenceProxyTest) {
    std::string status("raw");
    const std::string CALLED = "CALLED";
    auto callback = [&]() {
        status = CALLED;
    };

51
    auto proxy = ReferenceProxy();
J
Jin Hai 已提交
52
    ASSERT_EQ(proxy.ref_count(), 0);
53 54 55 56 57

    int refcnt = 3;
    for (auto i = 0; i < refcnt; ++i) {
        proxy.Ref();
    }
J
Jin Hai 已提交
58
    ASSERT_EQ(proxy.ref_count(), refcnt);
59 60 61 62 63 64

    proxy.RegisterOnNoRefCB(callback);

    for (auto i = 0; i < refcnt; ++i) {
        proxy.UnRef();
    }
J
Jin Hai 已提交
65
    ASSERT_EQ(proxy.ref_count(), 0);
66 67 68 69
    ASSERT_EQ(status, CALLED);
}

TEST_F(SnapshotTest, ScopedResourceTest) {
70
    auto inner = std::make_shared<Collection>("c1");
J
Jin Hai 已提交
71
    ASSERT_EQ(inner->ref_count(), 0);
72 73

    {
74
        auto not_scoped = CollectionScopedT(inner, false);
J
Jin Hai 已提交
75
        ASSERT_EQ(not_scoped->ref_count(), 0);
76
        not_scoped->Ref();
J
Jin Hai 已提交
77 78
        ASSERT_EQ(not_scoped->ref_count(), 1);
        ASSERT_EQ(inner->ref_count(), 1);
79 80

        auto not_scoped_2 = not_scoped;
J
Jin Hai 已提交
81 82 83 84 85 86 87 88
        ASSERT_EQ(not_scoped_2->ref_count(), 1);
        ASSERT_EQ(not_scoped->ref_count(), 1);
        ASSERT_EQ(inner->ref_count(), 1);

        not_scoped_2->Ref();
        ASSERT_EQ(not_scoped_2->ref_count(), 2);
        ASSERT_EQ(not_scoped->ref_count(), 2);
        ASSERT_EQ(inner->ref_count(), 2);
89
    }
J
Jin Hai 已提交
90 91
    inner->UnRef();
    ASSERT_EQ(inner->ref_count(), 1);
92 93

    inner->UnRef();
J
Jin Hai 已提交
94
    ASSERT_EQ(inner->ref_count(), 0);
95 96 97

    {
        // Test scoped construct
98
        auto scoped = CollectionScopedT(inner);
J
Jin Hai 已提交
99 100
        ASSERT_EQ(scoped->ref_count(), 1);
        ASSERT_EQ(inner->ref_count(), 1);
101 102 103

        {
            // Test bool operator
C
Cai Yudong 已提交
104
            CollectionScopedT other_scoped;
105 106 107
            ASSERT_EQ(other_scoped, false);
            // Test operator=
            other_scoped = scoped;
J
Jin Hai 已提交
108 109 110
            ASSERT_EQ(other_scoped->ref_count(), 2);
            ASSERT_EQ(scoped->ref_count(), 2);
            ASSERT_EQ(inner->ref_count(), 2);
111
        }
J
Jin Hai 已提交
112 113
        ASSERT_EQ(scoped->ref_count(), 1);
        ASSERT_EQ(inner->ref_count(), 1);
114 115 116 117

        {
            // Test copy
            auto other_scoped(scoped);
J
Jin Hai 已提交
118 119 120
            ASSERT_EQ(other_scoped->ref_count(), 2);
            ASSERT_EQ(scoped->ref_count(), 2);
            ASSERT_EQ(inner->ref_count(), 2);
121
        }
J
Jin Hai 已提交
122 123
        ASSERT_EQ(scoped->ref_count(), 1);
        ASSERT_EQ(inner->ref_count(), 1);
124
    }
J
Jin Hai 已提交
125
    ASSERT_EQ(inner->ref_count(), 0);
126 127 128
}

TEST_F(SnapshotTest, ResourceHoldersTest) {
129 130
    ID_TYPE collection_id;
    ASSERT_TRUE(GetFirstCollectionID(collection_id).ok());
131
    auto collection = CollectionsHolder::GetInstance().GetResource(collection_id, false);
J
Jin Hai 已提交
132
    auto prev_cnt = collection->ref_count();
133
    {
C
Cai Yudong 已提交
134
        auto collection_2 = CollectionsHolder::GetInstance().GetResource(collection_id, false);
C
Cai Yudong 已提交
135 136
        ASSERT_EQ(collection_2->GetID(), collection_id);
        ASSERT_EQ(collection_2->ref_count(), prev_cnt);
137 138 139
    }

    {
J
Jin Hai 已提交
140 141 142
        auto collection_3 = CollectionsHolder::GetInstance().GetResource(collection_id, true);
        ASSERT_EQ(collection_3->GetID(), collection_id);
        ASSERT_EQ(collection_3->ref_count(), 1+prev_cnt);
143 144
    }

145 146
    std::this_thread::sleep_for(std::chrono::milliseconds(80));

147
    if (prev_cnt == 0) {
J
Jin Hai 已提交
148 149
        auto collection_4 = CollectionsHolder::GetInstance().GetResource(collection_id, false);
        ASSERT_TRUE(!collection_4);
150 151 152
    }
}

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
TEST_F(SnapshotTest, DeleteOperationTest) {
    std::string collection_name = "test_c1";
    LSN_TYPE lsn = 1;
    auto ss = CreateCollection(collection_name, lsn);
    ASSERT_TRUE(ss);

    auto collection = CollectionsHolder::GetInstance().GetResource(ss->GetCollectionId());
    ASSERT_EQ(collection->GetName(), collection_name);

    {
        auto soft_op = std::make_shared<SoftDeleteCollectionOperation>(collection->GetID());
        auto status = soft_op->Push();
        ASSERT_TRUE(status.ok());
        CollectionPtr soft_deleted;
        status = soft_op->GetResource(soft_deleted);
        ASSERT_TRUE(status.ok());
        ASSERT_TRUE(soft_deleted);
        ASSERT_EQ(soft_deleted->GetID(), collection->GetID());
        ASSERT_TRUE(soft_deleted->IsDeactive());
    }

    {
        CollectionPtr loaded;
        LoadOperationContext context;
        context.id = collection->GetID();
        auto load_op = std::make_shared<milvus::engine::snapshot::LoadOperation<Collection>>(context);
        auto status = load_op->Push();
        ASSERT_TRUE(status.ok());
        status = load_op->GetResource(loaded);
        ASSERT_TRUE(status.ok());
        ASSERT_TRUE(loaded);
        ASSERT_EQ(loaded->GetID(), collection->GetID());
        ASSERT_TRUE(loaded->IsDeactive());
    }

    {
        auto hard_op = std::make_shared<milvus::engine::snapshot::HardDeleteOperation<Collection>
            >(collection->GetID());
        auto status = hard_op->Push();
        ASSERT_TRUE(status.ok());
    }

    {
        CollectionPtr loaded;
        LoadOperationContext context;
        context.id = collection->GetID();
        auto load_op = std::make_shared<milvus::engine::snapshot::LoadOperation<Collection>>(context);
        auto status = load_op->Push();
        if (!status.ok()) {
            std::cout << status.ToString() << std::endl;
        }
        ASSERT_FALSE(status.ok());
    }

    {
        auto soft_op = std::make_shared<SoftDeleteCollectionOperation>(collection->GetID());
        auto status = soft_op->Push();
        if (!status.ok()) {
            std::cout << status.ToString() << std::endl;
        }
        ASSERT_FALSE(status.ok());
    }
}

217
TEST_F(SnapshotTest, CreateCollectionOperationTest) {
218 219
    ScopedSnapshotT expect_null;
    auto status = Snapshots::GetInstance().GetSnapshot(expect_null, 100000);
C
Cai Yudong 已提交
220
    ASSERT_FALSE(expect_null);
221 222

    std::string collection_name = "test_c1";
223
    LSN_TYPE lsn = 1;
X
XuPeng-SH 已提交
224
    auto ss = CreateCollection(collection_name, lsn);
225
    ASSERT_TRUE(ss);
226

227 228
    ScopedSnapshotT latest_ss;
    status = Snapshots::GetInstance().GetSnapshot(latest_ss, "xxxx");
C
Cai Yudong 已提交
229
    ASSERT_FALSE(status.ok());
230

231
    status = Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
C
Cai Yudong 已提交
232
    ASSERT_TRUE(status.ok());
233 234 235
    ASSERT_TRUE(latest_ss);
    ASSERT_TRUE(latest_ss->GetName() == collection_name);

236 237
    IDS_TYPE ids;
    status = Snapshots::GetInstance().GetCollectionIds(ids);
C
Cai Yudong 已提交
238
    ASSERT_TRUE(status.ok());
239
    ASSERT_EQ(ids.size(), 6);
J
Jin Hai 已提交
240
    ASSERT_EQ(ids.back(), latest_ss->GetCollectionId());
241

242
    OperationContext sd_op_ctx;
243
    sd_op_ctx.collection = latest_ss->GetCollection();
X
XuPeng-SH 已提交
244
    sd_op_ctx.lsn = latest_ss->GetMaxLsn() + 1;
245
    ASSERT_TRUE(sd_op_ctx.collection->IsActive());
246
    auto sd_op = std::make_shared<DropCollectionOperation>(sd_op_ctx, latest_ss);
247 248
    status = sd_op->Push();
    ASSERT_TRUE(status.ok());
249
    ASSERT_TRUE(sd_op->GetStatus().ok());
C
Cai Yudong 已提交
250 251
    ASSERT_FALSE(sd_op_ctx.collection->IsActive());
    ASSERT_FALSE(latest_ss->GetCollection()->IsActive());
252

253
    Snapshots::GetInstance().Reset();
254 255 256
}

TEST_F(SnapshotTest, DropCollectionTest) {
257
    std::string collection_name = "test_c1";
258
    LSN_TYPE lsn = 1;
X
XuPeng-SH 已提交
259
    auto ss = CreateCollection(collection_name, lsn);
260
    ASSERT_TRUE(ss);
261 262
    ScopedSnapshotT lss;
    auto status = Snapshots::GetInstance().GetSnapshot(lss, collection_name);
263 264 265 266 267
    ASSERT_TRUE(status.ok());
    ASSERT_TRUE(lss);
    ASSERT_EQ(ss->GetID(), lss->GetID());
    auto prev_ss_id = ss->GetID();
    auto prev_c_id = ss->GetCollection()->GetID();
X
XuPeng-SH 已提交
268
    lsn = ss->GetMaxLsn() + 1;
269
    status = Snapshots::GetInstance().DropCollection(collection_name, lsn);
270
    ASSERT_TRUE(status.ok());
271
    status = Snapshots::GetInstance().GetSnapshot(lss, collection_name);
C
Cai Yudong 已提交
272
    ASSERT_FALSE(status.ok());
273

X
XuPeng-SH 已提交
274
    auto ss_2 = CreateCollection(collection_name, ++lsn);
275
    status = Snapshots::GetInstance().GetSnapshot(lss, collection_name);
276
//    EXPECT_DEATH({assert(1 == 2);}, "nullptr")
277 278
    ASSERT_TRUE(status.ok());
    ASSERT_EQ(ss_2->GetID(), lss->GetID());
C
Cai Yudong 已提交
279 280
    ASSERT_NE(prev_ss_id, ss_2->GetID());
    ASSERT_NE(prev_c_id, ss_2->GetCollection()->GetID());
281
    status = Snapshots::GetInstance().DropCollection(collection_name, ++lsn);
282
    ASSERT_TRUE(status.ok());
283
    status = Snapshots::GetInstance().DropCollection(collection_name, ++lsn);
C
Cai Yudong 已提交
284
    ASSERT_FALSE(status.ok());
285 286 287 288
}

TEST_F(SnapshotTest, ConCurrentCollectionOperation) {
    std::string collection_name("c1");
289
    LSN_TYPE lsn = 1;
290

291
    ID_TYPE stale_ss_id;
292
    auto worker1 = [&]() {
293
        Status status;
X
XuPeng-SH 已提交
294
        auto ss = CreateCollection(collection_name, ++lsn);
295
        ASSERT_TRUE(ss);
296 297
        ASSERT_EQ(ss->GetName(), collection_name);
        stale_ss_id = ss->GetID();
C
Cai Yudong 已提交
298
        ScopedSnapshotT a_ss;
299
        status = Snapshots::GetInstance().GetSnapshot(a_ss, collection_name);
300
        ASSERT_TRUE(status.ok());
301
        std::this_thread::sleep_for(std::chrono::milliseconds(80));
C
Cai Yudong 已提交
302
        ASSERT_FALSE(ss->GetCollection()->IsActive());
303
        status = Snapshots::GetInstance().GetSnapshot(a_ss, collection_name);
C
Cai Yudong 已提交
304
        ASSERT_FALSE(status.ok());
305

306
        auto c_c = CollectionCommitsHolder::GetInstance().GetResource(stale_ss_id, false);
307 308 309 310 311
        ASSERT_TRUE(c_c);
        ASSERT_EQ(c_c->GetID(), stale_ss_id);
    };
    auto worker2 = [&] {
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
312
        auto status = Snapshots::GetInstance().DropCollection(collection_name, ++lsn);
313
        ASSERT_TRUE(status.ok());
314 315
        ScopedSnapshotT a_ss;
        status = Snapshots::GetInstance().GetSnapshot(a_ss, collection_name);
C
Cai Yudong 已提交
316
        ASSERT_FALSE(status.ok());
317 318 319
    };
    auto worker3 = [&] {
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
X
XuPeng-SH 已提交
320
        auto ss = CreateCollection(collection_name, ++lsn);
C
Cai Yudong 已提交
321
        ASSERT_FALSE(ss);
322
        std::this_thread::sleep_for(std::chrono::milliseconds(80));
X
XuPeng-SH 已提交
323
        ss = CreateCollection(collection_name, ++lsn);
324 325 326 327 328 329 330 331 332 333
        ASSERT_TRUE(ss);
        ASSERT_EQ(ss->GetName(), collection_name);
    };
    std::thread t1 = std::thread(worker1);
    std::thread t2 = std::thread(worker2);
    std::thread t3 = std::thread(worker3);
    t1.join();
    t2.join();
    t3.join();

334
    auto c_c = CollectionCommitsHolder::GetInstance().GetResource(stale_ss_id, false);
C
Cai Yudong 已提交
335
    ASSERT_FALSE(c_c);
336 337 338 339
}

TEST_F(SnapshotTest, PartitionTest) {
    std::string collection_name("c1");
340
    LSN_TYPE lsn = 1;
X
XuPeng-SH 已提交
341
    auto ss = CreateCollection(collection_name, ++lsn);
342 343 344 345
    ASSERT_TRUE(ss);
    ASSERT_EQ(ss->GetName(), collection_name);
    ASSERT_EQ(ss->NumberOfPartitions(), 1);

346 347 348 349 350
    auto partition_iterator = std::make_shared<PartitionCollector>(ss);
    partition_iterator->Iterate();
    ASSERT_TRUE(partition_iterator->GetStatus().ok());
    ASSERT_EQ(partition_iterator->partition_names_.size(), 1);

351
    OperationContext context;
X
XuPeng-SH 已提交
352
    context.lsn = ++lsn;
353
    auto op = std::make_shared<CreatePartitionOperation>(context, ss);
354 355

    std::string partition_name("p1");
356
    PartitionContext p_ctx;
357
    p_ctx.name = partition_name;
358
    PartitionPtr partition;
359 360 361 362
    auto status = op->CommitNewPartition(p_ctx, partition);
    ASSERT_TRUE(status.ok());
    ASSERT_TRUE(partition);
    ASSERT_EQ(partition->GetName(), partition_name);
C
Cai Yudong 已提交
363
    ASSERT_FALSE(partition->IsActive());
364 365 366 367
    ASSERT_TRUE(partition->HasAssigned());

    status = op->Push();
    ASSERT_TRUE(status.ok());
C
Cai Yudong 已提交
368
    ScopedSnapshotT curr_ss;
369 370 371 372
    status = op->GetSnapshot(curr_ss);
    ASSERT_TRUE(status.ok());
    ASSERT_TRUE(curr_ss);
    ASSERT_EQ(curr_ss->GetName(), ss->GetName());
C
Cai Yudong 已提交
373
    ASSERT_GT(curr_ss->GetID(), ss->GetID());
374 375
    ASSERT_EQ(curr_ss->NumberOfPartitions(), 2);

376 377 378 379 380
    partition_iterator = std::make_shared<PartitionCollector>(curr_ss);
    partition_iterator->Iterate();
    ASSERT_TRUE(partition_iterator->GetStatus().ok());
    ASSERT_EQ(partition_iterator->partition_names_.size(), 2);

X
XuPeng-SH 已提交
381
    p_ctx.lsn = ++lsn;
382
    auto drop_op = std::make_shared<DropPartitionOperation>(p_ctx, curr_ss);
383 384 385
    status = drop_op->Push();
    ASSERT_TRUE(status.ok());

C
Cai Yudong 已提交
386
    ScopedSnapshotT latest_ss;
387 388 389 390 391 392 393
    status = drop_op->GetSnapshot(latest_ss);
    ASSERT_TRUE(status.ok());
    ASSERT_TRUE(latest_ss);
    ASSERT_EQ(latest_ss->GetName(), ss->GetName());
    ASSERT_TRUE(latest_ss->GetID() > curr_ss->GetID());
    ASSERT_EQ(latest_ss->NumberOfPartitions(), 1);

X
XuPeng-SH 已提交
394
    p_ctx.lsn = ++lsn;
395
    drop_op = std::make_shared<DropPartitionOperation>(p_ctx, latest_ss);
396 397
    status = drop_op->Push();
    std::cout << status.ToString() << std::endl;
C
Cai Yudong 已提交
398
    ASSERT_FALSE(status.ok());
399

X
XuPeng-SH 已提交
400
    // TODO: Keep LSN in order
401
    PartitionContext pp_ctx;
X
XuPeng-SH 已提交
402 403 404
    /* pp_ctx.name = "p2"; */
    /* curr_ss = CreatePartition(collection_name, pp_ctx, lsn-1); */
    /* ASSERT_TRUE(curr_ss); */
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

    std::stringstream p_name_stream;

    auto num = RandomInt(20, 30);
    for (auto i = 0; i < num; ++i) {
        p_name_stream.str("");
        p_name_stream << "partition_" << i;
        pp_ctx.name = p_name_stream.str();
        curr_ss = CreatePartition(collection_name, pp_ctx, ++lsn);
        ASSERT_TRUE(curr_ss);
        ASSERT_EQ(curr_ss->NumberOfPartitions(), 2 + i);
    }

    auto total_partition_num = curr_ss->NumberOfPartitions();

    ID_TYPE partition_id;
    for (auto i = 0; i < num; ++i) {
        p_name_stream.str("");
        p_name_stream << "partition_" << i;

        status = curr_ss->GetPartitionId(p_name_stream.str(), partition_id);
        ASSERT_TRUE(status.ok());
C
Cai Yudong 已提交
427
        status = Snapshots::GetInstance().DropPartition(curr_ss->GetCollectionId(), partition_id, ++lsn);
428
        ASSERT_TRUE(status.ok());
C
Cai Yudong 已提交
429
        status = Snapshots::GetInstance().GetSnapshot(curr_ss, curr_ss->GetCollectionId());
430
        ASSERT_TRUE(status.ok());
C
Cai Yudong 已提交
431
        ASSERT_EQ(curr_ss->NumberOfPartitions(), total_partition_num - i - 1);
432
    }
433 434
}

435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
TEST_F(SnapshotTest, PartitionTest2) {
    std::string collection_name("c1");
    LSN_TYPE lsn = 1;
    milvus::Status status;

    auto ss = CreateCollection(collection_name, ++lsn);
    ASSERT_TRUE(ss);
    ASSERT_EQ(lsn, ss->GetMaxLsn());

    OperationContext context;
    context.lsn = lsn;
    auto cp_op = std::make_shared<CreatePartitionOperation>(context, ss);
    std::string partition_name("p1");
    PartitionContext p_ctx;
    p_ctx.name = partition_name;
    PartitionPtr partition;
    status = cp_op->CommitNewPartition(p_ctx, partition);
    ASSERT_TRUE(status.ok());
    ASSERT_TRUE(partition);
    ASSERT_EQ(partition->GetName(), partition_name);
    ASSERT_FALSE(partition->IsActive());
    ASSERT_TRUE(partition->HasAssigned());

    status = cp_op->Push();
    ASSERT_FALSE(status.ok());
}
X
XuPeng-SH 已提交
461

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
TEST_F(SnapshotTest, DropSegmentTest){
    LSN_TYPE lsn = 0;
    auto next_lsn = [&]() -> decltype(lsn) {
        return ++lsn;
    };
    auto collection_name = "test";
    ScopedSnapshotT ss;
    ss = CreateCollection(collection_name, ++lsn);


    milvus::Status status;

    PartitionContext pp_ctx;
    std::stringstream p_name_stream;

    auto num = RandomInt(3, 5);
    for (auto i = 0; i < num; ++i) {
        p_name_stream.str("");
        p_name_stream << "partition_" << i;
        pp_ctx.name = p_name_stream.str();
        ss = CreatePartition(ss->GetName(), pp_ctx, next_lsn());
        ASSERT_TRUE(ss);
    }

    ASSERT_EQ(ss->NumberOfPartitions(), num + 1);

    auto total_row_cnt = 0;
    auto partitions = ss->GetResources<Partition>();
    SegmentFileContext sf_context;
    SFContextBuilder(sf_context, ss);

    for (auto& kv : partitions) {
        num = RandomInt(2, 5);
        auto row_cnt = 1024;
        for (auto i = 0; i < num; ++i) {
            ASSERT_TRUE(CreateSegment(ss, kv.first, next_lsn(), sf_context, row_cnt).ok());
            total_row_cnt += row_cnt;
        }
    }

    status = Snapshots::GetInstance().GetSnapshot(ss, collection_name);
    ASSERT_TRUE(status.ok());
    ASSERT_EQ(total_row_cnt, ss->GetCollectionCommit()->GetRowCount());

    OperationContext drop_seg_context;
    auto segments = ss->GetResources<Segment>();
    auto prev_partitions = ss->GetResources<Partition>();
    ASSERT_TRUE(!prev_partitions.empty());
    ASSERT_TRUE(!segments.empty());
    for (auto kv:segments){
        milvus::engine::snapshot::ID_TYPE segment_id = kv.first;
        auto seg = ss->GetResource<milvus::engine::snapshot::Segment>(segment_id);
        drop_seg_context.prev_segment = seg;
        auto drop_op = std::make_shared<milvus::engine::snapshot::DropSegmentOperation>(drop_seg_context, ss);
        status = drop_op->Push();
        ASSERT_TRUE(status.ok());
    }
    status = Snapshots::GetInstance().GetSnapshot(ss, collection_name);
    ASSERT_TRUE(status.ok());
    auto result_segments = ss->GetResources<Segment>();
    auto result_partitions = ss->GetResources<Partition>();
    ASSERT_TRUE(!result_partitions.empty());
    ASSERT_TRUE(result_segments.empty());

}

528
TEST_F(SnapshotTest, IndexTest) {
529
    LSN_TYPE lsn = 0;
530 531 532 533
    auto next_lsn = [&]() -> decltype(lsn) {
        return ++lsn;
    };

534 535 536 537 538 539
    std::vector<ID_TYPE> ids;
    auto status = Snapshots::GetInstance().GetCollectionIds(ids);
    ASSERT_TRUE(status.ok()) << status.message();

    auto collection_id = ids.at(0);

540
    ScopedSnapshotT ss;
541 542
    status = Snapshots::GetInstance().GetSnapshot(ss, collection_id);
    ASSERT_TRUE(status.ok()) << status.message();
543

544 545 546
    SegmentFileContext sf_context;
    SFContextBuilder(sf_context, ss);

547 548
    OperationContext context;
    context.lsn = next_lsn();
549
    context.prev_partition = ss->GetResource<Partition>(sf_context.partition_id);
550
    auto build_op = std::make_shared<ChangeSegmentFileOperation>(context, ss);
551 552 553 554
    SegmentFilePtr seg_file;
    status = build_op->CommitNewSegmentFile(sf_context, seg_file);
    ASSERT_TRUE(status.ok());
    ASSERT_TRUE(seg_file);
555 556
    auto op_ctx = build_op->GetContext();
    ASSERT_EQ(seg_file, op_ctx.new_segment_files[0]);
557 558 559

    build_op->Push();
    status = build_op->GetSnapshot(ss);
560
    ASSERT_TRUE(status.ok()) << status.message();
561 562

    auto filter = [&](SegmentFile::Ptr segment_file) -> bool {
563
        return segment_file->GetSegmentId() == seg_file->GetSegmentId();
564
    };
565 566 567 568 569

    auto filter2 = [&](SegmentFile::Ptr segment_file) -> bool {
        return true;
    };

570 571 572 573 574 575
    auto sf_collector = std::make_shared<SegmentFileCollector>(ss, filter);
    sf_collector->Iterate();

    auto it_found = sf_collector->segment_files_.find(seg_file->GetID());
    ASSERT_NE(it_found, sf_collector->segment_files_.end());

576 577
    status = Snapshots::GetInstance().GetSnapshot(ss, collection_id);
    ASSERT_TRUE(status.ok()) << status.ToString();
578 579 580

    OperationContext drop_ctx;
    drop_ctx.lsn = next_lsn();
581
    drop_ctx.stale_segment_files.push_back(seg_file);
582 583 584 585 586 587 588 589 590 591 592 593
    auto drop_op = std::make_shared<DropIndexOperation>(drop_ctx, ss);
    status = drop_op->Push();
    ASSERT_TRUE(status.ok());

    status = drop_op->GetSnapshot(ss);
    ASSERT_TRUE(status.ok());

    sf_collector = std::make_shared<SegmentFileCollector>(ss, filter);
    sf_collector->Iterate();

    it_found = sf_collector->segment_files_.find(seg_file->GetID());
    ASSERT_EQ(it_found, sf_collector->segment_files_.end());
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

    PartitionContext pp_ctx;
    std::stringstream p_name_stream;

    auto num = RandomInt(3, 5);
    for (auto i = 0; i < num; ++i) {
        p_name_stream.str("");
        p_name_stream << "partition_" << i;
        pp_ctx.name = p_name_stream.str();
        ss = CreatePartition(ss->GetName(), pp_ctx, next_lsn());
        ASSERT_TRUE(ss);
    }
    ASSERT_EQ(ss->NumberOfPartitions(), num + 1);

    sf_collector = std::make_shared<SegmentFileCollector>(ss, filter2);
    sf_collector->Iterate();
    auto prev_total = sf_collector->segment_files_.size();

612 613 614 615
    decltype(sf_context) osf_context;
    SFContextBuilder(osf_context, ss, {sf_context.field_element_name});
    std::vector<SegmentFileContext> sfs_context = {sf_context, osf_context};

616 617 618 619
    auto new_total = 0;
    auto partitions = ss->GetResources<Partition>();
    for (auto& kv : partitions) {
        num = RandomInt(2, 5);
620
        auto row_cnt = 1024;
621
        for (auto i = 0; i < num; ++i) {
622
            ASSERT_TRUE(CreateSegment(ss, kv.first, next_lsn(), sfs_context, row_cnt).ok());
623
        }
624
        new_total += num * sfs_context.size();
625 626
    }

627 628
    status = Snapshots::GetInstance().GetSnapshot(ss, ss->GetName());
    ASSERT_TRUE(status.ok());
629
    std::cout << ss->ToString() << std::endl;
630

631 632 633 634 635
    sf_collector = std::make_shared<SegmentFileCollector>(ss, filter2);
    sf_collector->Iterate();
    auto total = sf_collector->segment_files_.size();
    ASSERT_EQ(total, prev_total + new_total);

636 637 638 639 640 641 642 643
    std::set<ID_TYPE> fe_ids;

    for (auto ctx : sfs_context) {
        auto field_element_id = ss->GetFieldElementId(ctx.field_name,
                ctx.field_element_name);
        ASSERT_NE(field_element_id, 0);
        fe_ids.insert(field_element_id);
    }
644

645
    auto filter3 = [&](SegmentFile::Ptr segment_file) -> bool {
646
        return fe_ids.find(segment_file->GetFieldElementId()) != fe_ids.end();
647 648 649 650 651
    };
    sf_collector = std::make_shared<SegmentFileCollector>(ss, filter3);
    sf_collector->Iterate();
    auto specified_segment_files_cnt = sf_collector->segment_files_.size();

652 653
    OperationContext d_a_i_ctx;
    d_a_i_ctx.lsn = next_lsn();
654 655 656
    for (auto fe_id : fe_ids) {
        d_a_i_ctx.stale_field_elements.push_back(ss->GetResource<FieldElement>(fe_id));
    }
657

658 659 660 661 662 663 664
    auto drop_all_index_op = std::make_shared<DropAllIndexOperation>(d_a_i_ctx, ss);
    status = drop_all_index_op->Push();
    ASSERT_TRUE(status.ok());

    status = drop_all_index_op->GetSnapshot(ss);
    ASSERT_TRUE(status.ok());

W
Wang XiangYu 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
    /* { */
    /*     auto& fields = ss->GetResources<Field>(); */
    /*     for (auto field_kv : fields) { */
    /*         auto field = field_kv.second; */
    /*         std::cout << "field " << field->GetID() << " " << field->GetName() << std::endl; */
    /*         auto& field_elements = ss->GetResources<FieldElement>(); */
    /*         for (auto element_kv : field_elements) { */
    /*             auto element = element_kv.second; */
    /*             if (element->GetFieldId() != field->GetID()) { */
    /*                 continue; */
    /*             } */
    /*             std::cout << "\tfield_element " << element->GetID() << " " << element->GetName() << std::endl; */
    /*         } */
    /*     } */
    /* } */

681
    std::cout << ss->ToString() << std::endl;
682 683
    sf_collector = std::make_shared<SegmentFileCollector>(ss, filter2);
    sf_collector->Iterate();
684
    ASSERT_EQ(sf_collector->segment_files_.size(), total - specified_segment_files_cnt);
685 686 687
    std::cout << "sf size = " << sf_collector->segment_files_.size() << std::endl;
    std::cout << "total = " << total << std::endl;
    std::cout << "specified_segment_files_cnt = " << specified_segment_files_cnt << std::endl;
688 689 690 691

    {
        auto& field_elements = ss->GetResources<FieldElement>();
        for (auto& kv : field_elements) {
692
            ASSERT_EQ(fe_ids.find(kv.second->GetID()), fe_ids.end());
693 694
        }
    }
695 696
}

697
TEST_F(SnapshotTest, OperationTest) {
698
    std::string to_string;
699
    LSN_TYPE lsn;
700
    Status status;
701

702 703 704 705 706
    /* ID_TYPE collection_id; */
    /* ASSERT_TRUE(GetFirstCollectionID(collection_id).ok()); */
    std::string collection_name("c1");
    auto ss = CreateCollection(collection_name, ++lsn);
    ASSERT_TRUE(ss);
707

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    SegmentFileContext sf_context;
    SFContextBuilder(sf_context, ss);

    auto& partitions = ss->GetResources<Partition>();
    auto total_row_cnt = 0;
    for (auto& kv : partitions) {
        auto num = RandomInt(2, 5);
        for (auto i = 0; i < num; ++i) {
            auto row_cnt = RandomInt(100, 200);
            ASSERT_TRUE(CreateSegment(ss, kv.first, ++lsn, sf_context, row_cnt).ok());
            total_row_cnt += row_cnt;
        }
    }

    status = Snapshots::GetInstance().GetSnapshot(ss, collection_name);
723
    ASSERT_TRUE(status.ok());
724 725
    ASSERT_EQ(total_row_cnt, ss->GetCollectionCommit()->GetRowCount());

726 727
    auto total_size = ss->GetCollectionCommit()->GetSize();

728
    auto ss_id = ss->GetID();
X
XuPeng-SH 已提交
729
    lsn = ss->GetMaxLsn() + 1;
730 731

    // Check snapshot
732
    {
C
Cai Yudong 已提交
733
        auto collection_commit = CollectionCommitsHolder::GetInstance().GetResource(ss_id, false);
734 735
        /* snapshot::SegmentCommitsHolder::GetInstance().GetResource(prev_segment_commit->GetID()); */
        ASSERT_TRUE(collection_commit);
736
        std::cout << collection_commit->ToString() << std::endl;
737
    }
738

739
    OperationContext merge_ctx;
740 741
    auto merge_segment_row_cnt = 0;

742
    std::set<ID_TYPE> stale_segment_commit_ids;
743 744 745
    SFContextBuilder(sf_context, ss);

    std::cout << ss->ToString() << std::endl;
746

C
Cai Yudong 已提交
747 748
    ID_TYPE new_seg_id;
    ScopedSnapshotT new_ss;
749 750
    // Check build operation correctness
    {
751
        OperationContext context;
X
XuPeng-SH 已提交
752
        context.lsn = ++lsn;
753
        auto build_op = std::make_shared<ChangeSegmentFileOperation>(context, ss);
754
        SegmentFilePtr seg_file;
755
        status = build_op->CommitNewSegmentFile(sf_context, seg_file);
756
        std::cout << status.ToString() << std::endl;
757 758
        ASSERT_TRUE(status.ok());
        ASSERT_TRUE(seg_file);
759
        auto prev_segment_commit = ss->GetSegmentCommitBySegmentId(seg_file->GetSegmentId());
760
        auto prev_segment_commit_mappings = prev_segment_commit->GetMappings();
C
Cai Yudong 已提交
761
        ASSERT_FALSE(prev_segment_commit->ToString().empty());
762

763 764 765 766
        auto new_size = RandomInt(1000, 20000);
        seg_file->SetSize(new_size);
        total_size += new_size;

767 768 769 770
        auto delta = prev_segment_commit->GetRowCount() / 2;
        build_op->CommitRowCountDelta(delta);
        total_row_cnt -= delta;

771 772
        build_op->Push();
        status = build_op->GetSnapshot(ss);
773
        ASSERT_TRUE(status.ok());
C
Cai Yudong 已提交
774
        ASSERT_GT(ss->GetID(), ss_id);
775
        ASSERT_EQ(ss->GetCollectionCommit()->GetRowCount(), total_row_cnt);
776
        ASSERT_EQ(ss->GetCollectionCommit()->GetSize(), total_size);
777
        std::cout << ss->ToString() << std::endl;
778

779
        auto segment_commit = ss->GetSegmentCommitBySegmentId(seg_file->GetSegmentId());
780
        auto segment_commit_mappings = segment_commit->GetMappings();
781
        MappingT expected_mappings = prev_segment_commit_mappings;
782 783 784
        expected_mappings.insert(seg_file->GetID());
        ASSERT_EQ(expected_mappings, segment_commit_mappings);

785
        auto seg = ss->GetResource<Segment>(seg_file->GetSegmentId());
786 787
        ASSERT_TRUE(seg);
        merge_ctx.stale_segments.push_back(seg);
788 789
        merge_segment_row_cnt += ss->GetSegmentCommitBySegmentId(seg->GetID())->GetRowCount();

790 791 792
        stale_segment_commit_ids.insert(segment_commit->GetID());
    }

793 794 795 796 797 798
//    std::this_thread::sleep_for(std::chrono::milliseconds(100));
//    // Check stale snapshot has been deleted from store
//    {
//        auto collection_commit = CollectionCommitsHolder::GetInstance().GetResource(ss_id, false);
//        ASSERT_FALSE(collection_commit);
//    }
799

800
    ss_id = ss->GetID();
801
    ID_TYPE partition_id;
802
    {
803 804 805 806 807 808 809 810 811 812 813 814
        std::vector<PartitionPtr> partitions;
        auto executor = [&](const PartitionPtr& partition,
                            PartitionIterator* itr) -> Status {
            if (partition->GetCollectionId() != ss->GetCollectionId()) {
                return Status::OK();
            }
            partitions.push_back(partition);
            return Status::OK();
        };
        auto iterator = std::make_shared<PartitionIterator>(ss, executor);
        iterator->Iterate();

815
        OperationContext context;
X
XuPeng-SH 已提交
816
        context.lsn = ++lsn;
817
        context.prev_partition = ss->GetResource<Partition>(partitions[0]->GetID());
818 819
        auto op = std::make_shared<NewSegmentOperation>(context, ss);
        SegmentPtr new_seg;
820 821
        status = op->CommitNewSegment(new_seg);
        ASSERT_TRUE(status.ok());
C
Cai Yudong 已提交
822
        ASSERT_FALSE(new_seg->ToString().empty());
823
        SegmentFilePtr seg_file;
824 825
        status = op->CommitNewSegmentFile(sf_context, seg_file);
        ASSERT_TRUE(status.ok());
826 827 828 829 830 831

        auto new_segment_row_cnt = RandomInt(100, 200);
        status = op->CommitRowCount(new_segment_row_cnt);
        ASSERT_TRUE(status.ok());
        total_row_cnt += new_segment_row_cnt;

832 833 834 835
        auto new_size = new_segment_row_cnt * 5;
        seg_file->SetSize(new_size);
        total_size += new_size;

836 837
        status = op->Push();
        ASSERT_TRUE(status.ok());
X
XuPeng-SH 已提交
838

839
        status = op->GetSnapshot(ss);
C
Cai Yudong 已提交
840
        ASSERT_GT(ss->GetID(), ss_id);
841
        ASSERT_TRUE(status.ok());
842
        ASSERT_EQ(ss->GetCollectionCommit()->GetRowCount(), total_row_cnt);
843
        ASSERT_EQ(ss->GetCollectionCommit()->GetSize(), total_size);
844

845
        auto segment_commit = ss->GetSegmentCommitBySegmentId(seg_file->GetSegmentId());
846
        auto segment_commit_mappings = segment_commit->GetMappings();
847
        MappingT expected_segment_mappings;
848 849
        expected_segment_mappings.insert(seg_file->GetID());
        ASSERT_EQ(expected_segment_mappings, segment_commit_mappings);
850

851
        merge_ctx.stale_segments.push_back(new_seg);
852 853
        merge_segment_row_cnt += ss->GetSegmentCommitBySegmentId(new_seg->GetID())->GetRowCount();

854 855
        partition_id = segment_commit->GetPartitionId();
        stale_segment_commit_ids.insert(segment_commit->GetID());
856
        auto partition = ss->GetResource<Partition>(partition_id);
857 858 859 860
        merge_ctx.prev_partition = partition;
        new_seg_id = seg_file->GetSegmentId();
        new_ss = ss;
    }
861

862
    SegmentPtr merge_seg;
863 864 865 866
    ss_id = ss->GetID();
    {
        auto prev_partition_commit = ss->GetPartitionCommitByPartitionId(partition_id);
        auto expect_null = ss->GetPartitionCommitByPartitionId(11111111);
C
Cai Yudong 已提交
867 868
        ASSERT_FALSE(expect_null);
        ASSERT_FALSE(prev_partition_commit->ToString().empty());
X
XuPeng-SH 已提交
869
        merge_ctx.lsn = ++lsn;
870 871
        auto op = std::make_shared<MergeOperation>(merge_ctx, ss);
        SegmentPtr new_seg;
872 873
        status = op->CommitNewSegment(new_seg);
        sf_context.segment_id = new_seg->GetID();
874
        SegmentFilePtr seg_file;
875 876
        status = op->CommitNewSegmentFile(sf_context, seg_file);
        ASSERT_TRUE(status.ok());
877 878 879 880 881 882 883 884 885 886

        auto new_size = RandomInt(1000, 20000);
        seg_file->SetSize(new_size);
        auto stale_size = 0;
        for (auto& stale_seg : merge_ctx.stale_segments) {
            stale_size += ss->GetSegmentCommitBySegmentId(stale_seg->GetID())->GetSize();
        }
        total_size += new_size;
        total_size -= stale_size;

887
        status = op->Push();
888
        ASSERT_TRUE(status.ok()) << status.ToString();
889 890
        std::cout << op->ToString() << std::endl;
        status = op->GetSnapshot(ss);
C
Cai Yudong 已提交
891
        ASSERT_GT(ss->GetID(), ss_id);
892
        ASSERT_TRUE(status.ok());
893
        ASSERT_EQ(total_size, ss->GetCollectionCommit()->GetSize());
X
XuPeng-SH 已提交
894

895
        auto segment_commit = ss->GetSegmentCommitBySegmentId(new_seg->GetID());
896
        ASSERT_EQ(segment_commit->GetRowCount(), merge_segment_row_cnt);
897
        ASSERT_EQ(segment_commit->GetSize(), new_size);
898 899
        ASSERT_EQ(ss->GetCollectionCommit()->GetRowCount(), total_row_cnt);

900 901 902 903 904 905
        auto new_partition_commit = ss->GetPartitionCommitByPartitionId(partition_id);
        auto new_mappings = new_partition_commit->GetMappings();
        auto prev_mappings = prev_partition_commit->GetMappings();
        auto expected_mappings = prev_mappings;
        for (auto id : stale_segment_commit_ids) {
            expected_mappings.erase(id);
906
        }
907 908 909
        expected_mappings.insert(segment_commit->GetID());
        ASSERT_EQ(expected_mappings, new_mappings);

910
        CollectionCommitsHolder::GetInstance().Dump();
911 912 913 914 915 916 917 918
        merge_seg = new_seg;
    }

    // 1. New seg1, seg2
    // 2. Build seg1 start
    // 3. Merge seg1, seg2 to seg3
    // 4. Commit new seg file of build operation -> Stale Segment Found Here!
    {
919
        OperationContext context;
X
XuPeng-SH 已提交
920
        context.lsn = ++lsn;
921
        auto build_op = std::make_shared<ChangeSegmentFileOperation>(context, new_ss);
922
        SegmentFilePtr seg_file;
923 924 925
        auto new_sf_context = sf_context;
        new_sf_context.segment_id = new_seg_id;
        status = build_op->CommitNewSegmentFile(new_sf_context, seg_file);
C
Cai Yudong 已提交
926
        ASSERT_FALSE(status.ok());
927
    }
928

929 930 931
    {
        OperationContext context;
        context.lsn = ++lsn;
932
        auto op = std::make_shared<ChangeSegmentFileOperation>(context, ss);
933 934 935 936 937 938 939 940 941 942 943 944 945 946
        SegmentFilePtr seg_file;
        auto new_sf_context = sf_context;
        new_sf_context.segment_id = merge_seg->GetID();
        status = op->CommitNewSegmentFile(new_sf_context, seg_file);
        ASSERT_TRUE(status.ok());
        auto prev_sc = ss->GetSegmentCommitBySegmentId(merge_seg->GetID());
        ASSERT_TRUE(prev_sc);
        auto delta = prev_sc->GetRowCount() + 1;
        op->CommitRowCountDelta(delta);
        status = op->Push();
        std::cout << status.ToString() << std::endl;
        ASSERT_FALSE(status.ok());
    }

X
XuPeng-SH 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
    std::string new_fe_name = "fe_index";
    {
        status = Snapshots::GetInstance().GetSnapshot(ss, collection_name);
        ASSERT_TRUE(status.ok());

        auto field = ss->GetField(sf_context.field_name);
        ASSERT_TRUE(field);
        auto new_fe = std::make_shared<FieldElement>(ss->GetCollectionId(),
                field->GetID(), new_fe_name, milvus::engine::FieldElementType::FET_INDEX);

        OperationContext context;
        context.lsn = ++lsn;
        context.new_field_elements.push_back(new_fe);
        auto op = std::make_shared<AddFieldElementOperation>(context, ss);
        status = op->Push();
        ASSERT_TRUE(status.ok());

        status = op->GetSnapshot(ss);
        ASSERT_TRUE(status.ok());

        std::cout << ss->ToString() << std::endl;
    }

    {
        auto snapshot_id = ss->GetID();
        auto field = ss->GetField(sf_context.field_name);
        ASSERT_TRUE(field);
        FieldElementPtr new_fe;
        status = ss->GetFieldElement(sf_context.field_name, new_fe_name, new_fe);
        ASSERT_TRUE(status.ok());
        ASSERT_TRUE(new_fe);

        OperationContext context;
        context.lsn = ++lsn;
        context.new_field_elements.push_back(new_fe);
        auto op = std::make_shared<AddFieldElementOperation>(context, ss);
        status = op->Push();
        ASSERT_FALSE(status.ok());

        status = Snapshots::GetInstance().GetSnapshot(ss, collection_name);
        ASSERT_TRUE(status.ok());
        ASSERT_EQ(snapshot_id, ss->GetID());
    }

991 992 993 994 995
    // 1. Build start
    // 2. Commit new seg file of build operation
    // 3. Drop collection
    // 4. Commit build operation -> Stale Segment Found Here!
    {
996
        OperationContext context;
X
XuPeng-SH 已提交
997
        context.lsn = ++lsn;
998
        auto build_op = std::make_shared<ChangeSegmentFileOperation>(context, ss);
999
        SegmentFilePtr seg_file;
1000 1001 1002 1003 1004 1005
        auto new_sf_context = sf_context;
        new_sf_context.segment_id = merge_seg->GetID();
        status = build_op->CommitNewSegmentFile(new_sf_context, seg_file);
        ASSERT_TRUE(status.ok());
        std::cout << build_op->ToString() << std::endl;

C
Cai Yudong 已提交
1006
        auto status = Snapshots::GetInstance().DropCollection(ss->GetName(), ++lsn);
1007 1008
        ASSERT_TRUE(status.ok());
        status = build_op->Push();
1009
        std::cout << status.ToString() << std::endl;
C
Cai Yudong 已提交
1010 1011
        ASSERT_FALSE(status.ok());
        ASSERT_FALSE(build_op->GetStatus().ok());
1012 1013
        std::cout << build_op->ToString() << std::endl;
    }
X
XuPeng-SH 已提交
1014

1015 1016 1017
    Snapshots::GetInstance().Reset();
}

1018
TEST_F(SnapshotTest, OperationTest2) {
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
    LSN_TYPE lsn = 0;
    std::string collection_name("c1");
    auto ss = CreateCollection(collection_name, ++lsn);
    ASSERT_TRUE(ss);

    SegmentFileContext sf_context;
    SFContextBuilder(sf_context, ss);

    auto& partitions = ss->GetResources<Partition>();
    auto total_row_cnt = 0;
    for (auto& kv : partitions) {
        auto num = RandomInt(2, 5);
        for (auto i = 0; i < num; ++i) {
            auto row_cnt = RandomInt(100, 200);
            ASSERT_TRUE(CreateSegment(ss, kv.first, ++lsn, sf_context, row_cnt).ok());
            total_row_cnt += row_cnt;
        }
    }

    auto status = Snapshots::GetInstance().GetSnapshot(ss, collection_name);
    ASSERT_TRUE(status.ok());
    ASSERT_EQ(total_row_cnt, ss->GetCollectionCommit()->GetRowCount());

    auto total_size = ss->GetCollectionCommit()->GetSize();

    auto target_segment = ss->GetResources<Segment>().begin()->second.Get();

    auto sf_ids = ss->GetSegmentFileIds(target_segment->GetID());
    ASSERT_GT(sf_ids.size(), 0);
    auto stale_sf = ss->GetResource<SegmentFile>(*(sf_ids.begin()));
    ASSERT_TRUE(stale_sf);

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
    {
        OperationContext context;
        context.lsn = ++lsn;
        context.stale_segment_files.push_back(stale_sf);
        auto op = std::make_shared<ChangeSegmentFileOperation>(context, ss);
        SegmentFilePtr seg_file;
        sf_context.field_name = "vector";
        sf_context.field_element_name = "_raw";
        sf_context.segment_id = stale_sf->GetSegmentId();
        sf_context.partition_id = stale_sf->GetPartitionId();
        sf_context.collection_id = stale_sf->GetCollectionId();
        status = op->CommitNewSegmentFile(sf_context, seg_file);
        /* std::cout << status.ToString() << std::endl; */
        ASSERT_TRUE(status.ok());
        ASSERT_TRUE(seg_file);
1066

1067
        auto prev_segment_commit = ss->GetSegmentCommitBySegmentId(seg_file->GetSegmentId());
C
Cai Yudong 已提交
1068
        // auto prev_segment_commit_mappings = prev_segment_commit->GetMappings();
1069
        ASSERT_FALSE(prev_segment_commit->ToString().empty());
1070

1071 1072 1073 1074
        auto new_size = RandomInt(1000, 20000);
        seg_file->SetSize(new_size);
        total_size += new_size;
        total_size -= stale_sf->GetSize();
1075

1076 1077 1078
        auto delta = prev_segment_commit->GetRowCount() / 2;
        op->CommitRowCountDelta(delta);
        total_row_cnt -= delta;
1079

1080 1081 1082 1083 1084 1085 1086 1087
        status = op->Push();
        ASSERT_TRUE(status.ok()) << status.message();
        status = op->GetSnapshot(ss);
        ASSERT_TRUE(status.ok());
        ASSERT_EQ(ss->GetCollectionCommit()->GetRowCount(), total_row_cnt);
        ASSERT_EQ(ss->GetCollectionCommit()->GetSize(), total_size);
        std::cout << ss->ToString() << std::endl;
    }
1088

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    {
        OperationContext context;
        context.lsn = ++lsn;

        SegmentFile::VecT stale_sfs;
        std::set<ID_TYPE> modified_segments;
        auto executor = [&](const SegmentFilePtr& sf,
                            SegmentFileIterator* itr) -> Status {
            context.stale_segment_files.push_back(sf);
            modified_segments.insert(sf->GetSegmentId());
            return Status::OK();
        };
        auto iterator = std::make_shared<SegmentFileIterator>(ss, executor);
        iterator->Iterate();
        ASSERT_TRUE(iterator->GetStatus().ok());

        {
            auto op = std::make_shared<CompoundSegmentsOperation>(context, ss);

            for (auto seg_id : modified_segments) {
                auto sc = ss->GetSegmentCommitBySegmentId(seg_id);
                ASSERT_TRUE(sc);
                status = op->CommitRowCountDelta(seg_id, sc->GetRowCount() + 1, true);
                ASSERT_TRUE(status.ok()) << status.ToString();
            }

            status = op->Push();
            ASSERT_FALSE(status.ok()) << status.ToString();
        }

        {
            auto op = std::make_shared<CompoundSegmentsOperation>(context, ss);
            status = op->CommitRowCountDelta(100000000, 1, false);
            ASSERT_FALSE(status.ok()) << status.ToString();
        }

        {
            auto segment_cnt = ss->GetResources<Segment>().size();
            context.lsn++;
            auto op = std::make_shared<CompoundSegmentsOperation>(context, ss);
            for (auto seg_id : modified_segments) {
                auto sc = ss->GetSegmentCommitBySegmentId(seg_id);
                ASSERT_TRUE(sc);
                bool is_sub = (RandomInt(1, 10) >= 5);
                auto delta = sc->GetRowCount() / 2;
                status = op->CommitRowCountDelta(seg_id, delta, is_sub);
                ASSERT_TRUE(status.ok()) << status.ToString();
                if (is_sub) {
                    total_row_cnt -= delta;
                } else {
                    total_row_cnt += delta;
                }
            }

            auto new_size = 0;
            for (auto stale_sf : context.stale_segment_files) {
                SegmentFilePtr seg_file;
                sf_context.field_name = "vector";
                sf_context.field_element_name = "_raw";
                sf_context.segment_id = stale_sf->GetSegmentId();
                sf_context.partition_id = stale_sf->GetPartitionId();
                sf_context.collection_id = stale_sf->GetCollectionId();
                status = op->CommitNewSegmentFile(sf_context, seg_file);
                auto size_delta = RandomInt(100, 1000);
                seg_file->SetSize(size_delta);
                new_size += size_delta;
                ASSERT_TRUE(status.ok()) << status.ToString();
            }

            SegmentPtr new_seg;
            OperationContext new_seg_ctx;
            new_seg_ctx.prev_partition = ss->GetResource<Partition>(
                    context.stale_segment_files[0]->GetPartitionId());
            status = op->CommitNewSegment(new_seg_ctx, new_seg);
            ASSERT_TRUE(status.ok()) << status.ToString();
            ASSERT_TRUE(new_seg);

            {
                SegmentFilePtr seg_file;
                sf_context.field_name = "vector";
                sf_context.field_element_name = "_raw";
                sf_context.segment_id = new_seg->GetID();
                sf_context.partition_id = new_seg->GetPartitionId();
                sf_context.collection_id = new_seg->GetCollectionId();
                status = op->CommitNewSegmentFile(sf_context, seg_file);
                ASSERT_TRUE(status.ok()) << status.ToString();
                auto size_delta = RandomInt(100, 1000);
                seg_file->SetSize(size_delta);
                new_size += size_delta;
                ASSERT_TRUE(status.ok()) << status.ToString();
            }

            auto delta_row = RandomInt(100, 1000);
            status = op->CommitRowCountDelta(new_seg->GetID(), delta_row, false);
            ASSERT_TRUE(status.ok());
            total_row_cnt += delta_row;

            status = op->Push();
            ASSERT_TRUE(status.ok()) << status.ToString();
            status = op->GetSnapshot(ss);
            ASSERT_TRUE(status.ok());
            std::cout << ss->ToString() << std::endl;
            ASSERT_EQ(segment_cnt + 1, ss->GetResources<Segment>().size());

            auto expect_size = ss->GetCollectionCommit()->GetSize();
            ASSERT_EQ(expect_size, new_size) << status.ToString();
            auto expect_row_cnt = ss->GetCollectionCommit()->GetRowCount();
            ASSERT_EQ(expect_row_cnt, total_row_cnt) << status.ToString();
        }

        {
            modified_segments.clear();
            context.stale_segment_files.clear();
            iterator = std::make_shared<SegmentFileIterator>(ss, executor);
            iterator->Iterate();
            ASSERT_TRUE(iterator->GetStatus().ok());

            context.lsn++;
            auto op = std::make_shared<CompoundSegmentsOperation>(context, ss);

            for (auto seg_id : modified_segments) {
                auto sc = ss->GetSegmentCommitBySegmentId(seg_id);
                ASSERT_TRUE(sc);
                status = op->CommitRowCountDelta(seg_id, sc->GetRowCount(), true);
                ASSERT_TRUE(status.ok()) << status.ToString();
            }

            status = op->Push();
            ASSERT_TRUE(status.ok()) << status.ToString();

            status = op->GetSnapshot(ss);
            ASSERT_TRUE(status.ok());
            std::cout << ss->ToString() << std::endl;
            ASSERT_EQ(ss->GetCollectionCommit()->GetRowCount(), 0);
            ASSERT_EQ(ss->GetCollectionCommit()->GetSize(), 0);
        }
    }
1226 1227
}

1228
TEST_F(SnapshotTest, CompoundTest1) {
1229
    Status status;
X
XuPeng-SH 已提交
1230
    std::atomic<LSN_TYPE> lsn = 0;
1231 1232 1233
    auto next_lsn = [&]() -> decltype(lsn) {
        return ++lsn;
    };
1234
    std::atomic<LSN_TYPE> pid = 0;
1235 1236 1237
    auto next_pid = [&]() -> decltype(pid) {
        return ++pid;
    };
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
    std::string collection_name("c1");
    auto ss = CreateCollection(collection_name, next_lsn());
    ASSERT_TRUE(ss);
    ASSERT_EQ(lsn, ss->GetMaxLsn());

    Queue merge_queue;
    Queue build_queue;

    std::set<ID_TYPE> all_segments;
    std::set<ID_TYPE> segment_in_building;
1248 1249
    std::map<ID_TYPE, std::set<ID_TYPE>> merged_segs_history;
    std::set<ID_TYPE> merged_segs;
1250
    std::set<ID_TYPE> built_segs;
1251
    std::set<ID_TYPE> build_stale_segs;
1252 1253

    std::mutex all_mtx;
1254 1255 1256
    std::mutex merge_mtx;
    std::mutex built_mtx;
    std::mutex partition_mtx;
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266

    WaitableObj merge_waiter;
    WaitableObj build_waiter;

    SegmentFileContext sf_context;
    sf_context.field_name = "vector";
    sf_context.field_element_name = "ivfsq8";
    sf_context.segment_id = 1;
    sf_context.partition_id = 1;

1267 1268
    IDS_TYPE partitions = {ss->GetResources<Partition>().begin()->second->GetID()};

1269
    auto do_build = [&] (const ID_TYPE& seg_id) {
C
Cai Yudong 已提交
1270
        ScopedSnapshotT latest_ss;
1271 1272 1273 1274 1275 1276 1277
        auto status = Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
        ASSERT_TRUE(status.ok());

        auto build_sf_context = sf_context;

        OperationContext context;
        context.lsn = next_lsn();
1278
        auto build_op = std::make_shared<ChangeSegmentFileOperation>(context, latest_ss);
1279 1280 1281
        SegmentFilePtr seg_file;
        build_sf_context.segment_id = seg_id;
        status = build_op->CommitNewSegmentFile(build_sf_context, seg_file);
1282 1283 1284 1285 1286 1287 1288 1289
        if (!status.ok()) {
            std::cout << status.ToString() << std::endl;
            std::unique_lock<std::mutex> lock(merge_mtx);
            auto it = merged_segs.find(seg_id);
            ASSERT_NE(it, merged_segs.end());
            return;
        }
        std::unique_lock<std::mutex> lock(built_mtx);
1290
        status = build_op->Push();
1291 1292 1293 1294 1295 1296 1297
        if (!status.ok()) {
            std::cout << status.ToString() << std::endl;
            std::unique_lock<std::mutex> lock(merge_mtx);
            auto it = merged_segs.find(seg_id);
            ASSERT_NE(it, merged_segs.end());
            return;
        }
1298 1299 1300
        ASSERT_TRUE(status.ok());
        status = build_op->GetSnapshot(latest_ss);
        ASSERT_TRUE(status.ok());
1301

1302 1303 1304 1305 1306 1307 1308
        built_segs.insert(seg_id);
    };

    auto do_merge = [&] (std::set<ID_TYPE>& seg_ids, ID_TYPE& new_seg_id) {
        if (seg_ids.size() == 0) {
            return;
        }
C
Cai Yudong 已提交
1309
        ScopedSnapshotT latest_ss;
1310 1311 1312
        auto status = Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
        ASSERT_TRUE(status.ok());

1313
        PartitionPtr partition;
1314 1315 1316 1317 1318 1319 1320
        OperationContext context;
        for (auto& id : seg_ids) {
            auto seg = latest_ss->GetResource<Segment>(id);
            if (!seg) {
                std::cout << "Error seg=" << id << std::endl;
                ASSERT_TRUE(seg);
            }
1321 1322 1323 1324 1325 1326
            if (!partition) {
                partition = latest_ss->GetResource<Partition>(seg->GetPartitionId());
                ASSERT_TRUE(partition);
            } else {
                ASSERT_EQ(seg->GetPartitionId(), partition->GetID());
            }
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
            context.stale_segments.push_back(seg);
            if (!context.prev_partition) {
                context.prev_partition = latest_ss->GetResource<Partition>(
                        seg->GetPartitionId());
            }
        }

        context.lsn = next_lsn();
        auto op = std::make_shared<MergeOperation>(context, latest_ss);
        SegmentPtr new_seg;
        status = op->CommitNewSegment(new_seg);
        ASSERT_TRUE(status.ok());
        sf_context.segment_id = new_seg->GetID();
        SegmentFilePtr seg_file;
        status = op->CommitNewSegmentFile(sf_context, seg_file);
        ASSERT_TRUE(status.ok());
1343
        std::unique_lock<std::mutex> lock(merge_mtx);
1344
        status = op->Push();
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
        if (!status.ok()) {
            lock.unlock();
            std::unique_lock<std::mutex> blk(built_mtx);
            std::cout << status.ToString() << std::endl;
            /* for (auto id : built_segs) { */
            /*     std::cout << "builted " << id << std::endl; */
            /* } */
            /* for (auto id : seg_ids) { */
            /*     std::cout << "to_merge " << id << std::endl; */
            /* } */
            bool stale_found = false;
            for (auto& seg_id : seg_ids) {
                auto it = built_segs.find(seg_id);
                if (it != built_segs.end()) {
                    stale_found = true;
                    break;
                }
            }
            ASSERT_TRUE(stale_found);
            return;
        }
1366 1367 1368 1369
        ID_TYPE ss_id = latest_ss->GetID();
        status = op->GetSnapshot(latest_ss);
        ASSERT_TRUE(status.ok());
        ASSERT_TRUE(latest_ss->GetID() > ss_id);
1370 1371 1372 1373 1374

        merged_segs_history[new_seg->GetID()] = seg_ids;
        for (auto& seg_id : seg_ids) {
            merged_segs.insert(seg_id);
        }
1375
        new_seg_id = new_seg->GetID();
1376
        ASSERT_EQ(new_seg->GetPartitionId(), partition->GetID());
1377 1378 1379 1380
    };

    // TODO: If any Compound Operation find larger Snapshot. This Operation should be rollback to latest
    auto handler_worker = [&] {
1381
        auto loop_cnt = RandomInt(10, 20);
C
Cai Yudong 已提交
1382
        ScopedSnapshotT latest_ss;
1383

1384 1385 1386 1387 1388 1389 1390
        auto create_new_segment = [&]() {
            ID_TYPE partition_id;
            {
                std::unique_lock<std::mutex> lock(partition_mtx);
                auto idx = RandomInt(0, partitions.size() - 1);
                partition_id = partitions[idx];
            }
1391 1392
            Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
            OperationContext context;
1393
            context.prev_partition = latest_ss->GetResource<Partition>(partition_id);
1394 1395 1396
            context.lsn = next_lsn();
            auto op = std::make_shared<NewSegmentOperation>(context, latest_ss);
            SegmentPtr new_seg;
X
XuPeng-SH 已提交
1397
            auto status = op->CommitNewSegment(new_seg);
1398 1399 1400
            if (!status.ok()) {
                std::cout << status.ToString() << std::endl;
            }
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
            ASSERT_TRUE(status.ok());
            SegmentFilePtr seg_file;
            sf_context.segment_id = new_seg->GetID();
            op->CommitNewSegmentFile(sf_context, seg_file);
            op->Push();
            status = op->GetSnapshot(latest_ss);
            ASSERT_TRUE(status.ok());

            {
                std::unique_lock<std::mutex> lock(all_mtx);
                all_segments.insert(new_seg->GetID());
            }
1413 1414 1415
            if (RandomInt(0, 10) >= 7) {
                build_queue.Put(new_seg->GetID());
            }
1416
            merge_queue.Put(new_seg->GetID());
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
        };

        auto create_partition = [&]() {
            std::stringstream ss;
            ss << "fake_partition_" << next_pid();
            PartitionContext context;
            context.name = ss.str();
            std::unique_lock<std::mutex> lock(partition_mtx);
            auto latest_ss = CreatePartition(collection_name, context, next_lsn());
            ASSERT_TRUE(latest_ss);
            auto partition = latest_ss->GetPartition(ss.str());
            partitions.push_back(partition->GetID());
            if (latest_ss->NumberOfPartitions() != partitions.size()) {
                for (auto& pid : partitions) {
                    std::cout << "PartitionId=" << pid << std::endl;
                }
            }
            ASSERT_EQ(latest_ss->NumberOfPartitions(), partitions.size());
        };

        for (auto i = 0; i < loop_cnt; ++i) {
            if (RandomInt(0, 10) > 7) {
                create_partition();
            }
            create_new_segment();
1442 1443 1444
        }
    };

1445
    std::map<ID_TYPE, std::set<ID_TYPE>> merge_segs;
1446 1447 1448 1449 1450 1451 1452
    auto merge_worker = [&] {
        while (true) {
            auto seg_id = merge_queue.Take();
            if (seg_id == 0) {
                std::cout << "Exiting Merge Worker" << std::endl;
                break;
            }
C
Cai Yudong 已提交
1453
            ScopedSnapshotT latest_ss;
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
            auto status = Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
            ASSERT_TRUE(status.ok());
            auto seg = latest_ss->GetResource<Segment>(seg_id);
            if (!seg) {
                std::cout << "SegID=" << seg_id << std::endl;
                std::cout << latest_ss->ToString() << std::endl;
                ASSERT_TRUE(seg);
            }

            auto it_segs = merge_segs.find(seg->GetPartitionId());
            if (it_segs == merge_segs.end()) {
                merge_segs[seg->GetPartitionId()] = {seg->GetID()};
            } else {
                merge_segs[seg->GetPartitionId()].insert(seg->GetID());
            }
            auto& segs = merge_segs[seg->GetPartitionId()];
            if ((segs.size() >= 2) && (RandomInt(0, 10) >= 2)) {
                std::cout << "Merging partition " << seg->GetPartitionId() << " segs (";
                for (auto seg : segs) {
1473 1474 1475 1476
                    std::cout << seg << ",";
                }
                std::cout << ")" << std::endl;
                ID_TYPE new_seg_id = 0;
1477 1478 1479 1480 1481 1482
                do_merge(segs, new_seg_id);
                segs.clear();
                if (new_seg_id == 0) {
                    continue;
                }
                if (RandomInt(0, 10) >= 6) {
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
                    build_queue.Put(new_seg_id);
                }

            } else {
                continue;
            }
        }
        merge_waiter.Notify();
        build_queue.Put(0);
        build_waiter.Wait();
    };

    auto build_worker = [&] {
        while (true) {
            auto seg_id = build_queue.Take();
            if (seg_id == 0) {
                std::cout << "Exiting Build Worker" << std::endl;
                break;
            }

            std::cout << "Building " << seg_id << std::endl;
            do_build(seg_id);
        }
        build_waiter.Notify();
    };
    std::vector<std::thread> handlers;
    auto num_handlers = RandomInt(8, 9);
    for (auto i = 0; i < num_handlers; ++i) {
        handlers.emplace_back(handler_worker);
    }
    std::thread t3 = std::thread(merge_worker);
    std::thread t4 = std::thread(build_worker);

    for (auto& handler : handlers) {
        handler.join();
    }

    merge_queue.Put(0);
    t3.join();
    t4.join();

1524
    /* for (auto& kv : merged_segs_history) { */
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
    /*     std::cout << "merged: ("; */
    /*     for (auto i : kv.second) { */
    /*         std::cout << i << ","; */
    /*     } */
    /*     std::cout << ") -> " << kv.first << std::endl; */
    /* } */

    /* for (auto& id : built_segs) { */
    /*     std::cout << "built: " << id << std::endl; */
    /* } */

    merge_waiter.Wait();

C
Cai Yudong 已提交
1538
    ScopedSnapshotT latest_ss;
1539 1540 1541
    status = Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
    ASSERT_TRUE(status.ok());
    auto expect_segments = all_segments;
1542
    for (auto& kv : merged_segs_history) {
1543 1544 1545 1546 1547
        expect_segments.insert(kv.first);
        for (auto& id : kv.second) {
            expect_segments.erase(id);
        }
    }
C
Cai Yudong 已提交
1548
    std::set<ID_TYPE> final_segments;
1549 1550 1551 1552 1553 1554 1555 1556
    auto segments = latest_ss->GetResources<Segment>();
    for (auto& kv : segments) {
        final_segments.insert(kv.first);
    }
    ASSERT_EQ(final_segments, expect_segments);

    auto final_segment_file_cnt = latest_ss->GetResources<SegmentFile>().size();

C
Cai Yudong 已提交
1557
    size_t expect_segment_file_cnt;
1558 1559
    expect_segment_file_cnt = expect_segments.size();
    expect_segment_file_cnt += built_segs.size();
1560 1561 1562 1563 1564
    std::cout << latest_ss->ToString() << std::endl;
    std::vector<int> common_ids;
    std::set_intersection(merged_segs.begin(), merged_segs.end(), built_segs.begin(), built_segs.end(),
            std::back_inserter(common_ids));
    expect_segment_file_cnt -= common_ids.size();
1565
    ASSERT_EQ(expect_segment_file_cnt, final_segment_file_cnt);
1566
}
X
XuPeng-SH 已提交
1567 1568 1569


TEST_F(SnapshotTest, CompoundTest2) {
1570
    Status status;
X
XuPeng-SH 已提交
1571
    LSN_TYPE lsn = 0;
C
Cai Yudong 已提交
1572
    auto next_lsn = [&]() -> LSN_TYPE& {
X
XuPeng-SH 已提交
1573 1574
        return ++lsn;
    };
1575
    std::atomic<LSN_TYPE> pid = 0;
C
Cai Yudong 已提交
1576
    auto next_pid = [&]() -> LSN_TYPE {
X
XuPeng-SH 已提交
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
        return ++pid;
    };
    std::string collection_name("c1");
    auto ss = CreateCollection(collection_name, next_lsn());
    ASSERT_TRUE(ss);
    ASSERT_EQ(lsn, ss->GetMaxLsn());

    TQueue merge_queue;
    TQueue build_queue;

    std::set<ID_TYPE> all_segments;
    std::set<ID_TYPE> segment_in_building;
    std::map<ID_TYPE, std::set<ID_TYPE>> merged_segs_history;
    std::set<ID_TYPE> merged_segs;
    std::set<ID_TYPE> built_segs;
    std::set<ID_TYPE> build_stale_segs;

    std::mutex all_mtx;
    std::mutex merge_mtx;
    std::mutex built_mtx;
    std::mutex partition_mtx;
    std::mutex seg_p_mtx;

    WaitableObj merge_waiter;
    WaitableObj build_waiter;

    SegmentFileContext sf_context;
    sf_context.field_name = "vector";
    sf_context.field_element_name = "ivfsq8";
    sf_context.segment_id = 1;
    sf_context.partition_id = 1;

    IDS_TYPE partitions = {ss->GetResources<Partition>().begin()->second->GetID()};
    std::set<ID_TYPE> stale_partitions;
    std::map<ID_TYPE, ID_TYPE> seg_p_map;

    auto do_build = [&] (const ID_TYPE& seg_id, const ID_TYPE& p_id) {
C
Cai Yudong 已提交
1614
        ScopedSnapshotT latest_ss;
X
XuPeng-SH 已提交
1615 1616 1617 1618 1619 1620 1621
        auto status = Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
        ASSERT_TRUE(status.ok());

        auto build_sf_context = sf_context;

        OperationContext context;
        context.lsn = next_lsn();
1622
        auto build_op = std::make_shared<ChangeSegmentFileOperation>(context, latest_ss);
X
XuPeng-SH 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
        SegmentFilePtr seg_file;
        build_sf_context.segment_id = seg_id;
        status = build_op->CommitNewSegmentFile(build_sf_context, seg_file);
        if (!status.ok()) {
            std::cout << status.ToString() << std::endl;
            {
                std::unique_lock<std::mutex> lock(partition_mtx);
                auto it = stale_partitions.find(p_id);
                if (it != stale_partitions.end()) {
                    std::cout << "Segment " << seg_id << " host partition " << p_id << " is stale" << std::endl;
                    return;
                }
            }
            std::unique_lock<std::mutex> lock(merge_mtx);
            auto it = merged_segs.find(seg_id);
            ASSERT_NE(it, merged_segs.end());
            return;
        }
        std::unique_lock<std::mutex> lock(built_mtx);
        status = build_op->Push();
        if (!status.ok()) {
            lock.unlock();
            std::cout << status.ToString() << std::endl;
            {
                std::unique_lock<std::mutex> lock(partition_mtx);
                auto it = stale_partitions.find(p_id);
                if (it != stale_partitions.end()) {
                    std::cout << "Segment " << seg_id << " host partition " << p_id << " is stale" << std::endl;
                    return;
                }
            }
            std::unique_lock<std::mutex> lock(merge_mtx);
            auto it = merged_segs.find(seg_id);
            ASSERT_NE(it, merged_segs.end());
            return;
        }
        ASSERT_TRUE(status.ok());
        status = build_op->GetSnapshot(latest_ss);
        ASSERT_TRUE(status.ok());

        built_segs.insert(seg_id);
    };

    auto do_merge = [&] (std::set<ID_TYPE>& seg_ids, ID_TYPE& new_seg_id, const ID_TYPE& p_id) {
        if (seg_ids.size() == 0) {
            return;
        }
C
Cai Yudong 已提交
1670
        ScopedSnapshotT latest_ss;
X
XuPeng-SH 已提交
1671 1672 1673 1674 1675 1676 1677 1678
        auto status = Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
        ASSERT_TRUE(status.ok());

        PartitionPtr partition;
        OperationContext context;
        for (auto& id : seg_ids) {
            auto seg = latest_ss->GetResource<Segment>(id);
            if (!seg) {
X
XuPeng-SH 已提交
1679 1680 1681 1682 1683 1684
                std::cout << "Stale seg=" << id << std::endl;
                std::unique_lock<std::mutex> lock(partition_mtx);
                std::cout << ((stale_partitions.find(p_id) != stale_partitions.end()) ? " due stale partition"
                        : " unexpected") << std::endl;
                ASSERT_TRUE(stale_partitions.find(p_id) != stale_partitions.end());
                return;
X
XuPeng-SH 已提交
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757
            }
            if (!partition) {
                partition = latest_ss->GetResource<Partition>(seg->GetPartitionId());
                ASSERT_TRUE(partition);
            } else {
                ASSERT_EQ(seg->GetPartitionId(), partition->GetID());
            }
            context.stale_segments.push_back(seg);
            if (!context.prev_partition) {
                context.prev_partition = latest_ss->GetResource<Partition>(
                        seg->GetPartitionId());
            }
        }

        context.lsn = next_lsn();
        auto op = std::make_shared<MergeOperation>(context, latest_ss);
        SegmentPtr new_seg;
        status = op->CommitNewSegment(new_seg);
        ASSERT_TRUE(status.ok());
        sf_context.segment_id = new_seg->GetID();
        SegmentFilePtr seg_file;
        status = op->CommitNewSegmentFile(sf_context, seg_file);
        ASSERT_TRUE(status.ok());
        std::unique_lock<std::mutex> lock(merge_mtx);
        status = op->Push();
        if (!status.ok()) {
            lock.unlock();
            bool stale_found = false;
            {
                std::unique_lock<std::mutex> blk(built_mtx);
                std::cout << status.ToString() << std::endl;
                /* for (auto id : built_segs) { */
                /*     std::cout << "builted " << id << std::endl; */
                /* } */
                /* for (auto id : seg_ids) { */
                /*     std::cout << "to_merge " << id << std::endl; */
                /* } */
                for (auto& seg_id : seg_ids) {
                    auto it = built_segs.find(seg_id);
                    if (it != built_segs.end()) {
                        stale_found = true;
                        break;
                    }
                }
            }
            if (!stale_found) {
                std::unique_lock<std::mutex> lock(partition_mtx);
                auto it = stale_partitions.find(p_id);
                if (it != stale_partitions.end()) {
                    /* std::cout << "Segment " << seg_id << " host partition " << p_id << " is stale" << std::endl; */
                    stale_found = true;
                }
            }

            ASSERT_TRUE(stale_found);
            return;
        }
        ID_TYPE ss_id = latest_ss->GetID();
        status = op->GetSnapshot(latest_ss);
        ASSERT_TRUE(status.ok());
        ASSERT_TRUE(latest_ss->GetID() > ss_id);

        merged_segs_history[new_seg->GetID()] = seg_ids;
        for (auto& seg_id : seg_ids) {
            merged_segs.insert(seg_id);
        }
        new_seg_id = new_seg->GetID();
        seg_p_map[new_seg_id] = new_seg->GetPartitionId();
        ASSERT_EQ(new_seg->GetPartitionId(), partition->GetID());
    };

    auto handler_worker = [&] {
        auto loop_cnt = RandomInt(30, 35);
C
Cai Yudong 已提交
1758
        ScopedSnapshotT latest_ss;
X
XuPeng-SH 已提交
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772

        auto create_new_segment = [&]() {
            ID_TYPE partition_id;
            {
                std::unique_lock<std::mutex> lock(partition_mtx);
                auto idx = RandomInt(0, partitions.size() - 1);
                partition_id = partitions[idx];
            }
            Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
            OperationContext context;
            context.prev_partition = latest_ss->GetResource<Partition>(partition_id);
            context.lsn = next_lsn();
            auto op = std::make_shared<NewSegmentOperation>(context, latest_ss);
            SegmentPtr new_seg;
X
XuPeng-SH 已提交
1773
            auto status = op->CommitNewSegment(new_seg);
X
XuPeng-SH 已提交
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
            if (!status.ok()) {
                std::cout << status.ToString() << std::endl;
                std::unique_lock<std::mutex> lock(partition_mtx);
                ASSERT_TRUE(stale_partitions.find(partition_id) != stale_partitions.end());
                return;
            }
            ASSERT_TRUE(status.ok());
            SegmentFilePtr seg_file;
            sf_context.segment_id = new_seg->GetID();
            status = op->CommitNewSegmentFile(sf_context, seg_file);
            if (!status.ok()) {
                std::cout << status.ToString() << std::endl;
                ASSERT_TRUE(status.ok());
            }
            status = op->Push();
            if (!status.ok()) {
                std::unique_lock<std::mutex> lock(partition_mtx);
X
XuPeng-SH 已提交
1791 1792 1793 1794 1795 1796
                /* if (stale_partitions.find(partition_id) == stale_partitions.end()) { */
                /*     for (auto p : stale_partitions) { */
                /*         std::cout << "stale p: " << p << std::endl; */
                /*     } */
                /*     ASSERT_TRUE(false); */
                /* } */
X
XuPeng-SH 已提交
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841
                ASSERT_TRUE(stale_partitions.find(partition_id) != stale_partitions.end());
                return;
            }
            status = op->GetSnapshot(latest_ss);
            if (!status.ok()) {
                std::cout << status.ToString() << std::endl;
                std::unique_lock<std::mutex> lock(partition_mtx);
                ASSERT_TRUE(stale_partitions.find(partition_id) != stale_partitions.end());
                return;
            }

            {
                std::unique_lock<std::mutex> lock(all_mtx);
                all_segments.insert(new_seg->GetID());
            }
            if (RandomInt(0, 10) >= 7) {
                build_queue.Put({new_seg->GetID(), new_seg->GetPartitionId()});
            }
            seg_p_map[new_seg->GetID()] = new_seg->GetPartitionId();
            merge_queue.Put({new_seg->GetID(), new_seg->GetPartitionId()});
        };

        auto create_partition = [&]() {
            std::stringstream ss;
            ss << "fake_partition_" << next_pid();
            PartitionContext context;
            context.name = ss.str();
            std::unique_lock<std::mutex> lock(partition_mtx);
            auto latest_ss = CreatePartition(collection_name, context, next_lsn());
            ASSERT_TRUE(latest_ss);
            auto partition = latest_ss->GetPartition(ss.str());
            partitions.push_back(partition->GetID());
            if (latest_ss->NumberOfPartitions() != partitions.size()) {
                for (auto& pid : partitions) {
                    std::cout << "PartitionId=" << pid << std::endl;
                }
            }
            ASSERT_EQ(latest_ss->NumberOfPartitions(), partitions.size());
        };

        auto drop_partition = [&]() {
            std::unique_lock<std::mutex> lock(partition_mtx);
            if (partitions.size() <= 2) {
                return;
            }
C
Cai Yudong 已提交
1842
            ScopedSnapshotT latest_ss;
X
XuPeng-SH 已提交
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
            Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
            auto index = RandomInt(0, partitions.size() - 1);
            auto pid = partitions[index];
            std::cout << "Dropping partition " << pid << std::endl;
            status = Snapshots::GetInstance().DropPartition(
                    latest_ss->GetCollectionId(), pid, next_lsn());
            ASSERT_TRUE(status.ok());
            stale_partitions.insert(pid);
            partitions.erase(partitions.begin() + index);
        };

        for (auto i = 0; i < loop_cnt; ++i) {
X
XuPeng-SH 已提交
1855
            if (RandomInt(0, 10) > 5) {
X
XuPeng-SH 已提交
1856 1857
                create_partition();
            }
X
XuPeng-SH 已提交
1858
            if (RandomInt(0, 10) > 7) {
X
XuPeng-SH 已提交
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
                drop_partition();
            }
            create_new_segment();
        }
    };

    std::map<ID_TYPE, std::set<ID_TYPE>> merge_segs;
    auto merge_worker = [&] {
        while (true) {
            auto ids = merge_queue.Take();
            auto seg_id = std::get<0>(ids);
            auto p_id = std::get<1>(ids);
            if (seg_id == 0) {
                std::cout << "Exiting Merge Worker" << std::endl;
                break;
            }
C
Cai Yudong 已提交
1875
            ScopedSnapshotT latest_ss;
X
XuPeng-SH 已提交
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
            auto status = Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
            ASSERT_TRUE(status.ok());
            auto seg = latest_ss->GetResource<Segment>(seg_id);
            if (!seg) {
                std::cout << "SegID=" << seg_id << std::endl;
                std::cout << latest_ss->ToString() << std::endl;
                std::unique_lock<std::mutex> lock(partition_mtx);
                auto it = stale_partitions.find(p_id);
                if (it != stale_partitions.end()) {
                    std::cout << "Segment " << seg_id << " host partition " << p_id << " is stale" << std::endl;
                    continue;
                }
                ASSERT_TRUE(seg);
            }

            auto it_segs = merge_segs.find(seg->GetPartitionId());
            if (it_segs == merge_segs.end()) {
                merge_segs[seg->GetPartitionId()] = {seg->GetID()};
            } else {
                merge_segs[seg->GetPartitionId()].insert(seg->GetID());
            }
            auto& segs = merge_segs[seg->GetPartitionId()];
            if ((segs.size() >= 2) && (RandomInt(0, 10) >= 2)) {
                std::cout << "Merging partition " << seg->GetPartitionId() << " segs (";
                for (auto seg : segs) {
                    std::cout << seg << ",";
                }
                std::cout << ")" << std::endl;
                ID_TYPE new_seg_id = 0;
                ID_TYPE partition_id = 0;
                do_merge(segs, new_seg_id, p_id);
                segs.clear();
                if (new_seg_id == 0) {
                    continue;
                }
                if (RandomInt(0, 10) >= 6) {
                    build_queue.Put({new_seg_id, p_id});
                }

            } else {
                continue;
            }
        }
        merge_waiter.Notify();
        build_queue.Put({0, 0});
        build_waiter.Wait();
    };

    auto build_worker = [&] {
        while (true) {
            auto ids = build_queue.Take();
            auto seg_id = std::get<0>(ids);
            auto p_id = std::get<1>(ids);
            if (seg_id == 0) {
                std::cout << "Exiting Build Worker" << std::endl;
                break;
            }

            std::cout << "Building " << seg_id << std::endl;
            do_build(seg_id, p_id);
        }
        build_waiter.Notify();
    };
    std::vector<std::thread> handlers;
    auto num_handlers = RandomInt(6, 8);
    for (auto i = 0; i < num_handlers; ++i) {
        handlers.emplace_back(handler_worker);
    }
    std::thread t3 = std::thread(merge_worker);
    std::thread t4 = std::thread(build_worker);

    for (auto& handler : handlers) {
        handler.join();
    }

    merge_queue.Put({0, 0});
    t3.join();
    t4.join();

    /* for (auto& kv : merged_segs_history) { */
    /*     std::cout << "merged: ("; */
    /*     for (auto i : kv.second) { */
    /*         std::cout << i << ","; */
    /*     } */
    /*     std::cout << ") -> " << kv.first << std::endl; */
    /* } */

    /* for (auto& id : built_segs) { */
    /*     std::cout << "built: " << id << std::endl; */
    /* } */

    merge_waiter.Wait();

C
Cai Yudong 已提交
1969
    ScopedSnapshotT latest_ss;
X
XuPeng-SH 已提交
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988
    status = Snapshots::GetInstance().GetSnapshot(latest_ss, collection_name);
    ASSERT_TRUE(status.ok());

    auto expect_segments = all_segments;
    for (auto& kv : merged_segs_history) {
        expect_segments.insert(kv.first);
        for (auto& id : kv.second) {
            expect_segments.erase(id);
        }
    }

    for (auto& seg_p : seg_p_map) {
        auto it = stale_partitions.find(seg_p.second);
        if (it == stale_partitions.end()) {
            continue;
        }
        expect_segments.erase(seg_p.first);
    }

C
Cai Yudong 已提交
1989
    std::set<ID_TYPE> final_segments;
X
XuPeng-SH 已提交
1990 1991 1992 1993 1994 1995 1996
    auto segments = latest_ss->GetResources<Segment>();
    for (auto& kv : segments) {
        final_segments.insert(kv.first);
    }
    ASSERT_EQ(final_segments, expect_segments);
    // TODO: Check Total Segment Files Cnt
}
1997 1998

struct GCSchedule {
C
Cai Yudong 已提交
1999
    // static constexpr const char* Name = "GCSchedule";
2000 2001 2002
};

struct FlushSchedule {
C
Cai Yudong 已提交
2003
    // static constexpr const char* Name = "FlushSchedule";
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
};

using IEventHandler = milvus::engine::snapshot::IEventHandler;
/* struct SampleHandler : public IEventHandler { */
/*     static constexpr const char* EventName = "SampleHandler"; */
/*     const char* */
/*     GetEventName() const override { */
/*         return EventName; */
/*     } */
/* }; */

REGISTER_HANDLER(GCSchedule, IEventHandler);
/* REGISTER_HANDLER(GCSchedule, SampleHandler); */
REGISTER_HANDLER(FlushSchedule, IEventHandler);
/* REGISTER_HANDLER(FlushSchedule, SampleHandler); */

using GCScheduleFactory = milvus::engine::snapshot::HandlerFactory<GCSchedule>;
using FlushScheduleFactory = milvus::engine::snapshot::HandlerFactory<GCSchedule>;

TEST_F(SnapshotTest, RegistryTest) {
    {
        auto& factory = GCScheduleFactory::GetInstance();
        auto ihandler = factory.GetHandler(IEventHandler::EventName);
        ASSERT_TRUE(ihandler);
        /* auto sihandler = factory.GetHandler(SampleHandler::EventName); */
        /* ASSERT_TRUE(sihandler); */
        /* ASSERT_EQ(SampleHandler::EventName, sihandler->GetEventName()); */
    }
    {
        /* auto& factory = FlushScheduleFactory::GetInstance(); */
        /* auto ihandler = factory.GetHandler(IEventHandler::EventName); */
        /* ASSERT_TRUE(ihandler); */
        /* auto sihandler = factory.GetHandler(SampleHandler::EventName); */
        /* ASSERT_TRUE(sihandler); */
        /* ASSERT_EQ(SampleHandler::EventName, sihandler->GetEventName()); */
    }
}