]> git.sesse.net Git - plocate/blob - plocate-build.cpp
Switch trigram lookup from binary search to a hash table.
[plocate] / plocate-build.cpp
1 #include "vp4.h"
2
3 #include <algorithm>
4 #include <arpa/inet.h>
5 #include <assert.h>
6 #include <chrono>
7 #include <endian.h>
8 #include <fcntl.h>
9 #include <math.h>
10 #include <memory>
11 #include <stdio.h>
12 #include <string.h>
13 #include <string>
14 #include <sys/mman.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include <unistd.h>
18 #include <unordered_map>
19 #include <vector>
20 #include <zstd.h>
21
22 #include "db.h"
23
24 #define P4NENC_BOUND(n) ((n + 127) / 128 + (n + 32) * sizeof(uint32_t))
25 #define dprintf(...)
26 //#define dprintf(...) fprintf(stderr, __VA_ARGS__);
27
28 using namespace std;
29 using namespace std::chrono;
30
31 string zstd_compress(const string &src, string *tempbuf);
32
33 static inline uint32_t read_unigram(const string_view s, size_t idx)
34 {
35         if (idx < s.size()) {
36                 return (unsigned char)s[idx];
37         } else {
38                 return 0;
39         }
40 }
41
42 static inline uint32_t read_trigram(const string_view s, size_t start)
43 {
44         return read_unigram(s, start) |
45                 (read_unigram(s, start + 1) << 8) |
46                 (read_unigram(s, start + 2) << 16);
47 }
48
49 enum {
50         DBE_NORMAL = 0, /* A non-directory file */
51         DBE_DIRECTORY = 1, /* A directory */
52         DBE_END = 2 /* End of directory contents; contains no name */
53 };
54
55 // From mlocate.
56 struct db_header {
57         uint8_t magic[8];
58         uint32_t conf_size;
59         uint8_t version;
60         uint8_t check_visibility;
61         uint8_t pad[2];
62 };
63
64 // From mlocate.
65 struct db_directory {
66         uint64_t time_sec;
67         uint32_t time_nsec;
68         uint8_t pad[4];
69 };
70
71 class PostingListBuilder {
72 public:
73         void add_docid(uint32_t docid);
74         void finish();
75
76         string encoded;
77         size_t num_docids = 0;
78
79 private:
80         void write_header(uint32_t docid);
81         void append_block();
82
83         vector<uint32_t> pending_docids;
84
85         uint32_t last_block_end;
86 };
87
88 void PostingListBuilder::add_docid(uint32_t docid)
89 {
90         // Deduplicate against the last inserted value, if any.
91         if (pending_docids.empty()) {
92                 if (encoded.empty()) {
93                         // Very first docid.
94                         write_header(docid);
95                         ++num_docids;
96                         last_block_end = docid;
97                         return;
98                 } else if (docid == last_block_end) {
99                         return;
100                 }
101         } else {
102                 if (docid == pending_docids.back()) {
103                         return;
104                 }
105         }
106
107         pending_docids.push_back(docid);
108         if (pending_docids.size() == 128) {
109                 append_block();
110                 pending_docids.clear();
111                 last_block_end = docid;
112         }
113         ++num_docids;
114 }
115
116 void PostingListBuilder::finish()
117 {
118         if (pending_docids.empty()) {
119                 return;
120         }
121
122         assert(!encoded.empty());  // write_header() should already have run.
123
124         // No interleaving for partial blocks.
125         unsigned char buf[P4NENC_BOUND(128)];
126         unsigned char *end = p4d1enc32(pending_docids.data(), pending_docids.size(), buf, last_block_end);
127         encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
128 }
129
130 void PostingListBuilder::append_block()
131 {
132         unsigned char buf[P4NENC_BOUND(128)];
133         assert(pending_docids.size() == 128);
134         unsigned char *end = p4d1enc128v32(pending_docids.data(), 128, buf, last_block_end);
135         encoded.append(reinterpret_cast<char *>(buf), reinterpret_cast<char *>(end));
136 }
137
138 void PostingListBuilder::write_header(uint32_t docid)
139 {
140         unsigned char buf[P4NENC_BOUND(1)];
141         size_t bytes = p4nd1enc128v32(&docid, 1, buf);
142         encoded.append(reinterpret_cast<char *>(buf), bytes);
143 }
144
145 class Corpus {
146 public:
147         Corpus(size_t block_size)
148                 : block_size(block_size) {}
149         void add_file(string filename);
150         void flush_block();
151
152         vector<string> filename_blocks;
153         unordered_map<uint32_t, PostingListBuilder> invindex;
154         size_t num_files = 0, num_files_in_block = 0, num_blocks = 0;
155
156 private:
157         string current_block;
158         string tempbuf;
159         const size_t block_size;
160 };
161
162 void Corpus::add_file(string filename)
163 {
164         ++num_files;
165         if (!current_block.empty()) {
166                 current_block.push_back('\0');
167         }
168         current_block += filename;
169         if (++num_files_in_block == block_size) {
170                 flush_block();
171         }
172 }
173
174 void Corpus::flush_block()
175 {
176         if (current_block.empty()) {
177                 return;
178         }
179
180         uint32_t docid = num_blocks;
181
182         // Create trigrams.
183         const char *ptr = current_block.c_str();
184         while (ptr < current_block.c_str() + current_block.size()) {
185                 string_view s(ptr);
186                 if (s.size() >= 3) {
187                         for (size_t j = 0; j < s.size() - 2; ++j) {
188                                 uint32_t trgm = read_trigram(s, j);
189                                 invindex[trgm].add_docid(docid);
190                         }
191                 }
192                 ptr += s.size() + 1;
193         }
194
195         // Compress and add the filename block.
196         filename_blocks.push_back(zstd_compress(current_block, &tempbuf));
197
198         current_block.clear();
199         num_files_in_block = 0;
200         ++num_blocks;
201 }
202
203 const char *handle_directory(const char *ptr, Corpus *corpus)
204 {
205         ptr += sizeof(db_directory);
206
207         string dir_path = ptr;
208         ptr += dir_path.size() + 1;
209         if (dir_path == "/") {
210                 dir_path = "";
211         }
212
213         for (;;) {
214                 uint8_t type = *ptr++;
215                 if (type == DBE_NORMAL) {
216                         string filename = ptr;
217                         corpus->add_file(dir_path + "/" + filename);
218                         ptr += filename.size() + 1;
219                 } else if (type == DBE_DIRECTORY) {
220                         string dirname = ptr;
221                         corpus->add_file(dir_path + "/" + dirname);
222                         ptr += dirname.size() + 1;
223                 } else {
224                         return ptr;
225                 }
226         }
227 }
228
229 void read_mlocate(const char *filename, Corpus *corpus)
230 {
231         int fd = open(filename, O_RDONLY);
232         if (fd == -1) {
233                 perror(filename);
234                 exit(1);
235         }
236         off_t len = lseek(fd, 0, SEEK_END);
237         if (len == -1) {
238                 perror("lseek");
239                 exit(1);
240         }
241         const char *data = (char *)mmap(nullptr, len, PROT_READ, MAP_SHARED, fd, /*offset=*/0);
242         if (data == MAP_FAILED) {
243                 perror("mmap");
244                 exit(1);
245         }
246
247         const db_header *hdr = (const db_header *)data;
248
249         // TODO: Care about the base path.
250         string path = data + sizeof(db_header);
251         uint64_t offset = sizeof(db_header) + path.size() + 1 + ntohl(hdr->conf_size);
252
253         const char *ptr = data + offset;
254         while (ptr < data + len) {
255                 ptr = handle_directory(ptr, corpus);
256         }
257
258         munmap((void *)data, len);
259         close(fd);
260 }
261
262 string zstd_compress(const string &src, string *tempbuf)
263 {
264         size_t max_size = ZSTD_compressBound(src.size());
265         if (tempbuf->size() < max_size) {
266                 tempbuf->resize(max_size);
267         }
268         size_t size = ZSTD_compress(&(*tempbuf)[0], max_size, src.data(), src.size(), /*level=*/6);
269         return string(tempbuf->data(), size);
270 }
271
272 bool is_prime(uint32_t x)
273 {
274         if ((x % 2) == 0 || (x % 3) == 0) {
275                 return false;
276         }
277         uint32_t limit = ceil(sqrt(x));
278         for (uint32_t factor = 5; factor <= limit; ++factor) {
279                 if ((x % factor) == 0) {
280                         return false;
281                 }
282         }
283         return true;
284 }
285
286 uint32_t next_prime(uint32_t x)
287 {
288         if ((x % 2) == 0) {
289                 ++x;
290         }
291         while (!is_prime(x)) {
292                 x += 2;
293         }
294         return x;
295 }
296
297 unique_ptr<Trigram[]> create_hashtable(const Corpus &corpus, const vector<uint32_t> &all_trigrams, uint32_t ht_size, uint32_t num_overflow_slots)
298 {
299         unique_ptr<Trigram[]> ht(new Trigram[ht_size + num_overflow_slots + 1]);  // 1 for the sentinel element at the end.
300         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
301                 ht[i].trgm = uint32_t(-1);
302                 ht[i].num_docids = 0;
303                 ht[i].offset = 0;
304         }
305         for (uint32_t trgm : all_trigrams) {
306                 // We don't know offset yet, so set it to zero.
307                 Trigram to_insert{trgm, uint32_t(corpus.invindex.find(trgm)->second.num_docids), 0};
308
309                 uint32_t bucket = hash_trigram(trgm, ht_size);
310                 unsigned distance = 0;
311                 while (ht[bucket].num_docids != 0) {
312                         // Robin Hood hashing; reduces the longest distance by a lot.
313                         unsigned other_distance = bucket - hash_trigram(ht[bucket].trgm, ht_size);
314                         if (distance > other_distance) {
315                                 swap(to_insert, ht[bucket]);
316                                 distance = other_distance;
317                         }
318
319                         ++bucket, ++distance;
320                         if (distance > num_overflow_slots) {
321                                 return nullptr;
322                         }
323                 }
324                 ht[bucket] = to_insert;
325         }
326         return ht;
327 }
328
329 void do_build(const char *infile, const char *outfile, int block_size)
330 {
331         steady_clock::time_point start __attribute__((unused)) = steady_clock::now();
332
333         Corpus corpus(block_size);
334
335         read_mlocate(infile, &corpus);
336         if (false) {  // To read a plain text file.
337                 FILE *fp = fopen(infile, "r");
338                 while (!feof(fp)) {
339                         char buf[1024];
340                         if (fgets(buf, 1024, fp) == nullptr || feof(fp)) {
341                                 break;
342                         }
343                         string s(buf);
344                         if (s.back() == '\n')
345                                 s.pop_back();
346                         corpus.add_file(move(s));
347                 }
348                 fclose(fp);
349         }
350         corpus.flush_block();
351         dprintf("Read %zu files from %s\n", corpus.num_files, infile);
352
353         size_t trigrams = 0, longest_posting_list = 0;
354         size_t bytes_used = 0;
355         for (auto &[trigram, pl_builder] : corpus.invindex) {
356                 pl_builder.finish();
357                 longest_posting_list = max(longest_posting_list, pl_builder.num_docids);
358                 trigrams += pl_builder.num_docids;
359                 bytes_used += pl_builder.encoded.size();
360         }
361         dprintf("%zu files, %zu different trigrams, %zu entries, avg len %.2f, longest %zu\n",
362                 corpus.num_files, corpus.invindex.size(), trigrams, double(trigrams) / corpus.invindex.size(), longest_posting_list);
363         dprintf("%zu bytes used for posting lists (%.2f bits/entry)\n", bytes_used, 8 * bytes_used / double(trigrams));
364
365         dprintf("Building posting lists took %.1f ms.\n\n", 1e3 * duration<float>(steady_clock::now() - start).count());
366
367         // Sort the trigrams, mostly to get a consistent result every time
368         // (the hash table will put things in random order anyway).
369         vector<uint32_t> all_trigrams;
370         for (auto &[trigram, pl_builder] : corpus.invindex) {
371                 all_trigrams.push_back(trigram);
372         }
373         sort(all_trigrams.begin(), all_trigrams.end());
374
375         unique_ptr<Trigram[]> hashtable;
376         uint32_t ht_size = next_prime(all_trigrams.size());
377         constexpr unsigned num_overflow_slots = 16;
378         for ( ;; ) {
379                 hashtable = create_hashtable(corpus, all_trigrams, ht_size, num_overflow_slots);
380                 if (hashtable == nullptr) {
381                         dprintf("Failed creating hash table of size %u, increasing by 5%% and trying again.\n", ht_size);
382                         ht_size = next_prime(ht_size * 1.05);
383                 } else {
384                         dprintf("Created hash table of size %u.\n\n", ht_size);
385                         break;
386                 }
387         }
388
389         umask(0027);
390         FILE *outfp = fopen(outfile, "wb");
391
392         // Find the offsets for each posting list.
393         size_t bytes_for_hashtable = (ht_size + num_overflow_slots + 1) * sizeof(Trigram);
394         uint64_t offset = sizeof(Header) + bytes_for_hashtable;
395         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
396                 hashtable[i].offset = offset;  // Needs to be there even for empty slots.
397                 if (hashtable[i].num_docids == 0) {
398                         continue;
399                 }
400
401                 const PostingListBuilder &pl_builder = corpus.invindex[hashtable[i].trgm];
402                 offset += pl_builder.encoded.size();
403         }
404
405         // Write the header.
406         Header hdr;
407         memcpy(hdr.magic, "\0plocate", 8);
408         hdr.version = 0;
409         hdr.hashtable_size = ht_size;
410         hdr.extra_ht_slots = num_overflow_slots;
411         hdr.hash_table_offset_bytes = sizeof(hdr);  // This member is just there for flexibility.
412         hdr.filename_index_offset_bytes = offset;
413         fwrite(&hdr, sizeof(hdr), 1, outfp);
414
415         // Write the hash table.
416         fwrite(hashtable.get(), ht_size + num_overflow_slots + 1, sizeof(Trigram), outfp);
417
418         // Write the actual posting lists.
419         size_t bytes_for_posting_lists = 0;
420         for (unsigned i = 0; i < ht_size + num_overflow_slots + 1; ++i) {
421                 if (hashtable[i].num_docids == 0) {
422                         continue;
423                 }
424                 const string &encoded = corpus.invindex[hashtable[i].trgm].encoded;
425                 fwrite(encoded.data(), encoded.size(), 1, outfp);
426                 bytes_for_posting_lists += encoded.size();
427         }
428
429         // Stick an empty block at the end as sentinel.
430         corpus.filename_blocks.push_back("");
431
432         // Write the offsets to the filenames.
433         size_t bytes_for_filename_index = 0, bytes_for_filenames = 0;
434         offset = hdr.filename_index_offset_bytes + corpus.filename_blocks.size() * sizeof(offset);
435         for (const string &filename : corpus.filename_blocks) {
436                 fwrite(&offset, sizeof(offset), 1, outfp);
437                 offset += filename.size();
438                 bytes_for_filename_index += sizeof(offset);
439                 bytes_for_filenames += filename.size();
440         }
441
442         // Write the actual filenames.
443         for (const string &filename : corpus.filename_blocks) {
444                 fwrite(filename.data(), filename.size(), 1, outfp);
445         }
446
447         fclose(outfp);
448
449         size_t total_bytes __attribute__((unused)) = (bytes_for_hashtable + bytes_for_posting_lists + bytes_for_filename_index + bytes_for_filenames);
450
451         dprintf("Block size:     %7d files\n", block_size);
452         dprintf("Hash table:     %'7.1f MB\n", bytes_for_hashtable / 1048576.0);
453         dprintf("Posting lists:  %'7.1f MB\n", bytes_for_posting_lists / 1048576.0);
454         dprintf("Filename index: %'7.1f MB\n", bytes_for_filename_index / 1048576.0);
455         dprintf("Filenames:      %'7.1f MB\n", bytes_for_filenames / 1048576.0);
456         dprintf("Total:          %'7.1f MB\n", total_bytes / 1048576.0);
457         dprintf("\n");
458 }
459
460 int main(int argc, char **argv)
461 {
462         do_build(argv[1], argv[2], 32);
463         exit(EXIT_SUCCESS);
464 }