MemTable.cpp 14.2 KB
Newer Older
1
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
J
jinhai 已提交
2
//
3 4
// 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
J
jinhai 已提交
5
//
6 7 8 9 10
// 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.
J
jinhai 已提交
11

S
starlord 已提交
12
#include "db/insert/MemTable.h"
Z
zhiru 已提交
13

14 15 16 17 18 19
#include <cache/CpuCacheMgr.h>
#include <segment/SegmentReader.h>
#include <wrapper/VecIndex.h>

#include <algorithm>
#include <chrono>
S
starlord 已提交
20 21
#include <memory>
#include <string>
22 23 24 25 26
#include <unordered_map>

#include "db/OngoingFileChecker.h"
#include "db/Utils.h"
#include "utils/Log.h"
Z
update  
zhiru 已提交
27

Z
zhiru 已提交
28 29 30
namespace milvus {
namespace engine {

S
starlord 已提交
31 32
MemTable::MemTable(const std::string& table_id, const meta::MetaPtr& meta, const DBOptions& options)
    : table_id_(table_id), meta_(meta), options_(options) {
33 34
    SetIdentity("MemTable");
    AddCacheInsertDataListener();
Z
zhiru 已提交
35 36
}

S
starlord 已提交
37
Status
38
MemTable::Add(const VectorSourcePtr& source) {
Z
zhiru 已提交
39
    while (!source->AllAdded()) {
S
starlord 已提交
40
        MemTableFilePtr current_mem_table_file;
Z
zhiru 已提交
41
        if (!mem_table_file_list_.empty()) {
Z
update  
zhiru 已提交
42
            current_mem_table_file = mem_table_file_list_.back();
Z
zhiru 已提交
43
        }
Z
update  
zhiru 已提交
44

Z
zhiru 已提交
45
        Status status;
Z
update  
zhiru 已提交
46
        if (mem_table_file_list_.empty() || current_mem_table_file->IsFull()) {
S
starlord 已提交
47
            MemTableFilePtr new_mem_table_file = std::make_shared<MemTableFile>(table_id_, meta_, options_);
G
groot 已提交
48
            status = new_mem_table_file->Add(source);
Z
zhiru 已提交
49
            if (status.ok()) {
Z
update  
zhiru 已提交
50
                mem_table_file_list_.emplace_back(new_mem_table_file);
Z
zhiru 已提交
51
            }
Z
update  
zhiru 已提交
52
        } else {
G
groot 已提交
53
            status = current_mem_table_file->Add(source);
Z
zhiru 已提交
54
        }
Z
update  
zhiru 已提交
55

Z
zhiru 已提交
56
        if (!status.ok()) {
S
starlord 已提交
57
            std::string err_msg = "Insert failed: " + status.ToString();
Z
update  
zhiru 已提交
58
            ENGINE_LOG_ERROR << err_msg;
S
starlord 已提交
59
            return Status(DB_ERROR, err_msg);
Z
zhiru 已提交
60 61 62 63 64
        }
    }
    return Status::OK();
}

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
Status
MemTable::Delete(segment::doc_id_t doc_id) {
    // Locate which table file the doc id lands in
    for (auto& table_file : mem_table_file_list_) {
        table_file->Delete(doc_id);
    }
    // Add the id to delete list so it can be applied to other segments on disk during the next flush
    doc_ids_to_delete_.insert(doc_id);

    return Status::OK();
}

Status
MemTable::Delete(const std::vector<segment::doc_id_t>& doc_ids) {
    // Locate which table file the doc id lands in
    for (auto& table_file : mem_table_file_list_) {
        table_file->Delete(doc_ids);
    }
    // Add the id to delete list so it can be applied to other segments on disk during the next flush
    for (auto& id : doc_ids) {
        doc_ids_to_delete_.insert(id);
    }

    return Status::OK();
}

S
starlord 已提交
91
void
S
starlord 已提交
92
MemTable::GetCurrentMemTableFile(MemTableFilePtr& mem_table_file) {
Z
zhiru 已提交
93
    mem_table_file = mem_table_file_list_.back();
Z
zhiru 已提交
94 95
}

S
starlord 已提交
96 97
size_t
MemTable::GetTableFileCount() {
Z
zhiru 已提交
98 99 100
    return mem_table_file_list_.size();
}

S
starlord 已提交
101
Status
Z
Zhiru Zhu 已提交
102
MemTable::Serialize(uint64_t wal_lsn, bool apply_delete) {
103 104
    auto start = std::chrono::high_resolution_clock::now();

Z
Zhiru Zhu 已提交
105
    if (!doc_ids_to_delete_.empty() && apply_delete) {
106 107 108 109 110 111
        auto status = ApplyDeletes();
        if (!status.ok()) {
            return Status(DB_ERROR, status.message());
        }
    }

Z
update  
zhiru 已提交
112
    for (auto mem_table_file = mem_table_file_list_.begin(); mem_table_file != mem_table_file_list_.end();) {
113
        auto status = (*mem_table_file)->Serialize(wal_lsn);
Z
zhiru 已提交
114
        if (!status.ok()) {
115
            return status;
Z
zhiru 已提交
116
        }
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

        ENGINE_LOG_DEBUG << "Flushed segment " << (*mem_table_file)->GetSegmentId();

        {
            std::lock_guard<std::mutex> lock(mutex_);
            mem_table_file = mem_table_file_list_.erase(mem_table_file);
        }
    }

    // Update flush lsn
    auto status = meta_->UpdateTableFlushLSN(table_id_, wal_lsn);
    if (!status.ok()) {
        std::string err_msg = "Failed to write flush lsn to meta: " + status.ToString();
        ENGINE_LOG_ERROR << err_msg;
        return Status(DB_ERROR, err_msg);
Z
zhiru 已提交
132
    }
133 134 135 136 137

    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;
    ENGINE_LOG_DEBUG << "Finished flushing for table " << table_id_ << " in " << diff.count() << " s";

Z
zhiru 已提交
138
    return Status::OK();
Z
zhiru 已提交
139 140
}

S
starlord 已提交
141 142
bool
MemTable::Empty() {
143
    return mem_table_file_list_.empty() && doc_ids_to_delete_.empty();
Z
zhiru 已提交
144 145
}

S
starlord 已提交
146
const std::string&
S
starlord 已提交
147
MemTable::GetTableId() const {
Z
zhiru 已提交
148 149 150
    return table_id_;
}

S
starlord 已提交
151 152
size_t
MemTable::GetCurrentMem() {
Z
zhiru 已提交
153
    std::lock_guard<std::mutex> lock(mutex_);
Z
update  
zhiru 已提交
154
    size_t total_mem = 0;
S
starlord 已提交
155
    for (auto& mem_table_file : mem_table_file_list_) {
Z
update  
zhiru 已提交
156
        total_mem += mem_table_file->GetCurrentMem();
Z
zhiru 已提交
157
    }
Z
update  
zhiru 已提交
158
    return total_mem;
Z
zhiru 已提交
159 160
}

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
Status
MemTable::ApplyDeletes() {
    // Applying deletes to other segments on disk and their corresponding cache:
    // For each segment in table:
    //     Load its bloom filter
    //     For each id in delete list:
    //         If present, add the uid to segment's uid list
    // For each segment
    //     Get its cache if exists
    //     Load its uids file.
    //     Scan the uids, if any uid in segment's uid list exists:
    //         add its offset to deletedDoc
    //         remove the id from bloom filter
    //         set black list in cache
    //     Serialize segment's deletedDoc TODO(zhiru): append directly to previous file for now, may have duplicates
    //     Serialize bloom filter

    ENGINE_LOG_DEBUG << "Applying " << doc_ids_to_delete_.size() << " deletes in table: " << table_id_;

    auto start_total = std::chrono::high_resolution_clock::now();

J
JinHai-CN 已提交
182
    //    auto start = std::chrono::high_resolution_clock::now();
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 217 218 219 220 221 222

    std::vector<int> file_types{meta::TableFileSchema::FILE_TYPE::RAW, meta::TableFileSchema::FILE_TYPE::TO_INDEX,
                                meta::TableFileSchema::FILE_TYPE::BACKUP};
    meta::TableFilesSchema table_files;
    auto status = meta_->FilesByType(table_id_, file_types, table_files);
    if (!status.ok()) {
        std::string err_msg = "Failed to apply deletes: " + status.ToString();
        ENGINE_LOG_ERROR << err_msg;
        return Status(DB_ERROR, err_msg);
    }

    OngoingFileChecker::GetInstance().MarkOngoingFiles(table_files);

    std::unordered_map<size_t, std::vector<segment::doc_id_t>> ids_to_check_map;

    for (size_t i = 0; i < table_files.size(); ++i) {
        auto& table_file = table_files[i];
        std::string segment_dir;
        utils::GetParentPath(table_file.location_, segment_dir);

        segment::SegmentReader segment_reader(segment_dir);
        segment::IdBloomFilterPtr id_bloom_filter_ptr;
        segment_reader.LoadBloomFilter(id_bloom_filter_ptr);

        for (auto& id : doc_ids_to_delete_) {
            if (id_bloom_filter_ptr->Check(id)) {
                ids_to_check_map[i].emplace_back(id);
            }
        }
    }

    meta::TableFilesSchema files_to_check;
    for (auto& kv : ids_to_check_map) {
        files_to_check.emplace_back(table_files[kv.first]);
    }

    OngoingFileChecker::GetInstance().UnmarkOngoingFiles(table_files);

    OngoingFileChecker::GetInstance().MarkOngoingFiles(files_to_check);

J
JinHai-CN 已提交
223 224 225
    auto time0 = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff0 = time0 - start_total;
    ENGINE_LOG_DEBUG << "Found " << ids_to_check_map.size() << " segment to apply deletes in " << diff0.count() << " s";
226 227 228 229 230 231 232

    meta::TableFilesSchema table_files_to_update;

    for (auto& kv : ids_to_check_map) {
        auto& table_file = table_files[kv.first];
        ENGINE_LOG_DEBUG << "Applying deletes in segment: " << table_file.segment_id_;

J
JinHai-CN 已提交
233
        auto time1 = std::chrono::high_resolution_clock::now();
234 235 236 237 238

        std::string segment_dir;
        utils::GetParentPath(table_file.location_, segment_dir);
        segment::SegmentReader segment_reader(segment_dir);

Z
update  
Zhiru Zhu 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
        auto& segment_id = table_file.segment_id_;
        meta::TableFilesSchema segment_files;
        status = meta_->GetTableFilesBySegmentId(segment_id, segment_files);
        if (!status.ok()) {
            break;
        }

        // Get all index that contains blacklist in cache
        std::vector<VecIndexPtr> indexes;
        std::vector<faiss::ConcurrentBitsetPtr> blacklists;
        for (auto& file : segment_files) {
            auto index =
                std::static_pointer_cast<VecIndex>(cache::CpuCacheMgr::GetInstance()->GetIndex(file.location_));
            faiss::ConcurrentBitsetPtr blacklist = nullptr;
            if (index != nullptr) {
                index->GetBlacklist(blacklist);
                if (blacklist != nullptr) {
                    indexes.emplace_back(index);
                    blacklists.emplace_back(blacklist);
                }
            }
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        }

        std::vector<segment::doc_id_t> uids;
        status = segment_reader.LoadUids(uids);
        if (!status.ok()) {
            break;
        }
        segment::IdBloomFilterPtr id_bloom_filter_ptr;
        status = segment_reader.LoadBloomFilter(id_bloom_filter_ptr);
        if (!status.ok()) {
            break;
        }

        auto& ids_to_check = kv.second;

        segment::DeletedDocsPtr deleted_docs = std::make_shared<segment::DeletedDocs>();

J
JinHai-CN 已提交
277 278 279
        auto time2 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff1 = time2 - time1;
        ENGINE_LOG_DEBUG << "Loading uids and deleted docs took " << diff1.count() << " s";
280 281 282

        std::sort(ids_to_check.begin(), ids_to_check.end());

J
JinHai-CN 已提交
283 284 285
        auto time3 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff2 = time3 - time2;
        ENGINE_LOG_DEBUG << "Sorting " << ids_to_check.size() << " ids took " << diff2.count() << " s";
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

        size_t delete_count = 0;
        auto find_diff = std::chrono::duration<double>::zero();
        auto set_diff = std::chrono::duration<double>::zero();

        for (size_t i = 0; i < uids.size(); ++i) {
            auto find_start = std::chrono::high_resolution_clock::now();

            auto found = std::binary_search(ids_to_check.begin(), ids_to_check.end(), uids[i]);

            auto find_end = std::chrono::high_resolution_clock::now();
            find_diff += (find_end - find_start);

            if (found) {
                auto set_start = std::chrono::high_resolution_clock::now();

                delete_count++;

                deleted_docs->AddDeletedDoc(i);

                if (id_bloom_filter_ptr->Check(uids[i])) {
                    id_bloom_filter_ptr->Remove(uids[i]);
                }

Z
update  
Zhiru Zhu 已提交
310
                for (auto& blacklist : blacklists) {
311 312 313 314 315 316 317 318 319 320 321 322 323 324
                    if (!blacklist->test(i)) {
                        blacklist->set(i);
                    }
                }

                auto set_end = std::chrono::high_resolution_clock::now();
                set_diff += (set_end - set_start);
            }
        }

        ENGINE_LOG_DEBUG << "Finding " << ids_to_check.size() << " uids in " << uids.size() << " uids took "
                         << find_diff.count() << " s in total";
        ENGINE_LOG_DEBUG << "Setting deleted docs and bloom filter took " << set_diff.count() << " s in total";

J
JinHai-CN 已提交
325
        auto time4 = std::chrono::high_resolution_clock::now();
J
Test  
JinHai-CN 已提交
326

Z
update  
Zhiru Zhu 已提交
327 328
        for (auto i = 0; i < indexes.size(); ++i) {
            indexes[i]->SetBlacklist(blacklists[i]);
329 330
        }

J
JinHai-CN 已提交
331
        //        start = std::chrono::high_resolution_clock::now();
332 333 334 335 336 337 338 339

        segment::Segment tmp_segment;
        segment::SegmentWriter segment_writer(segment_dir);
        status = segment_writer.WriteDeletedDocs(deleted_docs);
        if (!status.ok()) {
            break;
        }

J
JinHai-CN 已提交
340 341
        auto time5 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff4 = time5 - time4;
342
        ENGINE_LOG_DEBUG << "Appended " << deleted_docs->GetSize()
J
JinHai-CN 已提交
343
                         << " offsets to deleted docs in segment: " << table_file.segment_id_ << " in " << diff4.count()
344 345
                         << " s";

J
JinHai-CN 已提交
346
        //        start = std::chrono::high_resolution_clock::now();
347 348 349 350 351

        status = segment_writer.WriteBloomFilter(id_bloom_filter_ptr);
        if (!status.ok()) {
            break;
        }
J
JinHai-CN 已提交
352 353 354
        auto time6 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff5 = time6 - time5;
        ENGINE_LOG_DEBUG << "Updated bloom filter in segment: " << table_file.segment_id_ << " in " << diff5.count()
355 356 357 358 359 360 361 362 363 364
                         << " s";

        // Update table file row count
        for (auto& file : segment_files) {
            if (file.file_type_ == meta::TableFileSchema::RAW || file.file_type_ == meta::TableFileSchema::TO_INDEX ||
                file.file_type_ == meta::TableFileSchema::INDEX || file.file_type_ == meta::TableFileSchema::BACKUP) {
                file.row_count_ -= delete_count;
                table_files_to_update.emplace_back(file);
            }
        }
J
JinHai-CN 已提交
365 366 367
        auto time7 = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff6 = time7 - time6;
        diff6 = time6 - time5;
J
JinHai-CN 已提交
368 369
        ENGINE_LOG_DEBUG << "Update table file row count in vector of segment: " << table_file.segment_id_ << " in "
                         << diff6.count() << " s";
370 371
    }

J
Test  
JinHai-CN 已提交
372 373
    auto time7 = std::chrono::high_resolution_clock::now();

374
    status = meta_->UpdateTableFilesRowCount(table_files_to_update);
375 376 377 378 379 380 381 382 383 384

    if (!status.ok()) {
        std::string err_msg = "Failed to apply deletes: " + status.ToString();
        ENGINE_LOG_ERROR << err_msg;
        return Status(DB_ERROR, err_msg);
    }

    doc_ids_to_delete_.clear();

    auto end_total = std::chrono::high_resolution_clock::now();
J
JinHai-CN 已提交
385 386
    std::chrono::duration<double> diff7 = end_total - time7;
    ENGINE_LOG_DEBUG << "Update deletes to meta in table " << table_id_ << " in " << diff7.count() << " s";
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
    std::chrono::duration<double> diff_total = end_total - start_total;
    ENGINE_LOG_DEBUG << "Finished applying deletes in table " << table_id_ << " in " << diff_total.count() << " s";

    OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files_to_check);

    return Status::OK();
}

uint64_t
MemTable::GetLSN() {
    return lsn_;
}

void
MemTable::SetLSN(uint64_t lsn) {
    lsn_ = lsn;
}

405 406 407 408 409
void
MemTable::OnCacheInsertDataChanged(bool value) {
    options_.insert_cache_immediately_ = value;
}

S
starlord 已提交
410 411
}  // namespace engine
}  // namespace milvus