1 /* hyperloglog.c - Redis HyperLogLog probabilistic cardinality approximation.
2 * This file implements the algorithm and the exported Redis commands.
3 *
4 * Copyright (c) 2014, Salvatore Sanfilippo <antirez at gmail dot com>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are met:
9 *
10 * * Redistributions of source code must retain the above copyright notice,
11 * this list of conditions and the following disclaimer.
12 * * Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * * Neither the name of Redis nor the names of its contributors may be used
16 * to endorse or promote products derived from this software without
17 * specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
23 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 #include "server.h"
33
34 #include <stdint.h>
35 #include <math.h>
36
37 /* The Redis HyperLogLog implementation is based on the following ideas:
38 *
39 * * The use of a 64 bit hash function as proposed in [1], in order to don't
40 * limited to cardinalities up to 10^9, at the cost of just 1 additional
41 * bit per register.
42 * * The use of 16384 6-bit registers for a great level of accuracy, using
43 * a total of 12k per key.
44 * * The use of the Redis string data type. No new type is introduced.
45 * * No attempt is made to compress the data structure as in [1]. Also the
46 * algorithm used is the original HyperLogLog Algorithm as in [2], with
47 * the only difference that a 64 bit hash function is used, so no correction
48 * is performed for values near 2^32 as in [1].
49 *
50 * [1] Heule, Nunkesser, Hall: HyperLogLog in Practice: Algorithmic
51 * Engineering of a State of The Art Cardinality Estimation Algorithm.
52 *
53 * [2] P. Flajolet, Éric Fusy, O. Gandouet, and F. Meunier. Hyperloglog: The
54 * analysis of a near-optimal cardinality estimation algorithm.
55 *
56 * Redis uses two representations:
57 *
58 * 1) A "dense" representation where every entry is represented by
59 * a 6-bit integer.
60 * 2) A "sparse" representation using run length compression suitable
61 * for representing HyperLogLogs with many registers set to 0 in
62 * a memory efficient way.
63 *
64 *
65 * HLL header
66 * ===
67 *
68 * Both the dense and sparse representation have a 16 byte header as follows:
69 *
70 * +------+---+-----+----------+
71 * | HYLL | E | N/U | Cardin. |
72 * +------+---+-----+----------+
73 *
74 * The first 4 bytes are a magic string set to the bytes "HYLL".
75 * "E" is one byte encoding, currently set to HLL_DENSE or
76 * HLL_SPARSE. N/U are three not used bytes.
77 *
78 * The "Cardin." field is a 64 bit integer stored in little endian format
79 * with the latest cardinality computed that can be reused if the data
80 * structure was not modified since the last computation (this is useful
81 * because there are high probabilities that HLLADD operations don't
82 * modify the actual data structure and hence the approximated cardinality).
83 *
84 * When the most significant bit in the most significant byte of the cached
85 * cardinality is set, it means that the data structure was modified and
86 * we can't reuse the cached value that must be recomputed.
87 *
88 * Dense representation
89 * ===
90 *
91 * The dense representation used by Redis is the following:
92 *
93 * +--------+--------+--------+------// //--+
94 * |11000000|22221111|33333322|55444444 .... |
95 * +--------+--------+--------+------// //--+
96 *
97 * The 6 bits counters are encoded one after the other starting from the
98 * LSB to the MSB, and using the next bytes as needed.
99 *
100 * Sparse representation
101 * ===
102 *
103 * The sparse representation encodes registers using a run length
104 * encoding composed of three opcodes, two using one byte, and one using
105 * of two bytes. The opcodes are called ZERO, XZERO and VAL.
106 *
107 * ZERO opcode is represented as 00xxxxxx. The 6-bit integer represented
108 * by the six bits 'xxxxxx', plus 1, means that there are N registers set
109 * to 0. This opcode can represent from 1 to 64 contiguous registers set
110 * to the value of 0.
111 *
112 * XZERO opcode is represented by two bytes 01xxxxxx yyyyyyyy. The 14-bit
113 * integer represented by the bits 'xxxxxx' as most significant bits and
114 * 'yyyyyyyy' as least significant bits, plus 1, means that there are N
115 * registers set to 0. This opcode can represent from 0 to 16384 contiguous
116 * registers set to the value of 0.
117 *
118 * VAL opcode is represented as 1vvvvvxx. It contains a 5-bit integer
119 * representing the value of a register, and a 2-bit integer representing
120 * the number of contiguous registers set to that value 'vvvvv'.
121 * To obtain the value and run length, the integers vvvvv and xx must be
122 * incremented by one. This opcode can represent values from 1 to 32,
123 * repeated from 1 to 4 times.
124 *
125 * The sparse representation can't represent registers with a value greater
126 * than 32, however it is very unlikely that we find such a register in an
127 * HLL with a cardinality where the sparse representation is still more
128 * memory efficient than the dense representation. When this happens the
129 * HLL is converted to the dense representation.
130 *
131 * The sparse representation is purely positional. For example a sparse
132 * representation of an empty HLL is just: XZERO:16384.
133 *
134 * An HLL having only 3 non-zero registers at position 1000, 1020, 1021
135 * respectively set to 2, 3, 3, is represented by the following three
136 * opcodes:
137 *
138 * XZERO:1000 (Registers 0-999 are set to 0)
139 * VAL:2,1 (1 register set to value 2, that is register 1000)
140 * ZERO:19 (Registers 1001-1019 set to 0)
141 * VAL:3,2 (2 registers set to value 3, that is registers 1020,1021)
142 * XZERO:15362 (Registers 1022-16383 set to 0)
143 *
144 * In the example the sparse representation used just 7 bytes instead
145 * of 12k in order to represent the HLL registers. In general for low
146 * cardinality there is a big win in terms of space efficiency, traded
147 * with CPU time since the sparse representation is slower to access:
148 *
149 * The following table shows average cardinality vs bytes used, 100
150 * samples per cardinality (when the set was not representable because
151 * of registers with too big value, the dense representation size was used
152 * as a sample).
153 *
154 * 100 267
155 * 200 485
156 * 300 678
157 * 400 859
158 * 500 1033
159 * 600 1205
160 * 700 1375
161 * 800 1544
162 * 900 1713
163 * 1000 1882
164 * 2000 3480
165 * 3000 4879
166 * 4000 6089
167 * 5000 7138
168 * 6000 8042
169 * 7000 8823
170 * 8000 9500
171 * 9000 10088
172 * 10000 10591
173 *
174 * The dense representation uses 12288 bytes, so there is a big win up to
175 * a cardinality of ~2000-3000. For bigger cardinalities the constant times
176 * involved in updating the sparse representation is not justified by the
177 * memory savings. The exact maximum length of the sparse representation
178 * when this implementation switches to the dense representation is
179 * configured via the define server.hll_sparse_max_bytes.
180 */
181
182 struct hllhdr {
183 char magic[4]; /* "HYLL" */
184 uint8_t encoding; /* HLL_DENSE or HLL_SPARSE. */
185 uint8_t notused[3]; /* Reserved for future use, must be zero. */
186 uint8_t card[8]; /* Cached cardinality, little endian. */
187 uint8_t registers[]; /* Data bytes. */
188 };
189
190 /* The cached cardinality MSB is used to signal validity of the cached value. */
191 #define HLL_INVALIDATE_CACHE(hdr) (hdr)->card[7] |= (1<<7)
192 #define HLL_VALID_CACHE(hdr) (((hdr)->card[7] & (1<<7)) == 0)
193
194 #define HLL_P 14 /* The greater is P, the smaller the error. */
195 #define HLL_REGISTERS (1<<HLL_P) /* With P=14, 16384 registers. */
196 #define HLL_P_MASK (HLL_REGISTERS-1) /* Mask to index register. */
197 #define HLL_BITS 6 /* Enough to count up to 63 leading zeroes. */
198 #define HLL_REGISTER_MAX ((1<<HLL_BITS)-1)
199 #define HLL_HDR_SIZE sizeof(struct hllhdr)
200 #define HLL_DENSE_SIZE (HLL_HDR_SIZE+((HLL_REGISTERS*HLL_BITS+7)/8))
201 #define HLL_DENSE 0 /* Dense encoding. */
202 #define HLL_SPARSE 1 /* Sparse encoding. */
203 #define HLL_RAW 255 /* Only used internally, never exposed. */
204 #define HLL_MAX_ENCODING 1
205
206 static char *invalid_hll_err = "-INVALIDOBJ Corrupted HLL object detected\r\n";
207
208 /* =========================== Low level bit macros ========================= */
209
210 /* Macros to access the dense representation.
211 *
212 * We need to get and set 6 bit counters in an array of 8 bit bytes.
213 * We use macros to make sure the code is inlined since speed is critical
214 * especially in order to compute the approximated cardinality in
215 * HLLCOUNT where we need to access all the registers at once.
216 * For the same reason we also want to avoid conditionals in this code path.
217 *
218 * +--------+--------+--------+------//
219 * |11000000|22221111|33333322|55444444
220 * +--------+--------+--------+------//
221 *
222 * Note: in the above representation the most significant bit (MSB)
223 * of every byte is on the left. We start using bits from the LSB to MSB,
224 * and so forth passing to the next byte.
225 *
226 * Example, we want to access to counter at pos = 1 ("111111" in the
227 * illustration above).
228 *
229 * The index of the first byte b0 containing our data is:
230 *
231 * b0 = 6 * pos / 8 = 0
232 *
233 * +--------+
234 * |11000000| <- Our byte at b0
235 * +--------+
236 *
237 * The position of the first bit (counting from the LSB = 0) in the byte
238 * is given by:
239 *
240 * fb = 6 * pos % 8 -> 6
241 *
242 * Right shift b0 of 'fb' bits.
243 *
244 * +--------+
245 * |11000000| <- Initial value of b0
246 * |00000011| <- After right shift of 6 pos.
247 * +--------+
248 *
249 * Left shift b1 of bits 8-fb bits (2 bits)
250 *
251 * +--------+
252 * |22221111| <- Initial value of b1
253 * |22111100| <- After left shift of 2 bits.
254 * +--------+
255 *
256 * OR the two bits, and finally AND with 111111 (63 in decimal) to
257 * clean the higher order bits we are not interested in:
258 *
259 * +--------+
260 * |00000011| <- b0 right shifted
261 * |22111100| <- b1 left shifted
262 * |22111111| <- b0 OR b1
263 * | 111111| <- (b0 OR b1) AND 63, our value.
264 * +--------+
265 *
266 * We can try with a different example, like pos = 0. In this case
267 * the 6-bit counter is actually contained in a single byte.
268 *
269 * b0 = 6 * pos / 8 = 0
270 *
271 * +--------+
272 * |11000000| <- Our byte at b0
273 * +--------+
274 *
275 * fb = 6 * pos % 8 = 0
276 *
277 * So we right shift of 0 bits (no shift in practice) and
278 * left shift the next byte of 8 bits, even if we don't use it,
279 * but this has the effect of clearing the bits so the result
280 * will not be affacted after the OR.
281 *
282 * -------------------------------------------------------------------------
283 *
284 * Setting the register is a bit more complex, let's assume that 'val'
285 * is the value we want to set, already in the right range.
286 *
287 * We need two steps, in one we need to clear the bits, and in the other
288 * we need to bitwise-OR the new bits.
289 *
290 * Let's try with 'pos' = 1, so our first byte at 'b' is 0,
291 *
292 * "fb" is 6 in this case.
293 *
294 * +--------+
295 * |11000000| <- Our byte at b0
296 * +--------+
297 *
298 * To create a AND-mask to clear the bits about this position, we just
299 * initialize the mask with the value 63, left shift it of "fs" bits,
300 * and finally invert the result.
301 *
302 * +--------+
303 * |00111111| <- "mask" starts at 63
304 * |11000000| <- "mask" after left shift of "ls" bits.
305 * |00111111| <- "mask" after invert.
306 * +--------+
307 *
308 * Now we can bitwise-AND the byte at "b" with the mask, and bitwise-OR
309 * it with "val" left-shifted of "ls" bits to set the new bits.
310 *
311 * Now let's focus on the next byte b1:
312 *
313 * +--------+
314 * |22221111| <- Initial value of b1
315 * +--------+
316 *
317 * To build the AND mask we start again with the 63 value, right shift
318 * it by 8-fb bits, and invert it.
319 *
320 * +--------+
321 * |00111111| <- "mask" set at 2&6-1
322 * |00001111| <- "mask" after the right shift by 8-fb = 2 bits
323 * |11110000| <- "mask" after bitwise not.
324 * +--------+
325 *
326 * Now we can mask it with b+1 to clear the old bits, and bitwise-OR
327 * with "val" left-shifted by "rs" bits to set the new value.
328 */
329
330 /* Note: if we access the last counter, we will also access the b+1 byte
331 * that is out of the array, but sds strings always have an implicit null
332 * term, so the byte exists, and we can skip the conditional (or the need
333 * to allocate 1 byte more explicitly). */
334
335 /* Store the value of the register at position 'regnum' into variable 'target'.
336 * 'p' is an array of unsigned bytes. */
337 #define HLL_DENSE_GET_REGISTER(target,p,regnum) do { \
338 uint8_t *_p = (uint8_t*) p; \
339 unsigned long _byte = regnum*HLL_BITS/8; \
340 unsigned long _fb = regnum*HLL_BITS&7; \
341 unsigned long _fb8 = 8 - _fb; \
342 unsigned long b0 = _p[_byte]; \
343 unsigned long b1 = _p[_byte+1]; \
344 target = ((b0 >> _fb) | (b1 << _fb8)) & HLL_REGISTER_MAX; \
345 } while(0)
346
347 /* Set the value of the register at position 'regnum' to 'val'.
348 * 'p' is an array of unsigned bytes. */
349 #define HLL_DENSE_SET_REGISTER(p,regnum,val) do { \
350 uint8_t *_p = (uint8_t*) p; \
351 unsigned long _byte = regnum*HLL_BITS/8; \
352 unsigned long _fb = regnum*HLL_BITS&7; \
353 unsigned long _fb8 = 8 - _fb; \
354 unsigned long _v = val; \
355 _p[_byte] &= ~(HLL_REGISTER_MAX << _fb); \
356 _p[_byte] |= _v << _fb; \
357 _p[_byte+1] &= ~(HLL_REGISTER_MAX >> _fb8); \
358 _p[_byte+1] |= _v >> _fb8; \
359 } while(0)
360
361 /* Macros to access the sparse representation.
362 * The macros parameter is expected to be an uint8_t pointer. */
363 #define HLL_SPARSE_XZERO_BIT 0x40 /* 01xxxxxx */
364 #define HLL_SPARSE_VAL_BIT 0x80 /* 1vvvvvxx */
365 #define HLL_SPARSE_IS_ZERO(p) (((*(p)) & 0xc0) == 0) /* 00xxxxxx */
366 #define HLL_SPARSE_IS_XZERO(p) (((*(p)) & 0xc0) == HLL_SPARSE_XZERO_BIT)
367 #define HLL_SPARSE_IS_VAL(p) ((*(p)) & HLL_SPARSE_VAL_BIT)
368 #define HLL_SPARSE_ZERO_LEN(p) (((*(p)) & 0x3f)+1)
369 #define HLL_SPARSE_XZERO_LEN(p) (((((*(p)) & 0x3f) << 8) | (*((p)+1)))+1)
370 #define HLL_SPARSE_VAL_VALUE(p) ((((*(p)) >> 2) & 0x1f)+1)
371 #define HLL_SPARSE_VAL_LEN(p) (((*(p)) & 0x3)+1)
372 #define HLL_SPARSE_VAL_MAX_VALUE 32
373 #define HLL_SPARSE_VAL_MAX_LEN 4
374 #define HLL_SPARSE_ZERO_MAX_LEN 64
375 #define HLL_SPARSE_XZERO_MAX_LEN 16384
376 #define HLL_SPARSE_VAL_SET(p,val,len) do { \
377 *(p) = (((val)-1)<<2|((len)-1))|HLL_SPARSE_VAL_BIT; \
378 } while(0)
379 #define HLL_SPARSE_ZERO_SET(p,len) do { \
380 *(p) = (len)-1; \
381 } while(0)
382 #define HLL_SPARSE_XZERO_SET(p,len) do { \
383 int _l = (len)-1; \
384 *(p) = (_l>>8) | HLL_SPARSE_XZERO_BIT; \
385 *((p)+1) = (_l&0xff); \
386 } while(0)
387
388 /* ========================= HyperLogLog algorithm ========================= */
389
390 /* Our hash function is MurmurHash2, 64 bit version.
391 * It was modified for Redis in order to provide the same result in
392 * big and little endian archs (endian neutral). */
MurmurHash64A(const void * key,int len,unsigned int seed)393 uint64_t MurmurHash64A (const void * key, int len, unsigned int seed) {
394 const uint64_t m = 0xc6a4a7935bd1e995;
395 const int r = 47;
396 uint64_t h = seed ^ (len * m);
397 const uint8_t *data = (const uint8_t *)key;
398 const uint8_t *end = data + (len-(len&7));
399
400 while(data != end) {
401 uint64_t k;
402
403 #if (BYTE_ORDER == LITTLE_ENDIAN)
404 k = *((uint64_t*)data);
405 #else
406 k = (uint64_t) data[0];
407 k |= (uint64_t) data[1] << 8;
408 k |= (uint64_t) data[2] << 16;
409 k |= (uint64_t) data[3] << 24;
410 k |= (uint64_t) data[4] << 32;
411 k |= (uint64_t) data[5] << 40;
412 k |= (uint64_t) data[6] << 48;
413 k |= (uint64_t) data[7] << 56;
414 #endif
415
416 k *= m;
417 k ^= k >> r;
418 k *= m;
419 h ^= k;
420 h *= m;
421 data += 8;
422 }
423
424 switch(len & 7) {
425 case 7: h ^= (uint64_t)data[6] << 48;
426 case 6: h ^= (uint64_t)data[5] << 40;
427 case 5: h ^= (uint64_t)data[4] << 32;
428 case 4: h ^= (uint64_t)data[3] << 24;
429 case 3: h ^= (uint64_t)data[2] << 16;
430 case 2: h ^= (uint64_t)data[1] << 8;
431 case 1: h ^= (uint64_t)data[0];
432 h *= m;
433 };
434
435 h ^= h >> r;
436 h *= m;
437 h ^= h >> r;
438 return h;
439 }
440
441 /* Given a string element to add to the HyperLogLog, returns the length
442 * of the pattern 000..1 of the element hash. As a side effect 'regp' is
443 * set to the register index this element hashes to. */
hllPatLen(unsigned char * ele,size_t elesize,long * regp)444 int hllPatLen(unsigned char *ele, size_t elesize, long *regp) {
445 uint64_t hash, bit, index;
446 int count;
447
448 /* Count the number of zeroes starting from bit HLL_REGISTERS
449 * (that is a power of two corresponding to the first bit we don't use
450 * as index). The max run can be 64-P+1 bits.
451 *
452 * Note that the final "1" ending the sequence of zeroes must be
453 * included in the count, so if we find "001" the count is 3, and
454 * the smallest count possible is no zeroes at all, just a 1 bit
455 * at the first position, that is a count of 1.
456 *
457 * This may sound like inefficient, but actually in the average case
458 * there are high probabilities to find a 1 after a few iterations. */
459 hash = MurmurHash64A(ele,elesize,0xadc83b19ULL);
460 index = hash & HLL_P_MASK; /* Register index. */
461 hash |= ((uint64_t)1<<63); /* Make sure the loop terminates. */
462 bit = HLL_REGISTERS; /* First bit not used to address the register. */
463 count = 1; /* Initialized to 1 since we count the "00000...1" pattern. */
464 while((hash & bit) == 0) {
465 count++;
466 bit <<= 1;
467 }
468 *regp = (int) index;
469 return count;
470 }
471
472 /* ================== Dense representation implementation ================== */
473
474 /* "Add" the element in the dense hyperloglog data structure.
475 * Actually nothing is added, but the max 0 pattern counter of the subset
476 * the element belongs to is incremented if needed.
477 *
478 * 'registers' is expected to have room for HLL_REGISTERS plus an
479 * additional byte on the right. This requirement is met by sds strings
480 * automatically since they are implicitly null terminated.
481 *
482 * The function always succeed, however if as a result of the operation
483 * the approximated cardinality changed, 1 is returned. Otherwise 0
484 * is returned. */
hllDenseAdd(uint8_t * registers,unsigned char * ele,size_t elesize)485 int hllDenseAdd(uint8_t *registers, unsigned char *ele, size_t elesize) {
486 uint8_t oldcount, count;
487 long index;
488
489 /* Update the register if this element produced a longer run of zeroes. */
490 count = hllPatLen(ele,elesize,&index);
491 HLL_DENSE_GET_REGISTER(oldcount,registers,index);
492 if (count > oldcount) {
493 HLL_DENSE_SET_REGISTER(registers,index,count);
494 return 1;
495 } else {
496 return 0;
497 }
498 }
499
500 /* Compute SUM(2^-reg) in the dense representation.
501 * PE is an array with a pre-computer table of values 2^-reg indexed by reg.
502 * As a side effect the integer pointed by 'ezp' is set to the number
503 * of zero registers. */
hllDenseSum(uint8_t * registers,double * PE,int * ezp)504 double hllDenseSum(uint8_t *registers, double *PE, int *ezp) {
505 double E = 0;
506 int j, ez = 0;
507
508 /* Redis default is to use 16384 registers 6 bits each. The code works
509 * with other values by modifying the defines, but for our target value
510 * we take a faster path with unrolled loops. */
511 if (HLL_REGISTERS == 16384 && HLL_BITS == 6) {
512 uint8_t *r = registers;
513 unsigned long r0, r1, r2, r3, r4, r5, r6, r7, r8, r9,
514 r10, r11, r12, r13, r14, r15;
515 for (j = 0; j < 1024; j++) {
516 /* Handle 16 registers per iteration. */
517 r0 = r[0] & 63; if (r0 == 0) ez++;
518 r1 = (r[0] >> 6 | r[1] << 2) & 63; if (r1 == 0) ez++;
519 r2 = (r[1] >> 4 | r[2] << 4) & 63; if (r2 == 0) ez++;
520 r3 = (r[2] >> 2) & 63; if (r3 == 0) ez++;
521 r4 = r[3] & 63; if (r4 == 0) ez++;
522 r5 = (r[3] >> 6 | r[4] << 2) & 63; if (r5 == 0) ez++;
523 r6 = (r[4] >> 4 | r[5] << 4) & 63; if (r6 == 0) ez++;
524 r7 = (r[5] >> 2) & 63; if (r7 == 0) ez++;
525 r8 = r[6] & 63; if (r8 == 0) ez++;
526 r9 = (r[6] >> 6 | r[7] << 2) & 63; if (r9 == 0) ez++;
527 r10 = (r[7] >> 4 | r[8] << 4) & 63; if (r10 == 0) ez++;
528 r11 = (r[8] >> 2) & 63; if (r11 == 0) ez++;
529 r12 = r[9] & 63; if (r12 == 0) ez++;
530 r13 = (r[9] >> 6 | r[10] << 2) & 63; if (r13 == 0) ez++;
531 r14 = (r[10] >> 4 | r[11] << 4) & 63; if (r14 == 0) ez++;
532 r15 = (r[11] >> 2) & 63; if (r15 == 0) ez++;
533
534 /* Additional parens will allow the compiler to optimize the
535 * code more with a loss of precision that is not very relevant
536 * here (floating point math is not commutative!). */
537 E += (PE[r0] + PE[r1]) + (PE[r2] + PE[r3]) + (PE[r4] + PE[r5]) +
538 (PE[r6] + PE[r7]) + (PE[r8] + PE[r9]) + (PE[r10] + PE[r11]) +
539 (PE[r12] + PE[r13]) + (PE[r14] + PE[r15]);
540 r += 12;
541 }
542 } else {
543 for (j = 0; j < HLL_REGISTERS; j++) {
544 unsigned long reg;
545
546 HLL_DENSE_GET_REGISTER(reg,registers,j);
547 if (reg == 0) {
548 ez++;
549 /* Increment E at the end of the loop. */
550 } else {
551 E += PE[reg]; /* Precomputed 2^(-reg[j]). */
552 }
553 }
554 E += ez; /* Add 2^0 'ez' times. */
555 }
556 *ezp = ez;
557 return E;
558 }
559
560 /* ================== Sparse representation implementation ================= */
561
562 /* Convert the HLL with sparse representation given as input in its dense
563 * representation. Both representations are represented by SDS strings, and
564 * the input representation is freed as a side effect.
565 *
566 * The function returns C_OK if the sparse representation was valid,
567 * otherwise C_ERR is returned if the representation was corrupted. */
hllSparseToDense(robj * o)568 int hllSparseToDense(robj *o) {
569 sds sparse = o->ptr, dense;
570 struct hllhdr *hdr, *oldhdr = (struct hllhdr*)sparse;
571 int idx = 0, runlen, regval;
572 uint8_t *p = (uint8_t*)sparse, *end = p+sdslen(sparse);
573
574 /* If the representation is already the right one return ASAP. */
575 hdr = (struct hllhdr*) sparse;
576 if (hdr->encoding == HLL_DENSE) return C_OK;
577
578 /* Create a string of the right size filled with zero bytes.
579 * Note that the cached cardinality is set to 0 as a side effect
580 * that is exactly the cardinality of an empty HLL. */
581 dense = sdsnewlen(NULL,HLL_DENSE_SIZE);
582 hdr = (struct hllhdr*) dense;
583 *hdr = *oldhdr; /* This will copy the magic and cached cardinality. */
584 hdr->encoding = HLL_DENSE;
585
586 /* Now read the sparse representation and set non-zero registers
587 * accordingly. */
588 p += HLL_HDR_SIZE;
589 while(p < end) {
590 if (HLL_SPARSE_IS_ZERO(p)) {
591 runlen = HLL_SPARSE_ZERO_LEN(p);
592 idx += runlen;
593 p++;
594 } else if (HLL_SPARSE_IS_XZERO(p)) {
595 runlen = HLL_SPARSE_XZERO_LEN(p);
596 idx += runlen;
597 p += 2;
598 } else {
599 runlen = HLL_SPARSE_VAL_LEN(p);
600 regval = HLL_SPARSE_VAL_VALUE(p);
601 while(runlen--) {
602 HLL_DENSE_SET_REGISTER(hdr->registers,idx,regval);
603 idx++;
604 }
605 p++;
606 }
607 }
608
609 /* If the sparse representation was valid, we expect to find idx
610 * set to HLL_REGISTERS. */
611 if (idx != HLL_REGISTERS) {
612 sdsfree(dense);
613 return C_ERR;
614 }
615
616 /* Free the old representation and set the new one. */
617 sdsfree(o->ptr);
618 o->ptr = dense;
619 return C_OK;
620 }
621
622 /* "Add" the element in the sparse hyperloglog data structure.
623 * Actually nothing is added, but the max 0 pattern counter of the subset
624 * the element belongs to is incremented if needed.
625 *
626 * The object 'o' is the String object holding the HLL. The function requires
627 * a reference to the object in order to be able to enlarge the string if
628 * needed.
629 *
630 * On success, the function returns 1 if the cardinality changed, or 0
631 * if the register for this element was not updated.
632 * On error (if the representation is invalid) -1 is returned.
633 *
634 * As a side effect the function may promote the HLL representation from
635 * sparse to dense: this happens when a register requires to be set to a value
636 * not representable with the sparse representation, or when the resulting
637 * size would be greater than server.hll_sparse_max_bytes. */
hllSparseAdd(robj * o,unsigned char * ele,size_t elesize)638 int hllSparseAdd(robj *o, unsigned char *ele, size_t elesize) {
639 struct hllhdr *hdr;
640 uint8_t oldcount, count, *sparse, *end, *p, *prev, *next;
641 long index, first, span;
642 long is_zero = 0, is_xzero = 0, is_val = 0, runlen = 0;
643
644 /* Update the register if this element produced a longer run of zeroes. */
645 count = hllPatLen(ele,elesize,&index);
646
647 /* If the count is too big to be representable by the sparse representation
648 * switch to dense representation. */
649 if (count > HLL_SPARSE_VAL_MAX_VALUE) goto promote;
650
651 /* When updating a sparse representation, sometimes we may need to
652 * enlarge the buffer for up to 3 bytes in the worst case (XZERO split
653 * into XZERO-VAL-XZERO). Make sure there is enough space right now
654 * so that the pointers we take during the execution of the function
655 * will be valid all the time. */
656 o->ptr = sdsMakeRoomFor(o->ptr,3);
657
658 /* Step 1: we need to locate the opcode we need to modify to check
659 * if a value update is actually needed. */
660 sparse = p = ((uint8_t*)o->ptr) + HLL_HDR_SIZE;
661 end = p + sdslen(o->ptr) - HLL_HDR_SIZE;
662
663 first = 0;
664 prev = NULL; /* Points to previos opcode at the end of the loop. */
665 next = NULL; /* Points to the next opcode at the end of the loop. */
666 span = 0;
667 while(p < end) {
668 long oplen;
669
670 /* Set span to the number of registers covered by this opcode.
671 *
672 * This is the most performance critical loop of the sparse
673 * representation. Sorting the conditionals from the most to the
674 * least frequent opcode in many-bytes sparse HLLs is faster. */
675 oplen = 1;
676 if (HLL_SPARSE_IS_ZERO(p)) {
677 span = HLL_SPARSE_ZERO_LEN(p);
678 } else if (HLL_SPARSE_IS_VAL(p)) {
679 span = HLL_SPARSE_VAL_LEN(p);
680 } else { /* XZERO. */
681 span = HLL_SPARSE_XZERO_LEN(p);
682 oplen = 2;
683 }
684 /* Break if this opcode covers the register as 'index'. */
685 if (index <= first+span-1) break;
686 prev = p;
687 p += oplen;
688 first += span;
689 }
690 if (span == 0) return -1; /* Invalid format. */
691
692 next = HLL_SPARSE_IS_XZERO(p) ? p+2 : p+1;
693 if (next >= end) next = NULL;
694
695 /* Cache current opcode type to avoid using the macro again and
696 * again for something that will not change.
697 * Also cache the run-length of the opcode. */
698 if (HLL_SPARSE_IS_ZERO(p)) {
699 is_zero = 1;
700 runlen = HLL_SPARSE_ZERO_LEN(p);
701 } else if (HLL_SPARSE_IS_XZERO(p)) {
702 is_xzero = 1;
703 runlen = HLL_SPARSE_XZERO_LEN(p);
704 } else {
705 is_val = 1;
706 runlen = HLL_SPARSE_VAL_LEN(p);
707 }
708
709 /* Step 2: After the loop:
710 *
711 * 'first' stores to the index of the first register covered
712 * by the current opcode, which is pointed by 'p'.
713 *
714 * 'next' ad 'prev' store respectively the next and previous opcode,
715 * or NULL if the opcode at 'p' is respectively the last or first.
716 *
717 * 'span' is set to the number of registers covered by the current
718 * opcode.
719 *
720 * There are different cases in order to update the data structure
721 * in place without generating it from scratch:
722 *
723 * A) If it is a VAL opcode already set to a value >= our 'count'
724 * no update is needed, regardless of the VAL run-length field.
725 * In this case PFADD returns 0 since no changes are performed.
726 *
727 * B) If it is a VAL opcode with len = 1 (representing only our
728 * register) and the value is less than 'count', we just update it
729 * since this is a trivial case. */
730 if (is_val) {
731 oldcount = HLL_SPARSE_VAL_VALUE(p);
732 /* Case A. */
733 if (oldcount >= count) return 0;
734
735 /* Case B. */
736 if (runlen == 1) {
737 HLL_SPARSE_VAL_SET(p,count,1);
738 goto updated;
739 }
740 }
741
742 /* C) Another trivial to handle case is a ZERO opcode with a len of 1.
743 * We can just replace it with a VAL opcode with our value and len of 1. */
744 if (is_zero && runlen == 1) {
745 HLL_SPARSE_VAL_SET(p,count,1);
746 goto updated;
747 }
748
749 /* D) General case.
750 *
751 * The other cases are more complex: our register requires to be updated
752 * and is either currently represented by a VAL opcode with len > 1,
753 * by a ZERO opcode with len > 1, or by an XZERO opcode.
754 *
755 * In those cases the original opcode must be split into muliple
756 * opcodes. The worst case is an XZERO split in the middle resuling into
757 * XZERO - VAL - XZERO, so the resulting sequence max length is
758 * 5 bytes.
759 *
760 * We perform the split writing the new sequence into the 'new' buffer
761 * with 'newlen' as length. Later the new sequence is inserted in place
762 * of the old one, possibly moving what is on the right a few bytes
763 * if the new sequence is longer than the older one. */
764 uint8_t seq[5], *n = seq;
765 int last = first+span-1; /* Last register covered by the sequence. */
766 int len;
767
768 if (is_zero || is_xzero) {
769 /* Handle splitting of ZERO / XZERO. */
770 if (index != first) {
771 len = index-first;
772 if (len > HLL_SPARSE_ZERO_MAX_LEN) {
773 HLL_SPARSE_XZERO_SET(n,len);
774 n += 2;
775 } else {
776 HLL_SPARSE_ZERO_SET(n,len);
777 n++;
778 }
779 }
780 HLL_SPARSE_VAL_SET(n,count,1);
781 n++;
782 if (index != last) {
783 len = last-index;
784 if (len > HLL_SPARSE_ZERO_MAX_LEN) {
785 HLL_SPARSE_XZERO_SET(n,len);
786 n += 2;
787 } else {
788 HLL_SPARSE_ZERO_SET(n,len);
789 n++;
790 }
791 }
792 } else {
793 /* Handle splitting of VAL. */
794 int curval = HLL_SPARSE_VAL_VALUE(p);
795
796 if (index != first) {
797 len = index-first;
798 HLL_SPARSE_VAL_SET(n,curval,len);
799 n++;
800 }
801 HLL_SPARSE_VAL_SET(n,count,1);
802 n++;
803 if (index != last) {
804 len = last-index;
805 HLL_SPARSE_VAL_SET(n,curval,len);
806 n++;
807 }
808 }
809
810 /* Step 3: substitute the new sequence with the old one.
811 *
812 * Note that we already allocated space on the sds string
813 * calling sdsMakeRoomFor(). */
814 int seqlen = n-seq;
815 int oldlen = is_xzero ? 2 : 1;
816 int deltalen = seqlen-oldlen;
817
818 if (deltalen > 0 &&
819 sdslen(o->ptr)+deltalen > server.hll_sparse_max_bytes) goto promote;
820 if (deltalen && next) memmove(next+deltalen,next,end-next);
821 sdsIncrLen(o->ptr,deltalen);
822 memcpy(p,seq,seqlen);
823 end += deltalen;
824
825 updated:
826 /* Step 4: Merge adjacent values if possible.
827 *
828 * The representation was updated, however the resulting representation
829 * may not be optimal: adjacent VAL opcodes can sometimes be merged into
830 * a single one. */
831 p = prev ? prev : sparse;
832 int scanlen = 5; /* Scan up to 5 upcodes starting from prev. */
833 while (p < end && scanlen--) {
834 if (HLL_SPARSE_IS_XZERO(p)) {
835 p += 2;
836 continue;
837 } else if (HLL_SPARSE_IS_ZERO(p)) {
838 p++;
839 continue;
840 }
841 /* We need two adjacent VAL opcodes to try a merge, having
842 * the same value, and a len that fits the VAL opcode max len. */
843 if (p+1 < end && HLL_SPARSE_IS_VAL(p+1)) {
844 int v1 = HLL_SPARSE_VAL_VALUE(p);
845 int v2 = HLL_SPARSE_VAL_VALUE(p+1);
846 if (v1 == v2) {
847 int len = HLL_SPARSE_VAL_LEN(p)+HLL_SPARSE_VAL_LEN(p+1);
848 if (len <= HLL_SPARSE_VAL_MAX_LEN) {
849 HLL_SPARSE_VAL_SET(p+1,v1,len);
850 memmove(p,p+1,end-p);
851 sdsIncrLen(o->ptr,-1);
852 end--;
853 /* After a merge we reiterate without incrementing 'p'
854 * in order to try to merge the just merged value with
855 * a value on its right. */
856 continue;
857 }
858 }
859 }
860 p++;
861 }
862
863 /* Invalidate the cached cardinality. */
864 hdr = o->ptr;
865 HLL_INVALIDATE_CACHE(hdr);
866 return 1;
867
868 promote: /* Promote to dense representation. */
869 if (hllSparseToDense(o) == C_ERR) return -1; /* Corrupted HLL. */
870 hdr = o->ptr;
871
872 /* We need to call hllDenseAdd() to perform the operation after the
873 * conversion. However the result must be 1, since if we need to
874 * convert from sparse to dense a register requires to be updated.
875 *
876 * Note that this in turn means that PFADD will make sure the command
877 * is propagated to slaves / AOF, so if there is a sparse -> dense
878 * convertion, it will be performed in all the slaves as well. */
879 int dense_retval = hllDenseAdd(hdr->registers, ele, elesize);
880 serverAssert(dense_retval == 1);
881 return dense_retval;
882 }
883
884 /* Compute SUM(2^-reg) in the sparse representation.
885 * PE is an array with a pre-computer table of values 2^-reg indexed by reg.
886 * As a side effect the integer pointed by 'ezp' is set to the number
887 * of zero registers. */
hllSparseSum(uint8_t * sparse,int sparselen,double * PE,int * ezp,int * invalid)888 double hllSparseSum(uint8_t *sparse, int sparselen, double *PE, int *ezp, int *invalid) {
889 double E = 0;
890 int ez = 0, idx = 0, runlen, regval;
891 uint8_t *end = sparse+sparselen, *p = sparse;
892
893 while(p < end) {
894 if (HLL_SPARSE_IS_ZERO(p)) {
895 runlen = HLL_SPARSE_ZERO_LEN(p);
896 idx += runlen;
897 ez += runlen;
898 /* Increment E at the end of the loop. */
899 p++;
900 } else if (HLL_SPARSE_IS_XZERO(p)) {
901 runlen = HLL_SPARSE_XZERO_LEN(p);
902 idx += runlen;
903 ez += runlen;
904 /* Increment E at the end of the loop. */
905 p += 2;
906 } else {
907 runlen = HLL_SPARSE_VAL_LEN(p);
908 regval = HLL_SPARSE_VAL_VALUE(p);
909 idx += runlen;
910 E += PE[regval]*runlen;
911 p++;
912 }
913 }
914 if (idx != HLL_REGISTERS && invalid) *invalid = 1;
915 E += ez; /* Add 2^0 'ez' times. */
916 *ezp = ez;
917 return E;
918 }
919
920 /* ========================= HyperLogLog Count ==============================
921 * This is the core of the algorithm where the approximated count is computed.
922 * The function uses the lower level hllDenseSum() and hllSparseSum() functions
923 * as helpers to compute the SUM(2^-reg) part of the computation, which is
924 * representation-specific, while all the rest is common. */
925
926 /* Implements the SUM operation for uint8_t data type which is only used
927 * internally as speedup for PFCOUNT with multiple keys. */
hllRawSum(uint8_t * registers,double * PE,int * ezp)928 double hllRawSum(uint8_t *registers, double *PE, int *ezp) {
929 double E = 0;
930 int j, ez = 0;
931 uint64_t *word = (uint64_t*) registers;
932 uint8_t *bytes;
933
934 for (j = 0; j < HLL_REGISTERS/8; j++) {
935 if (*word == 0) {
936 ez += 8;
937 } else {
938 bytes = (uint8_t*) word;
939 if (bytes[0]) E += PE[bytes[0]]; else ez++;
940 if (bytes[1]) E += PE[bytes[1]]; else ez++;
941 if (bytes[2]) E += PE[bytes[2]]; else ez++;
942 if (bytes[3]) E += PE[bytes[3]]; else ez++;
943 if (bytes[4]) E += PE[bytes[4]]; else ez++;
944 if (bytes[5]) E += PE[bytes[5]]; else ez++;
945 if (bytes[6]) E += PE[bytes[6]]; else ez++;
946 if (bytes[7]) E += PE[bytes[7]]; else ez++;
947 }
948 word++;
949 }
950 E += ez; /* 2^(-reg[j]) is 1 when m is 0, add it 'ez' times for every
951 zero register in the HLL. */
952 *ezp = ez;
953 return E;
954 }
955
956 /* Return the approximated cardinality of the set based on the harmonic
957 * mean of the registers values. 'hdr' points to the start of the SDS
958 * representing the String object holding the HLL representation.
959 *
960 * If the sparse representation of the HLL object is not valid, the integer
961 * pointed by 'invalid' is set to non-zero, otherwise it is left untouched.
962 *
963 * hllCount() supports a special internal-only encoding of HLL_RAW, that
964 * is, hdr->registers will point to an uint8_t array of HLL_REGISTERS element.
965 * This is useful in order to speedup PFCOUNT when called against multiple
966 * keys (no need to work with 6-bit integers encoding). */
hllCount(struct hllhdr * hdr,int * invalid)967 uint64_t hllCount(struct hllhdr *hdr, int *invalid) {
968 double m = HLL_REGISTERS;
969 double E, alpha = 0.7213/(1+1.079/m);
970 int j, ez; /* Number of registers equal to 0. */
971
972 /* We precompute 2^(-reg[j]) in a small table in order to
973 * speedup the computation of SUM(2^-register[0..i]). */
974 static int initialized = 0;
975 static double PE[64];
976 if (!initialized) {
977 PE[0] = 1; /* 2^(-reg[j]) is 1 when m is 0. */
978 for (j = 1; j < 64; j++) {
979 /* 2^(-reg[j]) is the same as 1/2^reg[j]. */
980 PE[j] = 1.0/(1ULL << j);
981 }
982 initialized = 1;
983 }
984
985 /* Compute SUM(2^-register[0..i]). */
986 if (hdr->encoding == HLL_DENSE) {
987 E = hllDenseSum(hdr->registers,PE,&ez);
988 } else if (hdr->encoding == HLL_SPARSE) {
989 E = hllSparseSum(hdr->registers,
990 sdslen((sds)hdr)-HLL_HDR_SIZE,PE,&ez,invalid);
991 } else if (hdr->encoding == HLL_RAW) {
992 E = hllRawSum(hdr->registers,PE,&ez);
993 } else {
994 serverPanic("Unknown HyperLogLog encoding in hllCount()");
995 }
996
997 /* Muliply the inverse of E for alpha_m * m^2 to have the raw estimate. */
998 E = (1/E)*alpha*m*m;
999
1000 /* Use the LINEARCOUNTING algorithm for small cardinalities.
1001 * For larger values but up to 72000 HyperLogLog raw approximation is
1002 * used since linear counting error starts to increase. However HyperLogLog
1003 * shows a strong bias in the range 2.5*16384 - 72000, so we try to
1004 * compensate for it. */
1005 if (E < m*2.5 && ez != 0) {
1006 E = m*log(m/ez); /* LINEARCOUNTING() */
1007 } else if (m == 16384 && E < 72000) {
1008 /* We did polynomial regression of the bias for this range, this
1009 * way we can compute the bias for a given cardinality and correct
1010 * according to it. Only apply the correction for P=14 that's what
1011 * we use and the value the correction was verified with. */
1012 double bias = 5.9119*1.0e-18*(E*E*E*E)
1013 -1.4253*1.0e-12*(E*E*E)+
1014 1.2940*1.0e-7*(E*E)
1015 -5.2921*1.0e-3*E+
1016 83.3216;
1017 E -= E*(bias/100);
1018 }
1019 /* We don't apply the correction for E > 1/30 of 2^32 since we use
1020 * a 64 bit function and 6 bit counters. To apply the correction for
1021 * 1/30 of 2^64 is not needed since it would require a huge set
1022 * to approach such a value. */
1023 return (uint64_t) E;
1024 }
1025
1026 /* Call hllDenseAdd() or hllSparseAdd() according to the HLL encoding. */
hllAdd(robj * o,unsigned char * ele,size_t elesize)1027 int hllAdd(robj *o, unsigned char *ele, size_t elesize) {
1028 struct hllhdr *hdr = o->ptr;
1029 switch(hdr->encoding) {
1030 case HLL_DENSE: return hllDenseAdd(hdr->registers,ele,elesize);
1031 case HLL_SPARSE: return hllSparseAdd(o,ele,elesize);
1032 default: return -1; /* Invalid representation. */
1033 }
1034 }
1035
1036 /* Merge by computing MAX(registers[i],hll[i]) the HyperLogLog 'hll'
1037 * with an array of uint8_t HLL_REGISTERS registers pointed by 'max'.
1038 *
1039 * The hll object must be already validated via isHLLObjectOrReply()
1040 * or in some other way.
1041 *
1042 * If the HyperLogLog is sparse and is found to be invalid, C_ERR
1043 * is returned, otherwise the function always succeeds. */
hllMerge(uint8_t * max,robj * hll)1044 int hllMerge(uint8_t *max, robj *hll) {
1045 struct hllhdr *hdr = hll->ptr;
1046 int i;
1047
1048 if (hdr->encoding == HLL_DENSE) {
1049 uint8_t val;
1050
1051 for (i = 0; i < HLL_REGISTERS; i++) {
1052 HLL_DENSE_GET_REGISTER(val,hdr->registers,i);
1053 if (val > max[i]) max[i] = val;
1054 }
1055 } else {
1056 uint8_t *p = hll->ptr, *end = p + sdslen(hll->ptr);
1057 long runlen, regval;
1058
1059 p += HLL_HDR_SIZE;
1060 i = 0;
1061 while(p < end) {
1062 if (HLL_SPARSE_IS_ZERO(p)) {
1063 runlen = HLL_SPARSE_ZERO_LEN(p);
1064 i += runlen;
1065 p++;
1066 } else if (HLL_SPARSE_IS_XZERO(p)) {
1067 runlen = HLL_SPARSE_XZERO_LEN(p);
1068 i += runlen;
1069 p += 2;
1070 } else {
1071 runlen = HLL_SPARSE_VAL_LEN(p);
1072 regval = HLL_SPARSE_VAL_VALUE(p);
1073 while(runlen--) {
1074 if (regval > max[i]) max[i] = regval;
1075 i++;
1076 }
1077 p++;
1078 }
1079 }
1080 if (i != HLL_REGISTERS) return C_ERR;
1081 }
1082 return C_OK;
1083 }
1084
1085 /* ========================== HyperLogLog commands ========================== */
1086
1087 /* Create an HLL object. We always create the HLL using sparse encoding.
1088 * This will be upgraded to the dense representation as needed. */
createHLLObject(void)1089 robj *createHLLObject(void) {
1090 robj *o;
1091 struct hllhdr *hdr;
1092 sds s;
1093 uint8_t *p;
1094 int sparselen = HLL_HDR_SIZE +
1095 (((HLL_REGISTERS+(HLL_SPARSE_XZERO_MAX_LEN-1)) /
1096 HLL_SPARSE_XZERO_MAX_LEN)*2);
1097 int aux;
1098
1099 /* Populate the sparse representation with as many XZERO opcodes as
1100 * needed to represent all the registers. */
1101 aux = HLL_REGISTERS;
1102 s = sdsnewlen(NULL,sparselen);
1103 p = (uint8_t*)s + HLL_HDR_SIZE;
1104 while(aux) {
1105 int xzero = HLL_SPARSE_XZERO_MAX_LEN;
1106 if (xzero > aux) xzero = aux;
1107 HLL_SPARSE_XZERO_SET(p,xzero);
1108 p += 2;
1109 aux -= xzero;
1110 }
1111 serverAssert((p-(uint8_t*)s) == sparselen);
1112
1113 /* Create the actual object. */
1114 o = createObject(OBJ_STRING,s);
1115 hdr = o->ptr;
1116 memcpy(hdr->magic,"HYLL",4);
1117 hdr->encoding = HLL_SPARSE;
1118 return o;
1119 }
1120
1121 /* Check if the object is a String with a valid HLL representation.
1122 * Return C_OK if this is true, otherwise reply to the client
1123 * with an error and return C_ERR. */
isHLLObjectOrReply(client * c,robj * o)1124 int isHLLObjectOrReply(client *c, robj *o) {
1125 struct hllhdr *hdr;
1126
1127 /* Key exists, check type */
1128 if (checkType(c,o,OBJ_STRING))
1129 return C_ERR; /* Error already sent. */
1130
1131 if (stringObjectLen(o) < sizeof(*hdr)) goto invalid;
1132 hdr = o->ptr;
1133
1134 /* Magic should be "HYLL". */
1135 if (hdr->magic[0] != 'H' || hdr->magic[1] != 'Y' ||
1136 hdr->magic[2] != 'L' || hdr->magic[3] != 'L') goto invalid;
1137
1138 if (hdr->encoding > HLL_MAX_ENCODING) goto invalid;
1139
1140 /* Dense representation string length should match exactly. */
1141 if (hdr->encoding == HLL_DENSE &&
1142 stringObjectLen(o) != HLL_DENSE_SIZE) goto invalid;
1143
1144 /* All tests passed. */
1145 return C_OK;
1146
1147 invalid:
1148 addReplySds(c,
1149 sdsnew("-WRONGTYPE Key is not a valid "
1150 "HyperLogLog string value.\r\n"));
1151 return C_ERR;
1152 }
1153
1154 /* PFADD var ele ele ele ... ele => :0 or :1 */
pfaddCommand(client * c)1155 void pfaddCommand(client *c) {
1156 robj *o = lookupKeyWrite(c->db,c->argv[1]);
1157 struct hllhdr *hdr;
1158 int updated = 0, j;
1159
1160 if (o == NULL) {
1161 /* Create the key with a string value of the exact length to
1162 * hold our HLL data structure. sdsnewlen() when NULL is passed
1163 * is guaranteed to return bytes initialized to zero. */
1164 o = createHLLObject();
1165 dbAdd(c->db,c->argv[1],o);
1166 updated++;
1167 } else {
1168 if (isHLLObjectOrReply(c,o) != C_OK) return;
1169 o = dbUnshareStringValue(c->db,c->argv[1],o);
1170 }
1171 /* Perform the low level ADD operation for every element. */
1172 for (j = 2; j < c->argc; j++) {
1173 int retval = hllAdd(o, (unsigned char*)c->argv[j]->ptr,
1174 sdslen(c->argv[j]->ptr));
1175 switch(retval) {
1176 case 1:
1177 updated++;
1178 break;
1179 case -1:
1180 addReplySds(c,sdsnew(invalid_hll_err));
1181 return;
1182 }
1183 }
1184 hdr = o->ptr;
1185 if (updated) {
1186 signalModifiedKey(c->db,c->argv[1]);
1187 notifyKeyspaceEvent(NOTIFY_STRING,"pfadd",c->argv[1],c->db->id);
1188 server.dirty++;
1189 HLL_INVALIDATE_CACHE(hdr);
1190 }
1191 addReply(c, updated ? shared.cone : shared.czero);
1192 }
1193
1194 /* PFCOUNT var -> approximated cardinality of set. */
pfcountCommand(client * c)1195 void pfcountCommand(client *c) {
1196 robj *o;
1197 struct hllhdr *hdr;
1198 uint64_t card;
1199
1200 /* Case 1: multi-key keys, cardinality of the union.
1201 *
1202 * When multiple keys are specified, PFCOUNT actually computes
1203 * the cardinality of the merge of the N HLLs specified. */
1204 if (c->argc > 2) {
1205 uint8_t max[HLL_HDR_SIZE+HLL_REGISTERS], *registers;
1206 int j;
1207
1208 /* Compute an HLL with M[i] = MAX(M[i]_j). */
1209 memset(max,0,sizeof(max));
1210 hdr = (struct hllhdr*) max;
1211 hdr->encoding = HLL_RAW; /* Special internal-only encoding. */
1212 registers = max + HLL_HDR_SIZE;
1213 for (j = 1; j < c->argc; j++) {
1214 /* Check type and size. */
1215 robj *o = lookupKeyRead(c->db,c->argv[j]);
1216 if (o == NULL) continue; /* Assume empty HLL for non existing var.*/
1217 if (isHLLObjectOrReply(c,o) != C_OK) return;
1218
1219 /* Merge with this HLL with our 'max' HHL by setting max[i]
1220 * to MAX(max[i],hll[i]). */
1221 if (hllMerge(registers,o) == C_ERR) {
1222 addReplySds(c,sdsnew(invalid_hll_err));
1223 return;
1224 }
1225 }
1226
1227 /* Compute cardinality of the resulting set. */
1228 addReplyLongLong(c,hllCount(hdr,NULL));
1229 return;
1230 }
1231
1232 /* Case 2: cardinality of the single HLL.
1233 *
1234 * The user specified a single key. Either return the cached value
1235 * or compute one and update the cache. */
1236 o = lookupKeyWrite(c->db,c->argv[1]);
1237 if (o == NULL) {
1238 /* No key? Cardinality is zero since no element was added, otherwise
1239 * we would have a key as HLLADD creates it as a side effect. */
1240 addReply(c,shared.czero);
1241 } else {
1242 if (isHLLObjectOrReply(c,o) != C_OK) return;
1243 o = dbUnshareStringValue(c->db,c->argv[1],o);
1244
1245 /* Check if the cached cardinality is valid. */
1246 hdr = o->ptr;
1247 if (HLL_VALID_CACHE(hdr)) {
1248 /* Just return the cached value. */
1249 card = (uint64_t)hdr->card[0];
1250 card |= (uint64_t)hdr->card[1] << 8;
1251 card |= (uint64_t)hdr->card[2] << 16;
1252 card |= (uint64_t)hdr->card[3] << 24;
1253 card |= (uint64_t)hdr->card[4] << 32;
1254 card |= (uint64_t)hdr->card[5] << 40;
1255 card |= (uint64_t)hdr->card[6] << 48;
1256 card |= (uint64_t)hdr->card[7] << 56;
1257 } else {
1258 int invalid = 0;
1259 /* Recompute it and update the cached value. */
1260 card = hllCount(hdr,&invalid);
1261 if (invalid) {
1262 addReplySds(c,sdsnew(invalid_hll_err));
1263 return;
1264 }
1265 hdr->card[0] = card & 0xff;
1266 hdr->card[1] = (card >> 8) & 0xff;
1267 hdr->card[2] = (card >> 16) & 0xff;
1268 hdr->card[3] = (card >> 24) & 0xff;
1269 hdr->card[4] = (card >> 32) & 0xff;
1270 hdr->card[5] = (card >> 40) & 0xff;
1271 hdr->card[6] = (card >> 48) & 0xff;
1272 hdr->card[7] = (card >> 56) & 0xff;
1273 /* This is not considered a read-only command even if the
1274 * data structure is not modified, since the cached value
1275 * may be modified and given that the HLL is a Redis string
1276 * we need to propagate the change. */
1277 signalModifiedKey(c->db,c->argv[1]);
1278 server.dirty++;
1279 }
1280 addReplyLongLong(c,card);
1281 }
1282 }
1283
1284 /* PFMERGE dest src1 src2 src3 ... srcN => OK */
pfmergeCommand(client * c)1285 void pfmergeCommand(client *c) {
1286 uint8_t max[HLL_REGISTERS];
1287 struct hllhdr *hdr;
1288 int j;
1289
1290 /* Compute an HLL with M[i] = MAX(M[i]_j).
1291 * We we the maximum into the max array of registers. We'll write
1292 * it to the target variable later. */
1293 memset(max,0,sizeof(max));
1294 for (j = 1; j < c->argc; j++) {
1295 /* Check type and size. */
1296 robj *o = lookupKeyRead(c->db,c->argv[j]);
1297 if (o == NULL) continue; /* Assume empty HLL for non existing var. */
1298 if (isHLLObjectOrReply(c,o) != C_OK) return;
1299
1300 /* Merge with this HLL with our 'max' HHL by setting max[i]
1301 * to MAX(max[i],hll[i]). */
1302 if (hllMerge(max,o) == C_ERR) {
1303 addReplySds(c,sdsnew(invalid_hll_err));
1304 return;
1305 }
1306 }
1307
1308 /* Create / unshare the destination key's value if needed. */
1309 robj *o = lookupKeyWrite(c->db,c->argv[1]);
1310 if (o == NULL) {
1311 /* Create the key with a string value of the exact length to
1312 * hold our HLL data structure. sdsnewlen() when NULL is passed
1313 * is guaranteed to return bytes initialized to zero. */
1314 o = createHLLObject();
1315 dbAdd(c->db,c->argv[1],o);
1316 } else {
1317 /* If key exists we are sure it's of the right type/size
1318 * since we checked when merging the different HLLs, so we
1319 * don't check again. */
1320 o = dbUnshareStringValue(c->db,c->argv[1],o);
1321 }
1322
1323 /* Only support dense objects as destination. */
1324 if (hllSparseToDense(o) == C_ERR) {
1325 addReplySds(c,sdsnew(invalid_hll_err));
1326 return;
1327 }
1328
1329 /* Write the resulting HLL to the destination HLL registers and
1330 * invalidate the cached value. */
1331 hdr = o->ptr;
1332 for (j = 0; j < HLL_REGISTERS; j++) {
1333 HLL_DENSE_SET_REGISTER(hdr->registers,j,max[j]);
1334 }
1335 HLL_INVALIDATE_CACHE(hdr);
1336
1337 signalModifiedKey(c->db,c->argv[1]);
1338 /* We generate an PFADD event for PFMERGE for semantical simplicity
1339 * since in theory this is a mass-add of elements. */
1340 notifyKeyspaceEvent(NOTIFY_STRING,"pfadd",c->argv[1],c->db->id);
1341 server.dirty++;
1342 addReply(c,shared.ok);
1343 }
1344
1345 /* ========================== Testing / Debugging ========================== */
1346
1347 /* PFSELFTEST
1348 * This command performs a self-test of the HLL registers implementation.
1349 * Something that is not easy to test from within the outside. */
1350 #define HLL_TEST_CYCLES 1000
pfselftestCommand(client * c)1351 void pfselftestCommand(client *c) {
1352 unsigned int j, i;
1353 sds bitcounters = sdsnewlen(NULL,HLL_DENSE_SIZE);
1354 struct hllhdr *hdr = (struct hllhdr*) bitcounters, *hdr2;
1355 robj *o = NULL;
1356 uint8_t bytecounters[HLL_REGISTERS];
1357
1358 /* Test 1: access registers.
1359 * The test is conceived to test that the different counters of our data
1360 * structure are accessible and that setting their values both result in
1361 * the correct value to be retained and not affect adjacent values. */
1362 for (j = 0; j < HLL_TEST_CYCLES; j++) {
1363 /* Set the HLL counters and an array of unsigned byes of the
1364 * same size to the same set of random values. */
1365 for (i = 0; i < HLL_REGISTERS; i++) {
1366 unsigned int r = rand() & HLL_REGISTER_MAX;
1367
1368 bytecounters[i] = r;
1369 HLL_DENSE_SET_REGISTER(hdr->registers,i,r);
1370 }
1371 /* Check that we are able to retrieve the same values. */
1372 for (i = 0; i < HLL_REGISTERS; i++) {
1373 unsigned int val;
1374
1375 HLL_DENSE_GET_REGISTER(val,hdr->registers,i);
1376 if (val != bytecounters[i]) {
1377 addReplyErrorFormat(c,
1378 "TESTFAILED Register %d should be %d but is %d",
1379 i, (int) bytecounters[i], (int) val);
1380 goto cleanup;
1381 }
1382 }
1383 }
1384
1385 /* Test 2: approximation error.
1386 * The test adds unique elements and check that the estimated value
1387 * is always reasonable bounds.
1388 *
1389 * We check that the error is smaller than a few times than the expected
1390 * standard error, to make it very unlikely for the test to fail because
1391 * of a "bad" run.
1392 *
1393 * The test is performed with both dense and sparse HLLs at the same
1394 * time also verifying that the computed cardinality is the same. */
1395 memset(hdr->registers,0,HLL_DENSE_SIZE-HLL_HDR_SIZE);
1396 o = createHLLObject();
1397 double relerr = 1.04/sqrt(HLL_REGISTERS);
1398 int64_t checkpoint = 1;
1399 uint64_t seed = (uint64_t)rand() | (uint64_t)rand() << 32;
1400 uint64_t ele;
1401 for (j = 1; j <= 10000000; j++) {
1402 ele = j ^ seed;
1403 hllDenseAdd(hdr->registers,(unsigned char*)&ele,sizeof(ele));
1404 hllAdd(o,(unsigned char*)&ele,sizeof(ele));
1405
1406 /* Make sure that for small cardinalities we use sparse
1407 * encoding. */
1408 if (j == checkpoint && j < server.hll_sparse_max_bytes/2) {
1409 hdr2 = o->ptr;
1410 if (hdr2->encoding != HLL_SPARSE) {
1411 addReplyError(c, "TESTFAILED sparse encoding not used");
1412 goto cleanup;
1413 }
1414 }
1415
1416 /* Check that dense and sparse representations agree. */
1417 if (j == checkpoint && hllCount(hdr,NULL) != hllCount(o->ptr,NULL)) {
1418 addReplyError(c, "TESTFAILED dense/sparse disagree");
1419 goto cleanup;
1420 }
1421
1422 /* Check error. */
1423 if (j == checkpoint) {
1424 int64_t abserr = checkpoint - (int64_t)hllCount(hdr,NULL);
1425 uint64_t maxerr = ceil(relerr*6*checkpoint);
1426
1427 /* Adjust the max error we expect for cardinality 10
1428 * since from time to time it is statistically likely to get
1429 * much higher error due to collision, resulting into a false
1430 * positive. */
1431 if (j == 10) maxerr = 1;
1432
1433 if (abserr < 0) abserr = -abserr;
1434 if (abserr > (int64_t)maxerr) {
1435 addReplyErrorFormat(c,
1436 "TESTFAILED Too big error. card:%llu abserr:%llu",
1437 (unsigned long long) checkpoint,
1438 (unsigned long long) abserr);
1439 goto cleanup;
1440 }
1441 checkpoint *= 10;
1442 }
1443 }
1444
1445 /* Success! */
1446 addReply(c,shared.ok);
1447
1448 cleanup:
1449 sdsfree(bitcounters);
1450 if (o) decrRefCount(o);
1451 }
1452
1453 /* PFDEBUG <subcommand> <key> ... args ...
1454 * Different debugging related operations about the HLL implementation. */
pfdebugCommand(client * c)1455 void pfdebugCommand(client *c) {
1456 char *cmd = c->argv[1]->ptr;
1457 struct hllhdr *hdr;
1458 robj *o;
1459 int j;
1460
1461 o = lookupKeyWrite(c->db,c->argv[2]);
1462 if (o == NULL) {
1463 addReplyError(c,"The specified key does not exist");
1464 return;
1465 }
1466 if (isHLLObjectOrReply(c,o) != C_OK) return;
1467 o = dbUnshareStringValue(c->db,c->argv[2],o);
1468 hdr = o->ptr;
1469
1470 /* PFDEBUG GETREG <key> */
1471 if (!strcasecmp(cmd,"getreg")) {
1472 if (c->argc != 3) goto arityerr;
1473
1474 if (hdr->encoding == HLL_SPARSE) {
1475 if (hllSparseToDense(o) == C_ERR) {
1476 addReplySds(c,sdsnew(invalid_hll_err));
1477 return;
1478 }
1479 server.dirty++; /* Force propagation on encoding change. */
1480 }
1481
1482 hdr = o->ptr;
1483 addReplyMultiBulkLen(c,HLL_REGISTERS);
1484 for (j = 0; j < HLL_REGISTERS; j++) {
1485 uint8_t val;
1486
1487 HLL_DENSE_GET_REGISTER(val,hdr->registers,j);
1488 addReplyLongLong(c,val);
1489 }
1490 }
1491 /* PFDEBUG DECODE <key> */
1492 else if (!strcasecmp(cmd,"decode")) {
1493 if (c->argc != 3) goto arityerr;
1494
1495 uint8_t *p = o->ptr, *end = p+sdslen(o->ptr);
1496 sds decoded = sdsempty();
1497
1498 if (hdr->encoding != HLL_SPARSE) {
1499 addReplyError(c,"HLL encoding is not sparse");
1500 return;
1501 }
1502
1503 p += HLL_HDR_SIZE;
1504 while(p < end) {
1505 int runlen, regval;
1506
1507 if (HLL_SPARSE_IS_ZERO(p)) {
1508 runlen = HLL_SPARSE_ZERO_LEN(p);
1509 p++;
1510 decoded = sdscatprintf(decoded,"z:%d ",runlen);
1511 } else if (HLL_SPARSE_IS_XZERO(p)) {
1512 runlen = HLL_SPARSE_XZERO_LEN(p);
1513 p += 2;
1514 decoded = sdscatprintf(decoded,"Z:%d ",runlen);
1515 } else {
1516 runlen = HLL_SPARSE_VAL_LEN(p);
1517 regval = HLL_SPARSE_VAL_VALUE(p);
1518 p++;
1519 decoded = sdscatprintf(decoded,"v:%d,%d ",regval,runlen);
1520 }
1521 }
1522 decoded = sdstrim(decoded," ");
1523 addReplyBulkCBuffer(c,decoded,sdslen(decoded));
1524 sdsfree(decoded);
1525 }
1526 /* PFDEBUG ENCODING <key> */
1527 else if (!strcasecmp(cmd,"encoding")) {
1528 char *encodingstr[2] = {"dense","sparse"};
1529 if (c->argc != 3) goto arityerr;
1530
1531 addReplyStatus(c,encodingstr[hdr->encoding]);
1532 }
1533 /* PFDEBUG TODENSE <key> */
1534 else if (!strcasecmp(cmd,"todense")) {
1535 int conv = 0;
1536 if (c->argc != 3) goto arityerr;
1537
1538 if (hdr->encoding == HLL_SPARSE) {
1539 if (hllSparseToDense(o) == C_ERR) {
1540 addReplySds(c,sdsnew(invalid_hll_err));
1541 return;
1542 }
1543 conv = 1;
1544 server.dirty++; /* Force propagation on encoding change. */
1545 }
1546 addReply(c,conv ? shared.cone : shared.czero);
1547 } else {
1548 addReplyErrorFormat(c,"Unknown PFDEBUG subcommand '%s'", cmd);
1549 }
1550 return;
1551
1552 arityerr:
1553 addReplyErrorFormat(c,
1554 "Wrong number of arguments for the '%s' subcommand",cmd);
1555 }
1556
1557