20 #include <tbb/parallel_for.h>
21 #include <tbb/task_arena.h>
23 #include <boost/filesystem/operations.hpp>
24 #include <boost/filesystem/path.hpp>
25 #include <boost/sort/spreadsort/string_sort.hpp>
29 #include <string_view>
31 #include <type_traits>
38 #include <sys/fcntl.h>
58 auto fd =
heavyai::open(path, O_RDWR | O_CREAT | (recover ? O_APPEND : O_TRUNC), 0644);
62 auto err = std::string(
"Dictionary path ") + std::string(path) +
63 std::string(
" does not exist.");
80 if (in == 0 || (in > (UINT32_MAX))) {
89 for (
size_t i = 0; i < str.size(); ++i) {
90 str_hash = str_hash * 997 + str[i];
100 const int64_t num_elems,
101 const int64_t target_elems_per_thread) {
103 std::min(std::max(max_thread_count, int64_t(1)),
104 ((num_elems + target_elems_per_thread - 1) / target_elems_per_thread));
118 const std::string& folder,
121 const bool materializeHashes,
122 size_t initial_capacity)
123 : dict_ref_(dict_ref)
126 , string_id_string_dict_hash_table_(initial_capacity, INVALID_STR_ID)
127 , hash_cache_(initial_capacity)
129 , materialize_hashes_(materializeHashes)
132 , offset_map_(nullptr)
133 , payload_map_(nullptr)
134 , offset_file_size_(0)
135 , payload_file_size_(0)
136 , payload_file_off_(0)
137 , strings_cache_(nullptr) {
138 if (!isTemp && folder.empty()) {
143 CHECK_EQ(
size_t(0), (initial_capacity & (initial_capacity - 1)));
145 boost::filesystem::path storage_path(folder);
146 offsets_path_ = (storage_path / boost::filesystem::path(
"DictOffsets")).
string();
147 const auto payload_path =
148 (storage_path / boost::filesystem::path(
"DictPayload")).
string();
154 bool storage_is_empty =
false;
156 storage_is_empty =
true;
172 const uint64_t str_count =
177 const uint64_t max_entries =
179 round_up_p2(std::max(initial_capacity, static_cast<size_t>(1))));
183 std::vector<string_dict_hash_t> new_hash_cache(max_entries / 2);
188 if (str_count == 0) {
192 unsigned string_id = 0;
195 uint32_t thread_inits = 0;
196 const auto thread_count = std::thread::hardware_concurrency();
197 const uint32_t items_per_thread = std::max<uint32_t>(
198 2000, std::min<uint32_t>(200000, (str_count / thread_count) + 1));
199 std::vector<std::future<std::vector<std::pair<string_dict_hash_t, unsigned int>>>>
201 for (string_id = 0; string_id < str_count; string_id += items_per_thread) {
204 std::vector<std::pair<string_dict_hash_t, unsigned int>> hashVec;
205 for (uint32_t curr_id = string_id;
206 curr_id < string_id + items_per_thread && curr_id < str_count;
209 if (recovered.canary) {
213 std::string_view temp(recovered.c_str_ptr, recovered.size);
214 hashVec.emplace_back(std::make_pair(
hash_string(temp), temp.size()));
220 if (thread_inits % thread_count == 0) {
225 if (dictionary_futures.size() != 0) {
228 VLOG(1) <<
"Opened string dictionary " << folder <<
" # Strings: " <<
str_count_
240 std::unordered_map<std::string, int32_t>
map_;
243 void operator()(std::string
const& str, int32_t
const string_id)
override {
244 auto const emplaced = map_.emplace(str, string_id);
245 CHECK(emplaced.second) <<
"str(" << str <<
") string_id(" << string_id <<
')';
247 void operator()(std::string_view
const, int32_t
const string_id)
override {
248 UNREACHABLE() <<
"MapMaker must be called with a std::string.";
250 std::unordered_map<std::string, int32_t>
moveMap() {
return std::move(map_); }
257 constexpr
size_t big_gen =
static_cast<size_t>(std::numeric_limits<size_t>::max());
260 return [map{map_maker.moveMap()}](std::string
const& str) {
261 auto const itr = map.find(str);
273 CHECK_LE(n, static_cast<size_t>(std::numeric_limits<int32_t>::max()) + 1);
274 for (
unsigned id = 0;
id <
n; ++id) {
279 serial_callback(str,
id);
282 size_t const n = std::min(static_cast<size_t>(generation),
str_count_);
283 CHECK_LE(n, static_cast<size_t>(std::numeric_limits<int32_t>::max()) + 1);
285 for (
unsigned id = 0;
id <
n; ++id) {
292 std::vector<std::future<std::vector<std::pair<string_dict_hash_t, unsigned int>>>>&
293 dictionary_futures) {
294 for (
auto& dictionary_future : dictionary_futures) {
295 dictionary_future.wait();
296 const auto hashVec = dictionary_future.get();
297 for (
const auto& hash : hashVec) {
298 const uint32_t bucket =
308 dictionary_futures.clear();
328 if (storage_slots == 0) {
333 int64_t min_bound = 0;
334 int64_t max_bound = storage_slots - 1;
336 while (min_bound <= max_bound) {
337 guess = (max_bound + min_bound) / 2;
339 if (getStringFromStorage(guess).canary) {
340 max_bound = guess - 1;
342 min_bound = guess + 1;
345 CHECK_GE(guess + (min_bound > guess ? 1 : 0), 0);
346 return guess + (min_bound > guess ? 1 : 0);
350 : dict_ref_(dict_ref)
351 , folder_(
"DB_" + std::
to_string(dict_ref.dbId) +
"_DICT_" +
353 , strings_cache_(nullptr)
384 std::vector<int32_t> string_ids;
385 client_->get_or_add_bulk(string_ids, std::vector<std::string>{str});
386 CHECK_EQ(
size_t(1), string_ids.size());
387 return string_ids.front();
389 return getOrAddImpl(str);
396 std::ostringstream oss;
397 oss <<
"The text encoded column using dictionary " << dict_ref.
toString()
398 <<
" has exceeded it's limit of " <<
sizeof(
T) * 8 <<
" bits ("
399 << static_cast<size_t>(max_valid_int_value<T>() + 1) <<
" unique values) "
400 <<
"while attempting to add the new string '" << str <<
"'. ";
409 oss <<
"To load more data, please re-create the table with "
410 <<
"this column as type TEXT ENCODING DICT(" <<
sizeof(
T) * 2 * 8 <<
") ";
411 if (
sizeof(
T) == 1) {
412 oss <<
"or TEXT ENCODING DICT(32) ";
414 oss <<
"and reload your data.";
418 oss <<
"Currently dictionary-encoded text columns support a maximum of "
420 <<
" strings. Consider recreating the table with "
421 <<
"this column as type TEXT ENCODING NONE and reloading your data.";
424 throw std::runtime_error(oss.str());
428 std::ostringstream oss;
429 oss <<
"The string '" << str <<
" could not be inserted into the dictionary "
430 << dict_ref.
toString() <<
" because it exceeded the maximum allowable "
432 << str.size() <<
" characters).";
434 throw std::runtime_error(oss.str());
439 template <
class String>
441 const std::vector<std::vector<String>>& string_array_vec,
442 std::vector<std::vector<int32_t>>& ids_array_vec) {
448 ids_array_vec.resize(string_array_vec.size());
449 for (
size_t i = 0; i < string_array_vec.size(); i++) {
450 auto& strings = string_array_vec[i];
451 auto& ids = ids_array_vec[i];
452 ids.resize(strings.size());
458 const std::vector<std::vector<std::string>>& string_array_vec,
459 std::vector<std::vector<int32_t>>& ids_array_vec);
462 const std::vector<std::vector<std::string_view>>& string_array_vec,
463 std::vector<std::vector<int32_t>>& ids_array_vec);
470 template <
class String>
472 std::vector<string_dict_hash_t>& hashes)
const
474 CHECK_EQ(string_vec.size(), hashes.size());
477 [&string_vec, &hashes](
const tbb::blocked_range<size_t>& r) {
478 for (
size_t curr_id = r.begin(); curr_id != r.end(); ++curr_id) {
479 if (string_vec[curr_id].empty()) {
482 hashes[curr_id] =
hash_string(string_vec[curr_id]);
487 template <
class T,
class String>
489 T* encoded_vec)
const {
490 return getBulk(string_vec, encoded_vec, -1L );
494 uint8_t* encoded_vec)
const;
496 uint16_t* encoded_vec)
const;
498 int32_t* encoded_vec)
const;
500 template <
class T,
class String>
503 const int64_t generation)
const {
504 constexpr int64_t target_strings_per_thread{1000};
505 const int64_t num_lookup_strings = string_vec.size();
506 if (num_lookup_strings == 0) {
511 std::thread::hardware_concurrency(), num_lookup_strings, target_strings_per_thread);
515 std::vector<size_t> num_strings_not_found_per_thread(thread_info.
num_threads, 0UL);
518 const int64_t num_dict_strings = generation >= 0 ? generation :
storageEntryCount();
519 const bool dictionary_is_empty = (num_dict_strings == 0);
520 if (dictionary_is_empty) {
522 [&](
const tbb::blocked_range<int64_t>& r) {
523 const int64_t start_idx = r.begin();
524 const int64_t end_idx = r.end();
525 for (int64_t string_idx = start_idx; string_idx < end_idx;
530 return num_lookup_strings;
535 tbb::task_arena limited_arena(thread_info.
num_threads);
536 limited_arena.execute([&] {
539 tbb::blocked_range<int64_t>(
541 [&](
const tbb::blocked_range<int64_t>& r) {
542 const int64_t start_idx = r.begin();
543 const int64_t end_idx = r.end();
544 size_t num_strings_not_found = 0;
545 for (int64_t string_idx = start_idx; string_idx != end_idx; ++string_idx) {
546 const auto& input_string = string_vec[string_idx];
547 if (input_string.empty()) {
548 encoded_vec[string_idx] = inline_int_null_value<T>();
560 string_id >= num_dict_strings) {
562 num_strings_not_found++;
565 encoded_vec[string_idx] = string_id;
567 const size_t tbb_thread_idx = tbb::this_task_arena::current_thread_index();
568 num_strings_not_found_per_thread[tbb_thread_idx] = num_strings_not_found;
570 tbb::simple_partitioner());
573 size_t num_strings_not_found = 0;
574 for (int64_t thread_idx = 0; thread_idx < thread_info.num_threads; ++thread_idx) {
575 num_strings_not_found += num_strings_not_found_per_thread[thread_idx];
577 return num_strings_not_found;
581 uint8_t* encoded_vec,
582 const int64_t generation)
const;
584 uint16_t* encoded_vec,
585 const int64_t generation)
const;
587 int32_t* encoded_vec,
588 const int64_t generation)
const;
590 template <
class T,
class String>
592 T* output_string_ids) {
602 for (
const auto& input_string : input_strings) {
603 if (input_string.empty()) {
604 output_string_ids[idx++] = inline_int_null_value<T>();
610 uint32_t hash_bucket =
618 if (
str_count_ > static_cast<size_t>(max_valid_int_value<T>())) {
619 throw_encoding_error<T>(input_string,
dict_ref_);
623 <<
") of Dictionary encoded Strings reached for this column, offset path "
637 const int32_t string_id =
static_cast<int32_t
>(
str_count_);
639 output_string_ids[idx++] = string_id;
642 const size_t num_strings_added =
str_count_ - initial_str_count;
643 if (num_strings_added > 0) {
648 template <
class T,
class String>
650 T* output_string_ids) {
653 std::vector<string_dict_hash_t> input_strings_hashes(input_strings.size());
657 size_t shadow_str_count =
659 const size_t storage_high_water_mark = shadow_str_count;
660 std::vector<size_t> string_memory_ids;
661 size_t sum_new_string_lengths = 0;
662 string_memory_ids.reserve(input_strings.size());
663 size_t input_string_idx{0};
664 for (
const auto& input_string : input_strings) {
666 if (input_string.empty()) {
667 output_string_ids[input_string_idx++] = inline_int_null_value<T>();
676 storage_high_water_mark,
679 input_strings_hashes);
684 const uint32_t hash_bucket =
688 storage_high_water_mark,
696 output_string_ids[input_string_idx++] =
702 if (shadow_str_count > static_cast<size_t>(max_valid_int_value<T>())) {
703 throw_encoding_error<T>(input_string,
dict_ref_);
706 <<
"Maximum number (" << shadow_str_count
707 <<
") of Dictionary encoded Strings reached for this column, offset path "
711 string_memory_ids.push_back(input_string_idx);
712 sum_new_string_lengths += input_string.size();
714 static_cast<int32_t
>(shadow_str_count);
718 output_string_ids[input_string_idx++] = shadow_str_count++;
721 const size_t num_strings_added = shadow_str_count -
str_count_;
722 str_count_ = shadow_str_count;
723 if (num_strings_added > 0) {
728 uint8_t* encoded_vec);
730 uint16_t* encoded_vec);
732 int32_t* encoded_vec);
735 const std::vector<std::string_view>& string_vec,
736 uint8_t* encoded_vec);
738 const std::vector<std::string_view>& string_vec,
739 uint16_t* encoded_vec);
741 const std::vector<std::string_view>& string_vec,
742 int32_t* encoded_vec);
744 template <
class String>
748 if constexpr (std::is_same_v<std::string, std::decay_t<String>>) {
751 return client_->get(std::string(str));
762 auto str_id = string_id_string_dict_hash_table_[computeBucket(
763 hash, sv, string_id_string_dict_hash_table_)];
771 client_->get_string(ret, string_id);
778 CHECK_LT(string_id, static_cast<int32_t>(str_count_));
779 return getStringChecked(string_id);
784 std::shared_lock<std::shared_mutex>
read_lock(rw_mutex_);
787 CHECK_LT(string_id, static_cast<int32_t>(str_count_));
788 return getStringBytesChecked(string_id);
794 return client_->storage_entry_count();
802 const std::string& pattern,
804 const bool is_simple,
808 str.c_str(), str.size(), pattern.c_str(), pattern.size())
815 str.c_str(), str.size(), pattern.c_str(), pattern.size())
827 const bool is_simple,
829 const size_t generation)
const {
832 return client_->get_like(pattern, icase, is_simple, escape, generation);
834 const auto cache_key = std::make_tuple(pattern, icase, is_simple, escape);
839 std::vector<int32_t>
result;
840 std::vector<std::thread> workers;
843 std::vector<std::vector<int32_t>> worker_results(worker_count);
845 for (
int worker_idx = 0; worker_idx < worker_count; ++worker_idx) {
846 workers.emplace_back([&worker_results,
855 for (
size_t string_id = worker_idx; string_id < generation;
856 string_id += worker_count) {
858 if (
is_like(str, pattern, icase, is_simple, escape)) {
859 worker_results[worker_idx].push_back(string_id);
864 for (
auto& worker : workers) {
867 for (
const auto& worker_result : worker_results) {
868 result.insert(result.end(), worker_result.begin(), worker_result.end());
871 const auto it_ok =
like_cache_.insert(std::make_pair(cache_key, result));
879 std::string comp_operator,
881 std::vector<int32_t>
result;
886 auto eq_id = eq_id_itr->second;
887 if (comp_operator ==
"=") {
888 result.push_back(eq_id);
890 for (int32_t idx = 0; idx <= cur_size; idx++) {
894 result.push_back(idx);
898 std::vector<std::thread> workers;
901 std::vector<std::vector<int32_t>> worker_results(worker_count);
903 for (
int worker_idx = 0; worker_idx < worker_count; ++worker_idx) {
904 workers.emplace_back(
905 [&worker_results, &pattern, generation, worker_idx, worker_count,
this]() {
906 for (
size_t string_id = worker_idx; string_id < generation;
907 string_id += worker_count) {
909 if (str == pattern) {
910 worker_results[worker_idx].push_back(string_id);
915 for (
auto& worker : workers) {
918 for (
const auto& worker_result : worker_results) {
919 result.insert(result.end(), worker_result.begin(), worker_result.end());
921 if (result.size() > 0) {
922 const auto it_ok =
equal_cache_.insert(std::make_pair(pattern, result[0]));
926 if (comp_operator ==
"<>") {
927 for (int32_t idx = 0; idx <= cur_size; idx++) {
931 result.push_back(idx);
939 const std::string& comp_operator,
940 const size_t generation) {
943 return client_->get_compare(pattern, comp_operator, generation);
945 std::vector<int32_t> ret;
950 if (comp_operator ==
"=" || comp_operator ==
"<>") {
951 return getEquals(pattern, comp_operator, generation);
959 cache_index = std::make_shared<StringDictionary::compare_cache_value_t>();
964 [
this](decltype(
sorted_cache)::value_type
const&
a, decltype(pattern)& b) {
966 return string_lt(a_str.c_str_ptr, a_str.size, b.c_str(), b.size());
971 cache_index->diff = 1;
975 cache_str.c_str_ptr, cache_str.size, pattern.c_str(), pattern.size())) {
976 cache_index->index = cache_itr -
sorted_cache.begin() - 1;
977 cache_index->diff = 1;
980 cache_index->diff = 0;
1001 if (comp_operator ==
"<") {
1002 size_t idx = cache_index->index;
1003 if (cache_index->diff) {
1004 idx = cache_index->index + 1;
1005 if (cache_index->index == 0 && cache_index->diff > 0) {
1006 idx = cache_index->index;
1009 for (
size_t i = 0; i < idx; i++) {
1020 }
else if (comp_operator ==
"<=") {
1021 size_t idx = cache_index->index + 1;
1022 if (cache_index == 0 && cache_index->diff > 0) {
1023 idx = cache_index->index;
1025 for (
size_t i = 0; i < idx; i++) {
1034 }
else if (comp_operator ==
">") {
1035 size_t idx = cache_index->index + 1;
1036 if (cache_index->index == 0 && cache_index->diff > 0) {
1037 idx = cache_index->index;
1049 }
else if (comp_operator ==
">=") {
1050 size_t idx = cache_index->index;
1051 if (cache_index->diff) {
1052 idx = cache_index->index + 1;
1053 if (cache_index->index == 0 && cache_index->diff > 0) {
1054 idx = cache_index->index;
1060 }
else if (comp_operator ==
"=") {
1061 if (!cache_index->diff) {
1067 }
else if (comp_operator ==
"<>") {
1068 if (!cache_index->diff) {
1069 size_t idx = cache_index->index;
1070 for (
size_t i = 0; i < idx; i++) {
1084 std::runtime_error(
"Unsupported string comparison operator");
1092 const std::string& pattern,
1093 const char escape) {
1094 return regexp_like(str.c_str(), str.size(), pattern.c_str(), pattern.size(), escape);
1101 const size_t generation)
const {
1104 return client_->get_regexp_like(pattern, escape, generation);
1106 const auto cache_key = std::make_pair(pattern, escape);
1111 std::vector<int32_t>
result;
1112 std::vector<std::thread> workers;
1115 std::vector<std::vector<int32_t>> worker_results(worker_count);
1117 for (
int worker_idx = 0; worker_idx < worker_count; ++worker_idx) {
1118 workers.emplace_back([&worker_results,
1125 for (
size_t string_id = worker_idx; string_id < generation;
1126 string_id += worker_count) {
1129 worker_results[worker_idx].push_back(string_id);
1134 for (
auto& worker : workers) {
1137 for (
const auto& worker_result : worker_results) {
1138 result.insert(result.end(), worker_result.begin(), worker_result.end());
1140 const auto it_ok =
regex_cache_.insert(std::make_pair(cache_key, result));
1141 CHECK(it_ok.second);
1150 throw std::runtime_error(
1151 "copying dictionaries from remote server is not supported yet.");
1160 const bool multithreaded =
str_count_ > 10000;
1161 const auto worker_count =
1162 multithreaded ?
static_cast<size_t>(
cpu_threads()) :
size_t(1);
1164 std::vector<std::vector<std::string>> worker_results(worker_count);
1165 auto copy = [
this](std::vector<std::string>& str_list,
1166 const size_t start_id,
1167 const size_t end_id) {
1169 str_list.reserve(end_id - start_id);
1170 for (
size_t string_id = start_id; string_id < end_id; ++string_id) {
1174 if (multithreaded) {
1175 std::vector<std::future<void>> workers;
1176 const auto stride = (
str_count_ + (worker_count - 1)) / worker_count;
1177 for (
size_t worker_idx = 0, start = 0, end = std::min(start + stride,
str_count_);
1178 worker_idx < worker_count && start <
str_count_;
1179 ++worker_idx, start += stride, end = std::min(start + stride, str_count_)) {
1183 for (
auto& worker : workers) {
1187 CHECK_EQ(worker_results.size(), size_t(1));
1191 for (
const auto& worker_result : worker_results) {
1193 strings_cache_->end(), worker_result.begin(), worker_result.end());
1199 return string_id_string_dict_hash_table_.size() <= num_strings * 2;
1210 new_str_ids[bucket] = i;
1218 new_str_ids[bucket] = i;
1224 template <
class String>
1226 const size_t str_count,
1228 const size_t storage_high_water_mark,
1229 const std::vector<String>& input_strings,
1230 const std::vector<size_t>& string_memory_ids,
1231 const std::vector<string_dict_hash_t>& input_strings_hashes) noexcept {
1232 std::vector<int32_t> new_str_ids(string_id_string_dict_hash_table_.size() * 2,
1234 if (materialize_hashes_) {
1235 for (
size_t i = 0; i != str_count; ++i) {
1237 const uint32_t bucket = computeUniqueBucketWithHash(hash, new_str_ids);
1238 new_str_ids[bucket] = i;
1240 hash_cache_.resize(hash_cache_.size() * 2);
1242 for (
size_t storage_idx = 0; storage_idx != storage_high_water_mark; ++storage_idx) {
1243 const auto storage_string = getStringChecked(storage_idx);
1245 const uint32_t bucket = computeUniqueBucketWithHash(hash, new_str_ids);
1246 new_str_ids[bucket] = storage_idx;
1248 for (
size_t memory_idx = 0; memory_idx != string_memory_ids.size(); ++memory_idx) {
1249 const size_t string_memory_id = string_memory_ids[memory_idx];
1250 const uint32_t bucket = computeUniqueBucketWithHash(
1251 input_strings_hashes[string_memory_id], new_str_ids);
1252 new_str_ids[bucket] = storage_high_water_mark + memory_idx;
1255 string_id_string_dict_hash_table_.swap(new_str_ids);
1260 if (str.size() == 0) {
1261 return inline_int_null_value<int32_t>();
1263 CHECK(str.size() <= MAX_STRLEN);
1266 std::shared_lock<std::shared_mutex>
read_lock(rw_mutex_);
1267 const uint32_t bucket = computeBucket(hash, str, string_id_string_dict_hash_table_);
1268 if (string_id_string_dict_hash_table_[bucket] != INVALID_STR_ID) {
1269 return string_id_string_dict_hash_table_[bucket];
1272 std::lock_guard<std::shared_mutex>
write_lock(rw_mutex_);
1273 if (fillRateIsHigh(str_count_)) {
1275 increaseHashTableCapacity();
1279 const uint32_t bucket = computeBucket(hash, str, string_id_string_dict_hash_table_);
1280 if (string_id_string_dict_hash_table_[bucket] == INVALID_STR_ID) {
1282 <<
"Maximum number (" << str_count_
1283 <<
") of Dictionary encoded Strings reached for this column, offset path "
1286 appendToStorage(str);
1287 string_id_string_dict_hash_table_[bucket] =
static_cast<int32_t
>(str_count_);
1288 if (materialize_hashes_) {
1289 hash_cache_[str_count_] = hash;
1292 invalidateInvertedIndex();
1294 return string_id_string_dict_hash_table_[bucket];
1298 const auto str_canary = getStringFromStorage(string_id);
1299 CHECK(!str_canary.canary);
1300 return std::string(str_canary.c_str_ptr, str_canary.size);
1304 const int string_id)
const noexcept {
1305 const auto str_canary = getStringFromStorage(string_id);
1306 CHECK(!str_canary.canary);
1307 return std::make_pair(str_canary.c_str_ptr, str_canary.size);
1310 template <
class String>
1313 const String& input_string,
1314 const std::vector<int32_t>& string_id_string_dict_hash_table)
const noexcept {
1315 const size_t string_dict_hash_table_size = string_id_string_dict_hash_table.size();
1316 uint32_t bucket = hash & (string_dict_hash_table_size - 1);
1318 const int32_t candidate_string_id = string_id_string_dict_hash_table[bucket];
1319 if (candidate_string_id ==
1323 if ((materialize_hashes_ && hash == hash_cache_[candidate_string_id]) ||
1324 !materialize_hashes_) {
1325 const auto candidate_string = getStringFromStorageFast(candidate_string_id);
1326 if (input_string.size() == candidate_string.size() &&
1327 !memcmp(input_string.data(), candidate_string.data(), input_string.size())) {
1333 if (++bucket == string_dict_hash_table_size) {
1340 template <
class String>
1343 const String& input_string,
1344 const std::vector<int32_t>& string_id_string_dict_hash_table,
1345 const size_t storage_high_water_mark,
1346 const std::vector<String>& input_strings,
1347 const std::vector<size_t>& string_memory_ids)
const noexcept {
1348 uint32_t bucket = input_string_hash & (string_id_string_dict_hash_table.size() - 1);
1350 const int32_t candidate_string_id = string_id_string_dict_hash_table[bucket];
1351 if (candidate_string_id ==
1355 if (!materialize_hashes_ || (input_string_hash == hash_cache_[candidate_string_id])) {
1356 if (candidate_string_id > 0 &&
1357 static_cast<size_t>(candidate_string_id) >= storage_high_water_mark) {
1360 size_t memory_offset =
1361 static_cast<size_t>(candidate_string_id - storage_high_water_mark);
1362 const String candidate_string = input_strings[string_memory_ids[memory_offset]];
1363 if (input_string.size() == candidate_string.size() &&
1364 !memcmp(input_string.data(), candidate_string.data(), input_string.size())) {
1370 const auto candidate_storage_string =
1371 getStringFromStorageFast(candidate_string_id);
1372 if (input_string.size() == candidate_storage_string.size() &&
1373 !memcmp(input_string.data(),
1374 candidate_storage_string.data(),
1375 input_string.size())) {
1383 if (++bucket == string_id_string_dict_hash_table.size()) {
1392 const std::vector<int32_t>& string_id_string_dict_hash_table) noexcept {
1393 const size_t string_dict_hash_table_size = string_id_string_dict_hash_table.size();
1394 uint32_t bucket = hash & (string_dict_hash_table_size - 1);
1396 if (string_id_string_dict_hash_table[bucket] ==
1402 if (++bucket == string_dict_hash_table_size) {
1410 const size_t write_length) {
1412 const size_t min_capacity_needed =
1429 const size_t write_length) {
1432 const size_t min_capacity_needed =
1448 template <
class String>
1451 checkAndConditionallyIncreasePayloadCapacity(str.size());
1452 memcpy(payload_map_ + payload_file_off_, str.data(), str.size());
1456 payload_file_off_ += str.size();
1458 checkAndConditionallyIncreaseOffsetCapacity(
sizeof(str_meta));
1459 memcpy(offset_map_ + str_count_, &str_meta,
sizeof(str_meta));
1462 template <
class String>
1464 const std::vector<String>& input_strings,
1465 const std::vector<size_t>& string_memory_ids,
1466 const size_t sum_new_strings_lengths) noexcept {
1467 const size_t num_strings = string_memory_ids.size();
1469 checkAndConditionallyIncreasePayloadCapacity(sum_new_strings_lengths);
1470 checkAndConditionallyIncreaseOffsetCapacity(
sizeof(
StringIdxEntry) * num_strings);
1472 for (
size_t i = 0; i < num_strings; ++i) {
1473 const size_t string_idx = string_memory_ids[i];
1474 const String str = input_strings[string_idx];
1475 const size_t str_size(str.size());
1476 memcpy(payload_map_ + payload_file_off_, str.data(), str_size);
1477 StringIdxEntry str_meta{
static_cast<uint64_t
>(payload_file_off_), str_size};
1478 payload_file_off_ += str_size;
1479 memcpy(offset_map_ + str_count_ + i, &str_meta,
sizeof(str_meta));
1486 return {payload_map_ + str_meta->
off, str_meta->
size};
1490 const int string_id)
const noexcept {
1497 if (str_meta->
size == 0xffff) {
1499 return {
nullptr, 0,
true};
1501 return {payload_map_ + str_meta->
off, str_meta->
size,
false};
1506 payload_file_size_ += addStorageCapacity(payload_fd_, min_capacity_requested);
1508 payload_map_ =
static_cast<char*
>(
1509 addMemoryCapacity(payload_map_, payload_file_size_, min_capacity_requested));
1515 offset_file_size_ += addStorageCapacity(offset_fd_, min_capacity_requested);
1518 addMemoryCapacity(offset_map_, offset_file_size_, min_capacity_requested));
1524 const size_t min_capacity_requested) noexcept {
1525 const size_t canary_buff_size_to_add =
1529 if (canary_buffer_size < canary_buff_size_to_add) {
1530 CANARY_BUFFER =
static_cast<char*
>(realloc(CANARY_BUFFER, canary_buff_size_to_add));
1531 canary_buffer_size = canary_buff_size_to_add;
1532 CHECK(CANARY_BUFFER);
1533 memset(CANARY_BUFFER, 0xff, canary_buff_size_to_add);
1536 CHECK_NE(lseek(fd, 0, SEEK_END), -1);
1537 const auto write_return =
write(fd, CANARY_BUFFER, canary_buff_size_to_add);
1538 CHECK(write_return > 0 &&
1539 (static_cast<size_t>(write_return) == canary_buff_size_to_add));
1540 return canary_buff_size_to_add;
1545 const size_t min_capacity_requested) noexcept {
1546 const size_t canary_buff_size_to_add =
1549 if (canary_buffer_size < canary_buff_size_to_add) {
1551 reinterpret_cast<char*
>(realloc(CANARY_BUFFER, canary_buff_size_to_add));
1552 canary_buffer_size = canary_buff_size_to_add;
1553 CHECK(CANARY_BUFFER);
1554 memset(CANARY_BUFFER, 0xff, canary_buff_size_to_add);
1556 void* new_addr = realloc(addr, mem_size + canary_buff_size_to_add);
1558 void* write_addr =
reinterpret_cast<void*
>(
static_cast<char*
>(new_addr) + mem_size);
1559 CHECK(memcpy(write_addr, CANARY_BUFFER, canary_buff_size_to_add));
1560 mem_size += canary_buff_size_to_add;
1601 return static_cast<bool>(
client_);
1607 std::vector<int32_t> temp_sorted_cache;
1608 for (
size_t i = cur_cache_size; i <
str_count_; i++) {
1609 temp_sorted_cache.push_back(i);
1621 std::sort(cache.begin(), cache.end(), [
this](int32_t
a, int32_t b) {
1624 return string_lt(a_str.c_str_ptr, a_str.size, b_str.c_str_ptr, b_str.size);
1630 std::vector<int32_t> updated_cache(temp_sorted_cache.size() +
sorted_cache.size());
1631 size_t t_idx = 0, s_idx = 0, idx = 0;
1632 for (; t_idx < temp_sorted_cache.size() && s_idx <
sorted_cache.size(); idx++) {
1635 const auto insert_from_temp_cache =
1636 string_lt(t_string.c_str_ptr, t_string.size, s_string.c_str_ptr, s_string.size);
1637 if (insert_from_temp_cache) {
1638 updated_cache[idx] = temp_sorted_cache[t_idx++];
1643 while (t_idx < temp_sorted_cache.size()) {
1644 updated_cache[idx++] = temp_sorted_cache[t_idx++];
1653 std::vector<int32_t>& dest_ids,
1655 const std::vector<int32_t>& source_ids,
1657 const std::vector<std::string const*>& transient_string_vec) {
1658 std::vector<std::string> strings;
1660 for (
const int32_t source_id : source_ids) {
1661 if (source_id == std::numeric_limits<int32_t>::min()) {
1662 strings.emplace_back(
"");
1663 }
else if (source_id < 0) {
1665 CHECK_LT(string_index, transient_string_vec.size()) <<
"source_id=" << source_id;
1666 strings.emplace_back(*transient_string_vec[string_index]);
1668 strings.push_back(source_dict->
getString(source_id));
1672 dest_ids.resize(strings.size());
1677 std::vector<std::vector<int32_t>>& dest_array_ids,
1679 const std::vector<std::vector<int32_t>>& source_array_ids,
1681 dest_array_ids.resize(source_array_ids.size());
1683 std::atomic<size_t> row_idx{0};
1684 auto processor = [&row_idx, &dest_array_ids, dest_dict, &source_array_ids, source_dict](
1687 auto row = row_idx.fetch_add(1);
1689 if (row >= dest_array_ids.size()) {
1692 const auto& source_ids = source_array_ids[row];
1693 auto& dest_ids = dest_array_ids[row];
1698 const int num_worker_threads = std::thread::hardware_concurrency();
1700 if (source_array_ids.size() / num_worker_threads > 10) {
1701 std::vector<std::future<void>> worker_threads;
1702 for (
int i = 0; i < num_worker_threads; ++i) {
1706 for (
auto& child : worker_threads) {
1709 for (
auto& child : worker_threads) {
1718 const size_t generation)
const {
1731 CHECK_LE(num_strings, std::numeric_limits<int32_t>::max());
1733 std::vector<std::string_view> string_views(num_strings);
1735 if (num_strings == 0) {
1736 return string_views;
1738 constexpr int64_t tbb_parallel_threshold{1000};
1739 if (num_strings < tbb_parallel_threshold) {
1741 for (int32_t string_idx = 0; string_idx < num_strings; ++string_idx) {
1745 constexpr int64_t target_strings_per_thread{1000};
1747 std::thread::hardware_concurrency(), num_strings, target_strings_per_thread);
1751 tbb::task_arena limited_arena(thread_info.
num_threads);
1753 limited_arena.execute([&] {
1755 tbb::blocked_range<int64_t>(
1757 [&](
const tbb::blocked_range<int64_t>& r) {
1759 const int32_t start_idx = r.begin();
1760 const int32_t end_idx = r.end();
1761 for (int32_t string_idx = start_idx; string_idx != end_idx; ++string_idx) {
1765 tbb::simple_partitioner());
1768 return string_views;
1776 const std::shared_ptr<StringDictionary> dest_dict,
1780 const size_t num_dest_strings = dest_dict->storageEntryCount();
1781 std::vector<int32_t> translated_ids(num_source_strings);
1784 translated_ids.data(),
1789 dest_transient_lookup_callback,
1791 return translated_ids;
1795 const int32_t source_dict_id,
1796 const int32_t dest_db_id,
1797 const int32_t dest_dict_id,
1798 std::shared_lock<std::shared_mutex>& source_read_lock,
1799 std::shared_lock<std::shared_mutex>& dest_read_lock) {
1800 const bool dicts_are_same =
1801 source_db_id == dest_db_id && source_dict_id == dest_dict_id;
1802 const bool source_dict_is_locked_first =
1803 source_db_id < dest_db_id ||
1804 (source_db_id == dest_db_id && source_dict_id < dest_dict_id);
1805 if (dicts_are_same) {
1807 dest_read_lock.lock();
1808 }
else if (source_dict_is_locked_first) {
1809 source_read_lock.lock();
1810 dest_read_lock.lock();
1812 dest_read_lock.lock();
1813 source_read_lock.lock();
1819 int32_t* translated_ids,
1820 const int64_t source_generation,
1821 const int64_t dest_generation,
1822 const bool dest_has_transients,
1824 const std::vector<StringOps_Namespace::StringOpInfo>& string_op_infos)
const {
1828 const int64_t num_source_strings = source_generation;
1829 const int64_t num_dest_strings = dest_generation;
1832 if (num_source_strings == 0L) {
1841 throw std::runtime_error(
1842 "Cannot translate between a local source and remote destination dictionary.");
1847 std::shared_lock<std::shared_mutex> source_read_lock(
rw_mutex_, std::defer_lock);
1848 std::shared_lock<std::shared_mutex> dest_read_lock(dest_dict->
rw_mutex_,
1864 const bool dest_dictionary_is_empty = (num_dest_strings == 0);
1866 constexpr int64_t target_strings_per_thread{1000};
1868 std::thread::hardware_concurrency(), num_source_strings, target_strings_per_thread);
1877 const StringOps_Namespace::StringOps string_ops(string_op_infos);
1878 const bool has_string_ops = string_ops.size();
1880 tbb::task_arena limited_arena(thread_info.
num_threads);
1881 std::vector<size_t> num_strings_not_translated_per_thread(thread_info.
num_threads, 0UL);
1882 constexpr
bool short_circuit_empty_dictionary_translations{
false};
1883 limited_arena.execute([&] {
1885 if (short_circuit_empty_dictionary_translations && dest_dictionary_is_empty) {
1887 tbb::blocked_range<int32_t>(
1891 [&](
const tbb::blocked_range<int32_t>& r) {
1892 const int32_t start_idx = r.begin();
1893 const int32_t end_idx = r.end();
1894 for (int32_t string_idx = start_idx; string_idx != end_idx; ++string_idx) {
1898 tbb::simple_partitioner());
1899 num_strings_not_translated_per_thread[0] += num_source_strings;
1908 tbb::blocked_range<int32_t>(
1912 [&](
const tbb::blocked_range<int32_t>& r) {
1913 const int32_t start_idx = r.begin();
1914 const int32_t end_idx = r.end();
1915 size_t num_strings_not_translated = 0;
1916 std::string string_ops_storage;
1918 for (int32_t source_string_id = start_idx; source_string_id != end_idx;
1919 ++source_string_id) {
1920 const std::string_view source_str =
1925 if (source_str.empty()) {
1926 translated_ids[source_string_id] = inline_int_null_value<int32_t>();
1940 const auto translated_string_id =
1942 translated_ids[source_string_id] = translated_string_id;
1945 translated_string_id >= num_dest_strings) {
1946 if (dest_has_transients) {
1947 num_strings_not_translated +=
1948 dest_transient_lookup_callback(source_str, source_string_id);
1950 num_strings_not_translated++;
1955 const size_t tbb_thread_idx = tbb::this_task_arena::current_thread_index();
1956 num_strings_not_translated_per_thread[tbb_thread_idx] +=
1957 num_strings_not_translated;
1959 tbb::simple_partitioner());
1962 size_t total_num_strings_not_translated = 0;
1963 for (int64_t thread_idx = 0; thread_idx < thread_info.num_threads; ++thread_idx) {
1964 total_num_strings_not_translated += num_strings_not_translated_per_thread[thread_idx];
1966 return total_num_strings_not_translated;
1972 const std::vector<int32_t>& source_ids,
1973 const DictRef source_dict_ref,
1974 const int32_t dest_generation) {
1975 DictRef temp_dict_ref(-1, -1);
1978 dest_ids, dest_dict_ref, source_ids, source_dict_ref, dest_generation);
StringIdxEntry * offset_map_
void translate_string_ids(std::vector< int32_t > &dest_ids, const DictRef dest_dict_ref, const std::vector< int32_t > &source_ids, const DictRef source_dict_ref, const int32_t dest_generation)
size_t payload_file_size_
bool isClient() const noexcept
void increaseHashTableCapacity() noexcept
void checkAndConditionallyIncreasePayloadCapacity(const size_t write_length)
string_dict_hash_t hash_string(const std::string_view &str)
size_t addStorageCapacity(int fd, const size_t min_capacity_requested=0) noexcept
std::vector< int32_t > getRegexpLike(const std::string &pattern, const char escape, const size_t generation) const
void operator()(std::string_view const, int32_t const string_id) override
size_t getBulk(const std::vector< String > &string_vec, T *encoded_vec) const
int64_t num_elems_per_thread
heavyai::shared_lock< heavyai::shared_mutex > read_lock
std::vector< int32_t > buildDictionaryTranslationMap(const std::shared_ptr< StringDictionary > dest_dict, StringLookupCallback const &dest_transient_lookup_callback) const
RUNTIME_EXPORT DEVICE bool string_eq(const char *lhs, const int32_t lhs_len, const char *rhs, const int32_t rhs_len)
std::vector< std::string > copyStrings() const
std::pair< char *, size_t > getStringBytesChecked(const int string_id) const noexcept
size_t storageEntryCount() const
void addOffsetCapacity(const size_t min_capacity_requested=0) noexcept
uint32_t computeBucketFromStorageAndMemory(const string_dict_hash_t input_string_hash, const String &input_string, const std::vector< int32_t > &string_id_string_dict_hash_table, const size_t storage_high_water_mark, const std::vector< String > &input_strings, const std::vector< size_t > &string_memory_ids) const noexcept
std::string getStringChecked(const int string_id) const noexcept
std::vector< string_dict_hash_t > hash_cache_
DictionaryCache< std::string, compare_cache_value_t > compare_cache_
DEVICE void sort(ARGS &&...args)
bool fillRateIsHigh(const size_t num_strings) const noexcept
void * addMemoryCapacity(void *addr, size_t &mem_size, const size_t min_capacity_requested=0) noexcept
Constants for Builtin SQL Types supported by HEAVY.AI.
std::string offsets_path_
heavyai::unique_lock< heavyai::shared_mutex > write_lock
static void populate_string_ids(std::vector< int32_t > &dest_ids, StringDictionary *dest_dict, const std::vector< int32_t > &source_ids, const StringDictionary *source_dict, const std::vector< std::string const * > &transient_string_vec={})
Populates provided dest_ids vector with string ids corresponding to given source strings.
std::unordered_map< std::string, int32_t > map_
std::shared_mutex rw_mutex_
std::string_view getStringFromStorageFast(const int string_id) const noexcept
int32_t getOrAdd(const std::string &str) noexcept
void throw_string_too_long_error(std::string_view str, const DictRef &dict_ref)
std::map< std::pair< std::string, char >, std::vector< int32_t > > regex_cache_
std::unique_ptr< StringDictionaryClient > client_
std::string getStringUnlocked(int32_t string_id) const noexcept
size_t write(FILE *f, const size_t offset, const size_t size, const int8_t *buf)
Writes the specified number of bytes to the offset position in file f from buf.
RUNTIME_EXPORT DEVICE bool string_lt(const char *lhs, const int32_t lhs_len, const char *rhs, const int32_t rhs_len)
int32_t getIdOfString(const String &) const
bool is_regexp_like(const std::string &str, const std::string &pattern, const char escape)
static constexpr size_t MAX_STRCOUNT
std::vector< int32_t > getEquals(std::string pattern, std::string comp_operator, size_t generation)
uint32_t computeBucket(const string_dict_hash_t hash, const String &input_string, const std::vector< int32_t > &string_id_string_dict_hash_table) const noexcept
future< Result > async(Fn &&fn, Args &&...args)
static constexpr int32_t INVALID_STR_ID
std::shared_ptr< std::vector< std::string > > strings_cache_
std::vector< int32_t > getCompare(const std::string &pattern, const std::string &comp_operator, const size_t generation)
DEVICE auto copy(ARGS &&...args)
int open(const char *path, int flags, int mode)
StringDictionary(const DictRef &dict_ref, const std::string &folder, const bool isTemp, const bool recover, const bool materializeHashes=false, size_t initial_capacity=256)
void order_translation_locks(const int32_t source_db_id, const int32_t source_dict_id, const int32_t dest_db_id, const int32_t dest_dict_id, std::shared_lock< std::shared_mutex > &source_read_lock, std::shared_lock< std::shared_mutex > &dest_read_lock)
RUNTIME_EXPORT DEVICE bool string_like(const char *str, const int32_t str_len, const char *pattern, const int32_t pat_len, const char escape_char)
void appendToStorageBulk(const std::vector< String > &input_strings, const std::vector< size_t > &string_memory_ids, const size_t sum_new_strings_lengths) noexcept
RUNTIME_EXPORT DEVICE bool string_like_simple(const char *str, const int32_t str_len, const char *pattern, const int32_t pat_len)
void addPayloadCapacity(const size_t min_capacity_requested=0) noexcept
bool is_like(const std::string &str, const std::string &pattern, const bool icase, const bool is_simple, const char escape)
std::map< std::string, int32_t > equal_cache_
uint32_t computeUniqueBucketWithHash(const string_dict_hash_t hash, const std::vector< int32_t > &string_id_string_dict_hash_table) noexcept
void getOrAddBulkArray(const std::vector< std::vector< String >> &string_array_vec, std::vector< std::vector< int32_t >> &ids_array_vec)
void translate_string_ids(std::vector< int32_t > &dest_ids, const LeafHostInfo &dict_server_host, const DictRef dest_dict_ref, const std::vector< int32_t > &source_ids, const DictRef source_dict_ref, const int32_t dest_generation)
Functions to support the LIKE and ILIKE operator in SQL. Only single-byte character set is supported ...
int32_t getUnlocked(const std::string_view sv) const noexcept
void appendToStorage(const String str) noexcept
void throw_encoding_error(std::string_view str, const DictRef &dict_ref)
int checked_open(const char *path, const bool recover)
bool g_enable_smem_group_by true
void getOrAddBulk(const std::vector< String > &string_vec, T *encoded_vec)
std::unordered_map< std::string, int32_t > moveMap()
std::pair< char *, size_t > getStringBytes(int32_t string_id) const noexcept
void processDictionaryFutures(std::vector< std::future< std::vector< std::pair< string_dict_hash_t, unsigned int >>>> &dictionary_futures)
const int SYSTEM_PAGE_SIZE
bool checkpoint() noexcept
std::vector< int32_t > getLike(const std::string &pattern, const bool icase, const bool is_simple, const char escape, const size_t generation) const
void mergeSortedCache(std::vector< int32_t > &temp_sorted_cache)
DEVICE auto lower_bound(ARGS &&...args)
void eachStringSerially(int64_t const generation, StringCallback &) const
int32_t getDictId() const noexcept
RUNTIME_EXPORT DEVICE bool string_ilike_simple(const char *str, const int32_t str_len, const char *pattern, const int32_t pat_len)
size_t getNumStringsFromStorage(const size_t storage_slots) const noexcept
void update_leaf(const LeafHostInfo &host_info)
int64_t num_elems_per_thread
std::string getString(int32_t string_id) const
void hashStrings(const std::vector< String > &string_vec, std::vector< string_dict_hash_t > &hashes) const noexcept
std::vector< std::string_view > getStringViews() const
int msync(void *addr, size_t length, bool async)
int32_t getDbId() const noexcept
std::unique_ptr< StringDictionaryClient > client_no_timeout_
void parallel_for(const blocked_range< Int > &range, const Body &body, const Partitioner &p=Partitioner())
void increaseHashTableCapacityFromStorageAndMemory(const size_t str_count, const size_t storage_high_water_mark, const std::vector< String > &input_strings, const std::vector< size_t > &string_memory_ids, const std::vector< string_dict_hash_t > &input_strings_hashes) noexcept
std::function< int32_t(std::string const &)> makeLambdaStringToId() const
void checkAndConditionallyIncreaseOffsetCapacity(const size_t write_length)
static void populate_string_array_ids(std::vector< std::vector< int32_t >> &dest_array_ids, StringDictionary *dest_dict, const std::vector< std::vector< int32_t >> &source_array_ids, const StringDictionary *source_dict)
bool g_enable_watchdog false
void invalidateInvertedIndex() noexcept
uint32_t string_dict_hash_t
#define DEBUG_TIMER(name)
void checked_munmap(void *addr, size_t length)
const uint64_t round_up_p2(const uint64_t num)
std::string toString() const
std::vector< int32_t > string_id_string_dict_hash_table_
ThreadInfo(const int64_t max_thread_count, const int64_t num_elems, const int64_t target_elems_per_thread)
void sortCache(std::vector< int32_t > &cache)
static constexpr size_t MAX_STRLEN
void getOrAddBulkParallel(const std::vector< String > &string_vec, T *encoded_vec)
std::function< bool(std::string_view, int32_t string_id)> StringLookupCallback
std::map< std::tuple< std::string, bool, bool, char >, std::vector< int32_t > > like_cache_
bool g_enable_stringdict_parallel
PayloadString getStringFromStorage(const int string_id) const noexcept
RUNTIME_EXPORT DEVICE bool regexp_like(const char *str, const int32_t str_len, const char *pattern, const int32_t pat_len, const char escape_char)
size_t file_size(const int fd)
static unsigned transientIdToIndex(int32_t const id)
void operator()(std::string const &str, int32_t const string_id) override
DEVICE void swap(ARGS &&...args)
std::vector< int32_t > sorted_cache
int32_t getOrAddImpl(const std::string_view &str) noexcept
~StringDictionary() noexcept
void * checked_mmap(const int fd, const size_t sz)
RUNTIME_EXPORT DEVICE bool string_ilike(const char *str, const int32_t str_len, const char *pattern, const int32_t pat_len, const char escape_char)