1 #include "database-builder.h"
4 #include "turbopfor-encode.h"
10 #include <string_view>
13 #include <sys/types.h>
18 #define P4NENC_BOUND(n) ((n + 127) / 128 + (n + 32) * sizeof(uint32_t))
20 #define NUM_TRIGRAMS 16777216
23 using namespace std::chrono;
25 constexpr unsigned num_overflow_slots = 16;
27 string zstd_compress(const string &src, ZSTD_CDict *cdict, string *tempbuf);
29 static inline uint32_t read_unigram(const string_view s, size_t idx)
32 return (unsigned char)s[idx];
38 static inline uint32_t read_trigram(const string_view s, size_t start)
40 return read_unigram(s, start) |
41 (read_unigram(s, start + 1) << 8) |
42 (read_unigram(s, start + 2) << 16);
45 class PostingListBuilder {
47 inline void add_docid(uint32_t docid);
51 size_t num_docids = 0;
54 void write_header(uint32_t docid);
57 vector<uint32_t> pending_deltas;
59 uint32_t last_block_end, last_docid = -1;
62 void PostingListBuilder::add_docid(uint32_t docid)
64 // Deduplicate against the last inserted value, if any.
65 if (docid == last_docid) {
69 if (num_docids == 0) {
73 last_block_end = last_docid = docid;
77 pending_deltas.push_back(docid - last_docid - 1);
79 if (pending_deltas.size() == 128) {
81 pending_deltas.clear();
82 last_block_end = docid;
87 void PostingListBuilder::finish()
89 if (pending_deltas.empty()) {
93 assert(!encoded.empty()); // write_header() should already have run.
95 // No interleaving for partial blocks.
96 unsigned char buf[P4NENC_BOUND(128)];
97 unsigned char *end = encode_pfor_single_block<128>(pending_deltas.data(), pending_deltas.size(), /*interleaved=*/false, buf);
98 encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
101 void PostingListBuilder::append_block()
103 unsigned char buf[P4NENC_BOUND(128)];
104 assert(pending_deltas.size() == 128);
105 unsigned char *end = encode_pfor_single_block<128>(pending_deltas.data(), 128, /*interleaved=*/true, buf);
106 encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
109 void PostingListBuilder::write_header(uint32_t docid)
111 unsigned char buf[P4NENC_BOUND(1)];
112 unsigned char *end = write_baseval(docid, buf);
113 encoded.append(reinterpret_cast<char *>(buf), end - buf);
116 void DictionaryBuilder::add_file(string filename)
118 if (keep_current_block) { // Only bother saving the filenames if we're actually keeping the block.
119 if (!current_block.empty()) {
120 current_block.push_back('\0');
122 current_block += filename;
124 if (++num_files_in_block == block_size) {
129 void DictionaryBuilder::flush_block()
131 if (keep_current_block) {
132 if (slot_for_current_block == -1) {
133 lengths.push_back(current_block.size());
134 sampled_blocks.push_back(move(current_block));
136 lengths[slot_for_current_block] = current_block.size();
137 sampled_blocks[slot_for_current_block] = move(current_block);
140 current_block.clear();
141 num_files_in_block = 0;
144 if (block_num < blocks_to_keep) {
145 keep_current_block = true;
146 slot_for_current_block = -1;
148 // Keep every block with equal probability (reservoir sampling).
149 uint64_t idx = uniform_int_distribution<uint64_t>(0, block_num)(reservoir_rand);
150 keep_current_block = (idx < blocks_to_keep);
151 slot_for_current_block = idx;
155 string DictionaryBuilder::train(size_t buf_size)
157 string dictionary_buf;
158 sort(sampled_blocks.begin(), sampled_blocks.end()); // Seemingly important for decompression speed.
159 for (const string &block : sampled_blocks) {
160 dictionary_buf += block;
164 buf.resize(buf_size);
165 size_t ret = ZDICT_trainFromBuffer(&buf[0], buf_size, dictionary_buf.data(), lengths.data(), lengths.size());
166 if (ret == size_t(-1)) {
169 dprintf("Sampled %zu bytes in %zu blocks, built a dictionary of size %zu\n", dictionary_buf.size(), lengths.size(), ret);
172 sampled_blocks.clear();
178 Corpus::Corpus(FILE *outfp, size_t block_size, ZSTD_CDict *cdict)
179 : invindex(new PostingListBuilder *[NUM_TRIGRAMS]), outfp(outfp), block_size(block_size), cdict(cdict)
181 fill(invindex.get(), invindex.get() + NUM_TRIGRAMS, nullptr);
186 for (unsigned i = 0; i < NUM_TRIGRAMS; ++i) {
191 PostingListBuilder &Corpus::get_pl_builder(uint32_t trgm)
193 if (invindex[trgm] == nullptr) {
194 invindex[trgm] = new PostingListBuilder;
196 return *invindex[trgm];
199 void Corpus::add_file(string filename)
202 if (!current_block.empty()) {
203 current_block.push_back('\0');
205 current_block += filename;
206 if (++num_files_in_block == block_size) {
211 void Corpus::flush_block()
213 if (current_block.empty()) {
217 uint32_t docid = num_blocks;
220 const char *ptr = current_block.c_str();
221 while (ptr < current_block.c_str() + current_block.size()) {
224 for (size_t j = 0; j < s.size() - 2; ++j) {
225 uint32_t trgm = read_trigram(s, j);
226 get_pl_builder(trgm).add_docid(docid);
232 // Compress and add the filename block.
233 filename_blocks.push_back(ftell(outfp));
234 string compressed = zstd_compress(current_block, cdict, &tempbuf);
235 if (fwrite(compressed.data(), compressed.size(), 1, outfp) != 1) {
240 current_block.clear();
241 num_files_in_block = 0;
245 void Corpus::finish()
250 size_t Corpus::num_trigrams() const
253 for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
254 if (invindex[trgm] != nullptr) {
261 string zstd_compress(const string &src, ZSTD_CDict *cdict, string *tempbuf)
263 static ZSTD_CCtx *ctx = nullptr;
264 if (ctx == nullptr) {
265 ctx = ZSTD_createCCtx();
268 size_t max_size = ZSTD_compressBound(src.size());
269 if (tempbuf->size() < max_size) {
270 tempbuf->resize(max_size);
273 if (cdict == nullptr) {
274 size = ZSTD_compressCCtx(ctx, &(*tempbuf)[0], max_size, src.data(), src.size(), /*level=*/6);
276 size = ZSTD_compress_usingCDict(ctx, &(*tempbuf)[0], max_size, src.data(), src.size(), cdict);
278 return string(tempbuf->data(), size);
281 bool is_prime(uint32_t x)
283 if ((x % 2) == 0 || (x % 3) == 0) {
286 uint32_t limit = ceil(sqrt(x));
287 for (uint32_t factor = 5; factor <= limit; ++factor) {
288 if ((x % factor) == 0) {
295 uint32_t next_prime(uint32_t x)
300 while (!is_prime(x)) {
306 unique_ptr<Trigram[]> create_hashtable(Corpus &corpus, const vector<uint32_t> &all_trigrams, uint32_t ht_size, uint32_t num_overflow_slots)
308 unique_ptr<Trigram[]> ht(new Trigram[ht_size + num_overflow_slots + 1]); // 1 for the sentinel element at the end.
309 for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
310 ht[i].trgm = uint32_t(-1);
311 ht[i].num_docids = 0;
314 for (uint32_t trgm : all_trigrams) {
315 // We don't know offset yet, so set it to zero.
316 Trigram to_insert{ trgm, uint32_t(corpus.get_pl_builder(trgm).num_docids), 0 };
318 uint32_t bucket = hash_trigram(trgm, ht_size);
319 unsigned distance = 0;
320 while (ht[bucket].num_docids != 0) {
321 // Robin Hood hashing; reduces the longest distance by a lot.
322 unsigned other_distance = bucket - hash_trigram(ht[bucket].trgm, ht_size);
323 if (distance > other_distance) {
324 swap(to_insert, ht[bucket]);
325 distance = other_distance;
328 ++bucket, ++distance;
329 if (distance > num_overflow_slots) {
333 ht[bucket] = to_insert;
338 DatabaseBuilder::DatabaseBuilder(const char *outfile, int block_size, string dictionary)
339 : outfile(outfile), block_size(block_size)
343 string path = outfile;
344 path.resize(path.find_last_of('/') + 1);
345 int fd = open(path.c_str(), O_WRONLY | O_TMPFILE, 0640);
347 perror(path.c_str());
351 outfp = fdopen(fd, "wb");
352 if (outfp == nullptr) {
358 memcpy(hdr.magic, "\0plocate", 8);
359 hdr.version = -1; // Mark as broken.
360 hdr.hashtable_size = 0; // Not known yet.
361 hdr.extra_ht_slots = num_overflow_slots;
363 hdr.hash_table_offset_bytes = -1; // We don't know these offsets yet.
365 hdr.filename_index_offset_bytes = -1;
366 hdr.zstd_dictionary_length_bytes = -1;
367 fwrite(&hdr, sizeof(hdr), 1, outfp);
369 if (dictionary.empty()) {
370 hdr.zstd_dictionary_offset_bytes = 0;
371 hdr.zstd_dictionary_length_bytes = 0;
373 hdr.zstd_dictionary_offset_bytes = ftell(outfp);
374 fwrite(dictionary.data(), dictionary.size(), 1, outfp);
375 hdr.zstd_dictionary_length_bytes = dictionary.size();
376 cdict = ZSTD_createCDict(dictionary.data(), dictionary.size(), /*level=*/6);
380 Corpus *DatabaseBuilder::start_corpus()
382 corpus_start = steady_clock::now();
383 corpus = new Corpus(outfp, block_size, cdict);
387 void DatabaseBuilder::finish_corpus()
390 hdr.num_docids = corpus->filename_blocks.size();
392 // Stick an empty block at the end as sentinel.
393 corpus->filename_blocks.push_back(ftell(outfp));
394 const size_t bytes_for_filenames = corpus->filename_blocks.back() - corpus->filename_blocks.front();
396 // Write the offsets to the filenames.
397 hdr.filename_index_offset_bytes = ftell(outfp);
398 const size_t bytes_for_filename_index = corpus->filename_blocks.size() * sizeof(uint64_t);
399 fwrite(corpus->filename_blocks.data(), corpus->filename_blocks.size(), sizeof(uint64_t), outfp);
400 corpus->filename_blocks.clear();
401 corpus->filename_blocks.shrink_to_fit();
403 // Finish up encoding the posting lists.
404 size_t trigrams = 0, longest_posting_list = 0;
405 size_t bytes_for_posting_lists = 0;
406 for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
407 if (!corpus->seen_trigram(trgm))
409 PostingListBuilder &pl_builder = corpus->get_pl_builder(trgm);
411 longest_posting_list = max(longest_posting_list, pl_builder.num_docids);
412 trigrams += pl_builder.num_docids;
413 bytes_for_posting_lists += pl_builder.encoded.size();
415 size_t num_trigrams = corpus->num_trigrams();
416 dprintf("%zu files, %zu different trigrams, %zu entries, avg len %.2f, longest %zu\n",
417 corpus->num_files, num_trigrams, trigrams, double(trigrams) / num_trigrams, longest_posting_list);
418 dprintf("%zu bytes used for posting lists (%.2f bits/entry)\n", bytes_for_posting_lists, 8 * bytes_for_posting_lists / double(trigrams));
420 dprintf("Building posting lists took %.1f ms.\n\n", 1e3 * duration<float>(steady_clock::now() - corpus_start).count());
422 // Find the used trigrams.
423 vector<uint32_t> all_trigrams;
424 for (unsigned trgm = 0; trgm < NUM_TRIGRAMS; ++trgm) {
425 if (corpus->seen_trigram(trgm)) {
426 all_trigrams.push_back(trgm);
430 // Create the hash table.
431 unique_ptr<Trigram[]> hashtable;
432 uint32_t ht_size = next_prime(all_trigrams.size());
434 hashtable = create_hashtable(*corpus, all_trigrams, ht_size, num_overflow_slots);
435 if (hashtable == nullptr) {
436 dprintf("Failed creating hash table of size %u, increasing by 5%% and trying again.\n", ht_size);
437 ht_size = next_prime(ht_size * 1.05);
439 dprintf("Created hash table of size %u.\n\n", ht_size);
444 // Find the offsets for each posting list.
445 size_t bytes_for_hashtable = (ht_size + num_overflow_slots + 1) * sizeof(Trigram);
446 uint64_t offset = ftell(outfp) + bytes_for_hashtable;
447 for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
448 hashtable[i].offset = offset; // Needs to be there even for empty slots.
449 if (hashtable[i].num_docids == 0) {
453 const string &encoded = corpus->get_pl_builder(hashtable[i].trgm).encoded;
454 offset += encoded.size();
457 // Write the hash table.
458 hdr.hash_table_offset_bytes = ftell(outfp);
459 hdr.hashtable_size = ht_size;
460 fwrite(hashtable.get(), ht_size + num_overflow_slots + 1, sizeof(Trigram), outfp);
462 // Write the actual posting lists.
463 for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
464 if (hashtable[i].num_docids == 0) {
467 const string &encoded = corpus->get_pl_builder(hashtable[i].trgm).encoded;
468 fwrite(encoded.data(), encoded.size(), 1, outfp);
471 // Rewind, and write the updated header.
473 fseek(outfp, 0, SEEK_SET);
474 fwrite(&hdr, sizeof(hdr), 1, outfp);
476 // Give the file a proper name, making it visible in the file system.
477 // TODO: It would be nice to be able to do this atomically, like with rename.
478 unlink(outfile.c_str());
480 snprintf(procpath, sizeof(procpath), "/proc/self/fd/%d", fileno(outfp));
481 if (linkat(AT_FDCWD, procpath, AT_FDCWD, outfile.c_str(), AT_SYMLINK_FOLLOW) == -1) {
488 size_t total_bytes = (bytes_for_hashtable + bytes_for_posting_lists + bytes_for_filename_index + bytes_for_filenames);
490 dprintf("Block size: %7d files\n", block_size);
491 dprintf("Dictionary: %'7.1f MB\n", hdr.zstd_dictionary_length_bytes / 1048576.0);
492 dprintf("Hash table: %'7.1f MB\n", bytes_for_hashtable / 1048576.0);
493 dprintf("Posting lists: %'7.1f MB\n", bytes_for_posting_lists / 1048576.0);
494 dprintf("Filename index: %'7.1f MB\n", bytes_for_filename_index / 1048576.0);
495 dprintf("Filenames: %'7.1f MB\n", bytes_for_filenames / 1048576.0);
496 dprintf("Total: %'7.1f MB\n", total_bytes / 1048576.0);