-
Notifications
You must be signed in to change notification settings - Fork 472
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Extract a rand sample helper and support negative sample count in "Set" #2113
Merged
PragmaTwice
merged 6 commits into
apache:unstable
from
mapleFU:cmd-srand-support-negative
Feb 26, 2024
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
bd96be8
support negative count during Set::Take
mapleFU 9a3e127
Extract a sample_helper.h to unify all sampling logic
mapleFU 51b07a4
cleanup comment
mapleFU 0352894
Fix lint
mapleFU 6c22327
Fix bug in Set::Take
mapleFU b989b0d
Merge branch 'unstable' into cmd-srand-support-negative
mapleFU File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -23,9 +23,9 @@ | |
#include <map> | ||
#include <memory> | ||
#include <optional> | ||
#include <random> | ||
|
||
#include "db_util.h" | ||
#include "sample_helper.h" | ||
|
||
namespace redis { | ||
|
||
|
@@ -197,9 +197,14 @@ rocksdb::Status Set::MIsMember(const Slice &user_key, const std::vector<Slice> & | |
} | ||
|
||
rocksdb::Status Set::Take(const Slice &user_key, std::vector<std::string> *members, int count, bool pop) { | ||
int n = 0; | ||
members->clear(); | ||
if (count <= 0) return rocksdb::Status::OK(); | ||
bool unique = true; | ||
if (count == 0) return rocksdb::Status::OK(); | ||
if (count < 0) { | ||
DCHECK(!pop); | ||
count = -count; | ||
unique = false; | ||
} | ||
|
||
std::string ns_key = AppendNamespacePrefix(user_key); | ||
|
||
|
@@ -210,49 +215,30 @@ rocksdb::Status Set::Take(const Slice &user_key, std::vector<std::string> *membe | |
rocksdb::Status s = GetMetadata(ns_key, &metadata); | ||
if (!s.ok()) return s.IsNotFound() ? rocksdb::Status::OK() : s; | ||
|
||
auto batch = storage_->GetWriteBatchBase(); | ||
WriteBatchLogData log_data(kRedisSet); | ||
batch->PutLogData(log_data.Encode()); | ||
|
||
std::string prefix = InternalKey(ns_key, "", metadata.version, storage_->IsSlotIdEncoded()).Encode(); | ||
std::string next_version_prefix = InternalKey(ns_key, "", metadata.version + 1, storage_->IsSlotIdEncoded()).Encode(); | ||
|
||
rocksdb::ReadOptions read_options = storage_->DefaultScanOptions(); | ||
LatestSnapShot ss(storage_); | ||
read_options.snapshot = ss.GetSnapShot(); | ||
rocksdb::Slice upper_bound(next_version_prefix); | ||
read_options.iterate_upper_bound = &upper_bound; | ||
|
||
std::vector<std::string> iter_keys; | ||
iter_keys.reserve(count); | ||
std::random_device rd; | ||
std::mt19937 gen(rd()); | ||
auto iter = util::UniqueIterator(storage_, read_options); | ||
for (iter->Seek(prefix); iter->Valid() && iter->key().starts_with(prefix); iter->Next()) { | ||
++n; | ||
if (n <= count) { | ||
iter_keys.push_back(iter->key().ToString()); | ||
} else { // n > count | ||
std::uniform_int_distribution<> distrib(0, n - 1); | ||
int random = distrib(gen); // [0,n-1] | ||
if (random < count) { | ||
iter_keys[random] = iter->key().ToString(); | ||
} | ||
} | ||
ObserverOrUniquePtr<rocksdb::WriteBatchBase> batch = storage_->GetWriteBatchBase(); | ||
if (pop) { | ||
WriteBatchLogData log_data(kRedisSet); | ||
batch->PutLogData(log_data.Encode()); | ||
} | ||
for (Slice key : iter_keys) { | ||
InternalKey ikey(key, storage_->IsSlotIdEncoded()); | ||
members->emplace_back(ikey.GetSubKey().ToString()); | ||
if (pop) { | ||
batch->Delete(key); | ||
} | ||
members->clear(); | ||
s = ExtractRandMemberFromSet<std::string>( | ||
unique, count, [this, user_key](std::vector<std::string> *samples) { return this->Members(user_key, samples); }, | ||
members); | ||
if (!s.ok()) { | ||
return s; | ||
} | ||
if (pop && !iter_keys.empty()) { | ||
metadata.size -= iter_keys.size(); | ||
std::string bytes; | ||
metadata.Encode(&bytes); | ||
batch->Put(metadata_cf_handle_, ns_key, bytes); | ||
// Avoid to write an empty op-log if just random select some members. | ||
if (!pop) return rocksdb::Status::OK(); | ||
// Avoid to write an empty op-log if the set is empty. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Don't know whether we can do this optimization, would it affect replication? |
||
if (members->empty()) return rocksdb::Status::OK(); | ||
for (std::string &user_sub_key : *members) { | ||
std::string sub_key = InternalKey(ns_key, user_sub_key, metadata.version, storage_->IsSlotIdEncoded()).Encode(); | ||
batch->Delete(sub_key); | ||
} | ||
metadata.size -= members->size(); | ||
std::string bytes; | ||
metadata.Encode(&bytes); | ||
batch->Put(metadata_cf_handle_, ns_key, bytes); | ||
return storage_->Write(storage_->DefaultWriteOptions(), batch->GetWriteBatch()); | ||
} | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one | ||
* or more contributor license agreements. See the NOTICE file | ||
* distributed with this work for additional information | ||
* regarding copyright ownership. The ASF licenses this file | ||
* to you 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. | ||
* | ||
*/ | ||
|
||
#pragma once | ||
|
||
#include <rocksdb/status.h> | ||
|
||
#include <random> | ||
#include <vector> | ||
|
||
/// ExtractRandMemberFromSet is a helper function to extract random elements from a kvrocks structure. | ||
/// | ||
/// The complexity of the function is O(N) where N is the number of elements inside the structure. | ||
template <typename ElementType, typename GetAllMemberFnType> | ||
rocksdb::Status ExtractRandMemberFromSet(bool unique, size_t count, const GetAllMemberFnType &get_all_member_fn, | ||
std::vector<ElementType> *elements) { | ||
elements->clear(); | ||
std::vector<ElementType> samples; | ||
rocksdb::Status s = get_all_member_fn(&samples); | ||
if (!s.ok() || samples.empty()) return s; | ||
|
||
size_t all_element_size = samples.size(); | ||
DCHECK_GE(all_element_size, 1U); | ||
elements->reserve(std::min(all_element_size, count)); | ||
|
||
if (!unique || count == 1) { | ||
// Case 1: Negative count, randomly select elements or without parameter | ||
std::mt19937 gen(std::random_device{}()); | ||
std::uniform_int_distribution<uint64_t> dist(0, all_element_size - 1); | ||
for (uint64_t i = 0; i < count; i++) { | ||
uint64_t index = dist(gen); | ||
elements->emplace_back(samples[index]); | ||
} | ||
} else if (all_element_size <= count) { | ||
// Case 2: Requested count is greater than or equal to the number of elements inside the structure | ||
for (auto &sample : samples) { | ||
elements->push_back(std::move(sample)); | ||
} | ||
} else { | ||
// Case 3: Requested count is less than the number of elements inside the structure | ||
std::mt19937 gen(std::random_device{}()); | ||
// use Fisher-Yates shuffle algorithm to randomize the order | ||
std::shuffle(samples.begin(), samples.end(), gen); | ||
// then pick the first `count` ones. | ||
for (uint64_t i = 0; i < count; i++) { | ||
elements->emplace_back(std::move(samples[i])); | ||
} | ||
} | ||
return rocksdb::Status::OK(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is just a dcheck. Previously, code called with
append_field_with_index
. However,GetAll
is already called with "type", so it's not neccessary to clean up or set it again