xref: /redis-3.2.3/src/hyperloglog.c (revision dde8dff7)
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 "redis.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 HLL_SPARSE_MAX.
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[0] |= (1<<7)
192 #define HLL_VALID_CACHE(hdr) (((hdr)->card[0] & (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_MAX_ENCODING 1
204 
205 #define HLL_SPARSE_MAX 3000
206 
207 static char *invalid_hll_err = "Corrupted HLL object detected";
208 
209 /* =========================== Low level bit macros ========================= */
210 
211 /* Macros to access the dense representation.
212  *
213  * We need to get and set 6 bit counters in an array of 8 bit bytes.
214  * We use macros to make sure the code is inlined since speed is critical
215  * especially in order to compute the approximated cardinality in
216  * HLLCOUNT where we need to access all the registers at once.
217  * For the same reason we also want to avoid conditionals in this code path.
218  *
219  * +--------+--------+--------+------//
220  * |11000000|22221111|33333322|55444444
221  * +--------+--------+--------+------//
222  *
223  * Note: in the above representation the most significant bit (MSB)
224  * of every byte is on the left. We start using bits from the LSB to MSB,
225  * and so forth passing to the next byte.
226  *
227  * Example, we want to access to counter at pos = 1 ("111111" in the
228  * illustration above).
229  *
230  * The index of the first byte b0 containing our data is:
231  *
232  *  b0 = 6 * pos / 8 = 0
233  *
234  *   +--------+
235  *   |11000000|  <- Our byte at b0
236  *   +--------+
237  *
238  * The position of the first bit (counting from the LSB = 0) in the byte
239  * is given by:
240  *
241  *  fb = 6 * pos % 8 -> 6
242  *
243  * Right shift b0 of 'fb' bits.
244  *
245  *   +--------+
246  *   |11000000|  <- Initial value of b0
247  *   |00000011|  <- After right shift of 6 pos.
248  *   +--------+
249  *
250  * Left shift b1 of bits 8-fb bits (2 bits)
251  *
252  *   +--------+
253  *   |22221111|  <- Initial value of b1
254  *   |22111100|  <- After left shift of 2 bits.
255  *   +--------+
256  *
257  * OR the two bits, and finally AND with 111111 (63 in decimal) to
258  * clean the higher order bits we are not interested in:
259  *
260  *   +--------+
261  *   |00000011|  <- b0 right shifted
262  *   |22111100|  <- b1 left shifted
263  *   |22111111|  <- b0 OR b1
264  *   |  111111|  <- (b0 OR b1) AND 63, our value.
265  *   +--------+
266  *
267  * We can try with a different example, like pos = 0. In this case
268  * the 6-bit counter is actually contained in a single byte.
269  *
270  *  b0 = 6 * pos / 8 = 0
271  *
272  *   +--------+
273  *   |11000000|  <- Our byte at b0
274  *   +--------+
275  *
276  *  fb = 6 * pos % 8 = 0
277  *
278  *  So we right shift of 0 bits (no shift in practice) and
279  *  left shift the next byte of 8 bits, even if we don't use it,
280  *  but this has the effect of clearing the bits so the result
281  *  will not be affacted after the OR.
282  *
283  * -------------------------------------------------------------------------
284  *
285  * Setting the register is a bit more complex, let's assume that 'val'
286  * is the value we want to set, already in the right range.
287  *
288  * We need two steps, in one we need to clear the bits, and in the other
289  * we need to bitwise-OR the new bits.
290  *
291  * Let's try with 'pos' = 1, so our first byte at 'b' is 0,
292  *
293  * "fb" is 6 in this case.
294  *
295  *   +--------+
296  *   |11000000|  <- Our byte at b0
297  *   +--------+
298  *
299  * To create a AND-mask to clear the bits about this position, we just
300  * initialize the mask with the value 63, left shift it of "fs" bits,
301  * and finally invert the result.
302  *
303  *   +--------+
304  *   |00111111|  <- "mask" starts at 63
305  *   |11000000|  <- "mask" after left shift of "ls" bits.
306  *   |00111111|  <- "mask" after invert.
307  *   +--------+
308  *
309  * Now we can bitwise-AND the byte at "b" with the mask, and bitwise-OR
310  * it with "val" left-shifted of "ls" bits to set the new bits.
311  *
312  * Now let's focus on the next byte b1:
313  *
314  *   +--------+
315  *   |22221111|  <- Initial value of b1
316  *   +--------+
317  *
318  * To build the AND mask we start again with the 63 value, right shift
319  * it by 8-fb bits, and invert it.
320  *
321  *   +--------+
322  *   |00111111|  <- "mask" set at 2&6-1
323  *   |00001111|  <- "mask" after the right shift by 8-fb = 2 bits
324  *   |11110000|  <- "mask" after bitwise not.
325  *   +--------+
326  *
327  * Now we can mask it with b+1 to clear the old bits, and bitwise-OR
328  * with "val" left-shifted by "rs" bits to set the new value.
329  */
330 
331 /* Note: if we access the last counter, we will also access the b+1 byte
332  * that is out of the array, but sds strings always have an implicit null
333  * term, so the byte exists, and we can skip the conditional (or the need
334  * to allocate 1 byte more explicitly). */
335 
336 /* Store the value of the register at position 'regnum' into variable 'target'.
337  * 'p' is an array of unsigned bytes. */
338 #define HLL_DENSE_GET_REGISTER(target,p,regnum) do { \
339     uint8_t *_p = (uint8_t*) p; \
340     unsigned long _byte = regnum*HLL_BITS/8; \
341     unsigned long _fb = regnum*HLL_BITS&7; \
342     unsigned long _fb8 = 8 - _fb; \
343     unsigned long b0 = _p[_byte]; \
344     unsigned long b1 = _p[_byte+1]; \
345     target = ((b0 >> _fb) | (b1 << _fb8)) & HLL_REGISTER_MAX; \
346 } while(0)
347 
348 /* Set the value of the register at position 'regnum' to 'val'.
349  * 'p' is an array of unsigned bytes. */
350 #define HLL_DENSE_SET_REGISTER(p,regnum,val) do { \
351     uint8_t *_p = (uint8_t*) p; \
352     unsigned long _byte = regnum*HLL_BITS/8; \
353     unsigned long _fb = regnum*HLL_BITS&7; \
354     unsigned long _fb8 = 8 - _fb; \
355     unsigned long _v = val; \
356     _p[_byte] &= ~(HLL_REGISTER_MAX << _fb); \
357     _p[_byte] |= _v << _fb; \
358     _p[_byte+1] &= ~(HLL_REGISTER_MAX >> _fb8); \
359     _p[_byte+1] |= _v >> _fb8; \
360 } while(0)
361 
362 /* Macros to access the sparse representation.
363  * The macros parameter is expected to be an uint8_t pointer. */
364 #define HLL_SPARSE_XZERO_BIT 0x40 /* 01xxxxxx */
365 #define HLL_SPARSE_VAL_BIT 0x80 /* 1vvvvvxx */
366 #define HLL_SPARSE_IS_ZERO(p) (((*(p)) & 0xc0) == 0) /* 00xxxxxx */
367 #define HLL_SPARSE_IS_XZERO(p) (((*(p)) & 0xc0) == HLL_SPARSE_XZERO_BIT)
368 #define HLL_SPARSE_IS_VAL(p) ((*(p)) & HLL_SPARSE_VAL_BIT)
369 #define HLL_SPARSE_ZERO_LEN(p) (((*(p)) & 0x3f)+1)
370 #define HLL_SPARSE_XZERO_LEN(p) (((((*(p)) & 0x3f) << 8) | (*((p)+1)))+1)
371 #define HLL_SPARSE_VAL_VALUE(p) ((((*(p)) >> 2) & 0x1f)+1)
372 #define HLL_SPARSE_VAL_LEN(p) (((*(p)) & 0x3)+1)
373 #define HLL_SPARSE_VAL_MAX_VALUE 32
374 #define HLL_SPARSE_VAL_MAX_LEN 4
375 #define HLL_SPARSE_ZERO_MAX_LEN 64
376 #define HLL_SPARSE_XZERO_MAX_LEN 16384
377 #define HLL_SPARSE_VAL_SET(p,val,len) do { \
378     *(p) = (((val)-1)<<2|((len)-1))|HLL_SPARSE_VAL_BIT; \
379 } while(0)
380 #define HLL_SPARSE_ZERO_SET(p,len) do { \
381     *(p) = (len)-1; \
382 } while(0)
383 #define HLL_SPARSE_XZERO_SET(p,len) do { \
384     int _l = (len)-1; \
385     *(p) = (_l>>8) | HLL_SPARSE_XZERO_BIT; \
386     *((p)+1) = (_l&0xff); \
387 } while(0)
388 
389 /* ========================= HyperLogLog algorithm  ========================= */
390 
391 /* Our hash function is MurmurHash2, 64 bit version.
392  * It was modified for Redis in order to provide the same result in
393  * big and little endian archs (endian neutral). */
394 uint64_t MurmurHash64A (const void * key, int len, unsigned int seed) {
395     const uint64_t m = 0xc6a4a7935bd1e995;
396     const int r = 47;
397     uint64_t h = seed ^ (len * m);
398     const uint8_t *data = (const uint8_t *)key;
399     const uint8_t *end = data + (len-(len&7));
400 
401     while(data != end) {
402         uint64_t k;
403 
404 #if (BYTE_ORDER == LITTLE_ENDIAN)
405         k = *((uint64_t*)data);
406 #else
407         k = (uint64_t) data[0];
408         k |= (uint64_t) data[1] << 8;
409         k |= (uint64_t) data[2] << 16;
410         k |= (uint64_t) data[3] << 24;
411         k |= (uint64_t) data[4] << 32;
412         k |= (uint64_t) data[5] << 40;
413         k |= (uint64_t) data[6] << 48;
414         k |= (uint64_t) data[7] << 56;
415 #endif
416 
417         k *= m;
418         k ^= k >> r;
419         k *= m;
420         h ^= k;
421         h *= m;
422         data += 8;
423     }
424 
425     switch(len & 7) {
426     case 7: h ^= (uint64_t)data[6] << 48;
427     case 6: h ^= (uint64_t)data[5] << 40;
428     case 5: h ^= (uint64_t)data[4] << 32;
429     case 4: h ^= (uint64_t)data[3] << 24;
430     case 3: h ^= (uint64_t)data[2] << 16;
431     case 2: h ^= (uint64_t)data[1] << 8;
432     case 1: h ^= (uint64_t)data[0];
433             h *= m;
434     };
435 
436     h ^= h >> r;
437     h *= m;
438     h ^= h >> r;
439     return h;
440 }
441 
442 /* Given a string element to add to the HyperLogLog, returns the length
443  * of the pattern 000..1 of the element hash. As a side effect 'regp' is
444  * set to the register index this element hashes to. */
445 int hllPatLen(unsigned char *ele, size_t elesize, long *regp) {
446     uint64_t hash, bit, index;
447     int count;
448 
449     /* Count the number of zeroes starting from bit HLL_REGISTERS
450      * (that is a power of two corresponding to the first bit we don't use
451      * as index). The max run can be 64-P+1 bits.
452      *
453      * Note that the final "1" ending the sequence of zeroes must be
454      * included in the count, so if we find "001" the count is 3, and
455      * the smallest count possible is no zeroes at all, just a 1 bit
456      * at the first position, that is a count of 1.
457      *
458      * This may sound like inefficient, but actually in the average case
459      * there are high probabilities to find a 1 after a few iterations. */
460     hash = MurmurHash64A(ele,elesize,0xadc83b19ULL);
461     index = hash & HLL_P_MASK; /* Register index. */
462     hash |= ((uint64_t)1<<63); /* Make sure the loop terminates. */
463     bit = HLL_REGISTERS; /* First bit not used to address the register. */
464     count = 1; /* Initialized to 1 since we count the "00000...1" pattern. */
465     while((hash & bit) == 0) {
466         count++;
467         bit <<= 1;
468     }
469     *regp = (int) index;
470     return count;
471 }
472 
473 /* ================== Dense representation implementation  ================== */
474 
475 /* "Add" the element in the dense hyperloglog data structure.
476  * Actually nothing is added, but the max 0 pattern counter of the subset
477  * the element belongs to is incremented if needed.
478  *
479  * 'registers' is expected to have room for HLL_REGISTERS plus an
480  * additional byte on the right. This requirement is met by sds strings
481  * automatically since they are implicitly null terminated.
482  *
483  * The function always succeed, however if as a result of the operation
484  * the approximated cardinality changed, 1 is returned. Otherwise 0
485  * is returned. */
486 int hllDenseAdd(uint8_t *registers, unsigned char *ele, size_t elesize) {
487     uint8_t oldcount, count;
488     long index;
489 
490     /* Update the register if this element produced a longer run of zeroes. */
491     count = hllPatLen(ele,elesize,&index);
492     HLL_DENSE_GET_REGISTER(oldcount,registers,index);
493     if (count > oldcount) {
494         HLL_DENSE_SET_REGISTER(registers,index,count);
495         return 1;
496     } else {
497         return 0;
498     }
499 }
500 
501 /* Compute SUM(2^-reg) in the dense representation.
502  * PE is an array with a pre-computer table of values 2^-reg indexed by reg.
503  * As a side effect the integer pointed by 'ezp' is set to the number
504  * of zero registers. */
505 double hllDenseSum(uint8_t *registers, double *PE, int *ezp) {
506     double E = 0;
507     int j, ez = 0;
508 
509     /* Redis default is to use 16384 registers 6 bits each. The code works
510      * with other values by modifying the defines, but for our target value
511      * we take a faster path with unrolled loops. */
512     if (HLL_REGISTERS == 16384 && HLL_BITS == 6) {
513         uint8_t *r = registers;
514         unsigned long r0, r1, r2, r3, r4, r5, r6, r7, r8, r9,
515                       r10, r11, r12, r13, r14, r15;
516         for (j = 0; j < 1024; j++) {
517             /* Handle 16 registers per iteration. */
518             r0 = r[0] & 63; if (r0 == 0) ez++;
519             r1 = (r[0] >> 6 | r[1] << 2) & 63; if (r1 == 0) ez++;
520             r2 = (r[1] >> 4 | r[2] << 4) & 63; if (r2 == 0) ez++;
521             r3 = (r[2] >> 2) & 63; if (r3 == 0) ez++;
522             r4 = r[3] & 63; if (r4 == 0) ez++;
523             r5 = (r[3] >> 6 | r[4] << 2) & 63; if (r5 == 0) ez++;
524             r6 = (r[4] >> 4 | r[5] << 4) & 63; if (r6 == 0) ez++;
525             r7 = (r[5] >> 2) & 63; if (r7 == 0) ez++;
526             r8 = r[6] & 63; if (r8 == 0) ez++;
527             r9 = (r[6] >> 6 | r[7] << 2) & 63; if (r9 == 0) ez++;
528             r10 = (r[7] >> 4 | r[8] << 4) & 63; if (r10 == 0) ez++;
529             r11 = (r[8] >> 2) & 63; if (r11 == 0) ez++;
530             r12 = r[9] & 63; if (r12 == 0) ez++;
531             r13 = (r[9] >> 6 | r[10] << 2) & 63; if (r13 == 0) ez++;
532             r14 = (r[10] >> 4 | r[11] << 4) & 63; if (r14 == 0) ez++;
533             r15 = (r[11] >> 2) & 63; if (r15 == 0) ez++;
534 
535             /* Additional parens will allow the compiler to optimize the
536              * code more with a loss of precision that is not very relevant
537              * here (floating point math is not commutative!). */
538             E += (PE[r0] + PE[r1]) + (PE[r2] + PE[r3]) + (PE[r4] + PE[r5]) +
539                  (PE[r6] + PE[r7]) + (PE[r8] + PE[r9]) + (PE[r10] + PE[r11]) +
540                  (PE[r12] + PE[r13]) + (PE[r14] + PE[r15]);
541             r += 12;
542         }
543     } else {
544         for (j = 0; j < HLL_REGISTERS; j++) {
545             unsigned long reg;
546 
547             HLL_DENSE_GET_REGISTER(reg,registers,j);
548             if (reg == 0) {
549                 ez++;
550                 E += 1; /* 2^(-reg[j]) is 1 when m is 0. */
551             } else {
552                 E += PE[reg]; /* Precomputed 2^(-reg[j]). */
553             }
554         }
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 REDIS_OK if the sparse representation was valid,
567  * otherwise REDIS_ERR is returned if the representation was corrupted. */
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 REDIS_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 REDIS_ERR;
614     }
615 
616     /* Free the old representation and set the new one. */
617     sdsfree(o->ptr);
618     o->ptr = dense;
619     return REDIS_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 HLL_SPARSE_MAX. */
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 && sdslen(o->ptr)+deltalen > HLL_SPARSE_MAX) goto promote;
819      if (deltalen && next) memmove(next+deltalen,next,end-next);
820      sdsIncrLen(o->ptr,deltalen);
821      memcpy(p,seq,seqlen);
822      end += deltalen;
823 
824 updated:
825     /* Step 4: Merge adjacent values if possible.
826      *
827      * The representation was updated, however the resulting representation
828      * may not be optimal: adjacent VAL opcodes can sometimes be merged into
829      * a single one. */
830     p = prev ? prev : sparse;
831     int scanlen = 5; /* Scan up to 5 upcodes starting from prev. */
832     while (p < end && scanlen--) {
833         if (HLL_SPARSE_IS_XZERO(p)) {
834             p += 2;
835             continue;
836         } else if (HLL_SPARSE_IS_ZERO(p)) {
837             p++;
838             continue;
839         }
840         /* We need two adjacent VAL opcodes to try a merge, having
841          * the same value, and a len that fits the VAL opcode max len. */
842         if (p+1 < end && HLL_SPARSE_IS_VAL(p+1)) {
843             int v1 = HLL_SPARSE_VAL_VALUE(p);
844             int v2 = HLL_SPARSE_VAL_VALUE(p+1);
845             if (v1 == v2) {
846                 int len = HLL_SPARSE_VAL_LEN(p)+HLL_SPARSE_VAL_LEN(p+1);
847                 if (len <= HLL_SPARSE_VAL_MAX_LEN) {
848                     HLL_SPARSE_VAL_SET(p+1,v1,len);
849                     memmove(p,p+1,end-p);
850                     sdsIncrLen(o->ptr,-1);
851                     end--;
852                     /* After a merge we reiterate without incrementing 'p'
853                      * in order to try to merge the just merged value with
854                      * a value on its right. */
855                     continue;
856                 }
857             }
858         }
859         p++;
860     }
861 
862     /* Invalidate the cached cardinality. */
863     hdr = o->ptr;
864     HLL_INVALIDATE_CACHE(hdr);
865     return 1;
866 
867 promote: /* Promote to dense representation. */
868     if (hllSparseToDense(o) == REDIS_ERR) return -1; /* Corrupted HLL. */
869     hdr = o->ptr;
870 
871     /* We need to call hllDenseAdd() to perform the operation after the
872      * conversion. However the result must be 1, since if we need to
873      * convert from sparse to dense a register requires to be updated.
874      *
875      * Note that this in turn means that PFADD will make sure the command
876      * is propagated to slaves / AOF, so if there is a sparse -> dense
877      * convertion, it will be performed in all the slaves as well. */
878     int dense_retval = hllDenseAdd(hdr->registers, ele, elesize);
879     redisAssert(dense_retval == 1);
880     return dense_retval;
881 }
882 
883 /* Compute SUM(2^-reg) in the sparse representation.
884  * PE is an array with a pre-computer table of values 2^-reg indexed by reg.
885  * As a side effect the integer pointed by 'ezp' is set to the number
886  * of zero registers. */
887 double hllSparseSum(uint8_t *sparse, int sparselen, double *PE, int *ezp, int *invalid) {
888     double E = 0;
889     int ez = 0, idx = 0, runlen, regval;
890     uint8_t *end = sparse+sparselen, *p = sparse;
891 
892     while(p < end) {
893         if (HLL_SPARSE_IS_ZERO(p)) {
894             runlen = HLL_SPARSE_ZERO_LEN(p);
895             idx += runlen;
896             ez += runlen;
897             E += 1*runlen; /* 2^(-reg[j]) is 1 when m is 0. */
898             p++;
899         } else if (HLL_SPARSE_IS_XZERO(p)) {
900             runlen = HLL_SPARSE_XZERO_LEN(p);
901             idx += runlen;
902             ez += runlen;
903             E += 1*runlen; /* 2^(-reg[j]) is 1 when m is 0. */
904             p += 2;
905         } else {
906             runlen = HLL_SPARSE_VAL_LEN(p);
907             regval = HLL_SPARSE_VAL_VALUE(p);
908             idx += runlen;
909             E += PE[regval]*runlen;
910             p++;
911         }
912     }
913     if (idx != HLL_REGISTERS && invalid) *invalid = 1;
914     *ezp = ez;
915     return E;
916 }
917 
918 /* ========================= HyperLogLog Count ==============================
919  * This is the core of the algorithm where the approximated count is computed.
920  * The function uses the lower level hllDenseSum() and hllSparseSum() functions
921  * as helpers to compute the SUM(2^-reg) part of the computation, which is
922  * representation-specific, while all the rest is common. */
923 
924 /* Return the approximated cardinality of the set based on the armonic
925  * mean of the registers values. 'hdr' points to the start of the SDS
926  * representing the String object holding the HLL representation.
927  *
928  * If the sparse representation of the HLL object is not valid, the integer
929  * pointed by 'invalid' is set to non-zero, otherwise it is left untouched. */
930 uint64_t hllCount(struct hllhdr *hdr, int *invalid) {
931     double m = HLL_REGISTERS;
932     double E, alpha = 0.7213/(1+1.079/m);
933     int j, ez; /* Number of registers equal to 0. */
934 
935     /* We precompute 2^(-reg[j]) in a small table in order to
936      * speedup the computation of SUM(2^-register[0..i]). */
937     static int initialized = 0;
938     static double PE[64];
939     if (!initialized) {
940         PE[0] = 1; /* 2^(-reg[j]) is 1 when m is 0. */
941         for (j = 1; j < 64; j++) {
942             /* 2^(-reg[j]) is the same as 1/2^reg[j]. */
943             PE[j] = 1.0/(1ULL << j);
944         }
945         initialized = 1;
946     }
947 
948     /* Compute SUM(2^-register[0..i]). */
949     if (hdr->encoding == HLL_DENSE) {
950         E = hllDenseSum(hdr->registers,PE,&ez);
951     } else {
952         E = hllSparseSum(hdr->registers,
953                          sdslen((sds)hdr)-HLL_HDR_SIZE,PE,&ez,invalid);
954     }
955 
956     /* Muliply the inverse of E for alpha_m * m^2 to have the raw estimate. */
957     E = (1/E)*alpha*m*m;
958 
959     /* Use the LINEARCOUNTING algorithm for small cardinalities.
960      * For larger values but up to 72000 HyperLogLog raw approximation is
961      * used since linear counting error starts to increase. However HyperLogLog
962      * shows a strong bias in the range 2.5*16384 - 72000, so we try to
963      * compensate for it. */
964     if (E < m*2.5 && ez != 0) {
965         E = m*log(m/ez); /* LINEARCOUNTING() */
966     } else if (m == 16384 && E < 72000) {
967         /* We did polynomial regression of the bias for this range, this
968          * way we can compute the bias for a given cardinality and correct
969          * according to it. Only apply the correction for P=14 that's what
970          * we use and the value the correction was verified with. */
971         double bias = 5.9119*1.0e-18*(E*E*E*E)
972                       -1.4253*1.0e-12*(E*E*E)+
973                       1.2940*1.0e-7*(E*E)
974                       -5.2921*1.0e-3*E+
975                       83.3216;
976         E -= E*(bias/100);
977     }
978     /* We don't apply the correction for E > 1/30 of 2^32 since we use
979      * a 64 bit function and 6 bit counters. To apply the correction for
980      * 1/30 of 2^64 is not needed since it would require a huge set
981      * to approach such a value. */
982     return (uint64_t) E;
983 }
984 
985 /* Call hllDenseAdd() or hllSparseAdd() according to the HLL encoding. */
986 int hllAdd(robj *o, unsigned char *ele, size_t elesize) {
987     struct hllhdr *hdr = o->ptr;
988     switch(hdr->encoding) {
989     case HLL_DENSE: return hllDenseAdd(hdr->registers,ele,elesize);
990     case HLL_SPARSE: return hllSparseAdd(o,ele,elesize);
991     default: return -1; /* Invalid representation. */
992     }
993 }
994 
995 /* ========================== HyperLogLog commands ========================== */
996 
997 /* Create an HLL object. We always create the HLL using sparse encoding.
998  * This will be upgraded to the dense representation as needed. */
999 robj *createHLLObject(void) {
1000     robj *o;
1001     struct hllhdr *hdr;
1002     sds s;
1003     uint8_t *p;
1004     int sparselen = HLL_HDR_SIZE +
1005                     (((HLL_REGISTERS+(HLL_SPARSE_XZERO_MAX_LEN-1)) /
1006                      HLL_SPARSE_XZERO_MAX_LEN)*2);
1007     int aux;
1008 
1009     /* Populate the sparse representation with as many XZERO opcodes as
1010      * needed to represent all the registers. */
1011     aux = HLL_REGISTERS;
1012     s = sdsnewlen(NULL,sparselen);
1013     p = (uint8_t*)s + HLL_HDR_SIZE;
1014     while(aux) {
1015         int xzero = HLL_SPARSE_XZERO_MAX_LEN;
1016         if (xzero > aux) xzero = aux;
1017         HLL_SPARSE_XZERO_SET(p,xzero);
1018         p += 2;
1019         aux -= xzero;
1020     }
1021     redisAssert((p-(uint8_t*)s) == sparselen);
1022 
1023     /* Create the actual object. */
1024     o = createObject(REDIS_STRING,s);
1025     hdr = o->ptr;
1026     memcpy(hdr->magic,"HYLL",4);
1027     hdr->encoding = HLL_SPARSE;
1028     return o;
1029 }
1030 
1031 /* Check if the object is a String with a valid HLL representation.
1032  * Return REDIS_OK if this is true, otherwise reply to the client
1033  * with an error and return REDIS_ERR. */
1034 int isHLLObjectOrReply(redisClient *c, robj *o) {
1035     struct hllhdr *hdr;
1036 
1037     /* Key exists, check type */
1038     if (checkType(c,o,REDIS_STRING))
1039         return REDIS_ERR; /* Error already sent. */
1040 
1041     if (stringObjectLen(o) < sizeof(*hdr)) goto invalid;
1042     hdr = o->ptr;
1043 
1044     /* Magic should be "HYLL". */
1045     if (hdr->magic[0] != 'H' || hdr->magic[1] != 'Y' ||
1046         hdr->magic[2] != 'L' || hdr->magic[3] != 'L') goto invalid;
1047 
1048     if (hdr->encoding > HLL_MAX_ENCODING) goto invalid;
1049 
1050     /* Dense representation string length should match exactly. */
1051     if (hdr->encoding == HLL_DENSE &&
1052         stringObjectLen(o) != HLL_DENSE_SIZE) goto invalid;
1053 
1054     /* All tests passed. */
1055     return REDIS_OK;
1056 
1057 invalid:
1058     addReplySds(c,
1059         sdsnew("-WRONGTYPE Key is not a valid "
1060                "HyperLogLog string value.\r\n"));
1061     return REDIS_ERR;
1062 }
1063 
1064 /* PFADD var ele ele ele ... ele => :0 or :1 */
1065 void pfaddCommand(redisClient *c) {
1066     robj *o = lookupKeyWrite(c->db,c->argv[1]);
1067     struct hllhdr *hdr;
1068     int updated = 0, j;
1069 
1070     if (o == NULL) {
1071         /* Create the key with a string value of the exact length to
1072          * hold our HLL data structure. sdsnewlen() when NULL is passed
1073          * is guaranteed to return bytes initialized to zero. */
1074         o = createHLLObject();
1075         dbAdd(c->db,c->argv[1],o);
1076         updated++;
1077     } else {
1078         if (isHLLObjectOrReply(c,o) != REDIS_OK) return;
1079         o = dbUnshareStringValue(c->db,c->argv[1],o);
1080     }
1081     /* Perform the low level ADD operation for every element. */
1082     for (j = 2; j < c->argc; j++) {
1083         int retval = hllAdd(o, (unsigned char*)c->argv[j]->ptr,
1084                                sdslen(c->argv[j]->ptr));
1085         switch(retval) {
1086         case 1:
1087             updated++;
1088             break;
1089         case -1:
1090             addReplyError(c,invalid_hll_err);
1091             return;
1092         }
1093     }
1094     hdr = o->ptr;
1095     if (updated) {
1096         signalModifiedKey(c->db,c->argv[1]);
1097         notifyKeyspaceEvent(REDIS_NOTIFY_STRING,"pfadd",c->argv[1],c->db->id);
1098         server.dirty++;
1099         HLL_INVALIDATE_CACHE(hdr);
1100     }
1101     addReply(c, updated ? shared.cone : shared.czero);
1102 }
1103 
1104 /* PFCOUNT var -> approximated cardinality of set. */
1105 void pfcountCommand(redisClient *c) {
1106     robj *o = lookupKeyRead(c->db,c->argv[1]);
1107     struct hllhdr *hdr;
1108     uint64_t card;
1109 
1110     if (o == NULL) {
1111         /* No key? Cardinality is zero since no element was added, otherwise
1112          * we would have a key as HLLADD creates it as a side effect. */
1113         addReply(c,shared.czero);
1114     } else {
1115         if (isHLLObjectOrReply(c,o) != REDIS_OK) return;
1116         o = dbUnshareStringValue(c->db,c->argv[1],o);
1117 
1118         /* Check if the cached cardinality is valid. */
1119         hdr = o->ptr;
1120         if (HLL_VALID_CACHE(hdr)) {
1121             /* Just return the cached value. */
1122             card = (uint64_t)hdr->card[0];
1123             card |= (uint64_t)hdr->card[1] << 8;
1124             card |= (uint64_t)hdr->card[2] << 16;
1125             card |= (uint64_t)hdr->card[3] << 24;
1126             card |= (uint64_t)hdr->card[4] << 32;
1127             card |= (uint64_t)hdr->card[5] << 40;
1128             card |= (uint64_t)hdr->card[6] << 48;
1129             card |= (uint64_t)hdr->card[7] << 56;
1130         } else {
1131             int invalid = 0;
1132             /* Recompute it and update the cached value. */
1133             card = hllCount(hdr,&invalid);
1134             if (invalid) {
1135                 addReplyError(c,invalid_hll_err);
1136                 return;
1137             }
1138             hdr->card[0] = card & 0xff;
1139             hdr->card[1] = (card >> 8) & 0xff;
1140             hdr->card[2] = (card >> 16) & 0xff;
1141             hdr->card[3] = (card >> 24) & 0xff;
1142             hdr->card[4] = (card >> 32) & 0xff;
1143             hdr->card[5] = (card >> 40) & 0xff;
1144             hdr->card[6] = (card >> 48) & 0xff;
1145             hdr->card[7] = (card >> 56) & 0xff;
1146             /* This is not considered a read-only command even if the
1147              * data structure is not modified, since the cached value
1148              * may be modified and given that the HLL is a Redis string
1149              * we need to propagate the change. */
1150             signalModifiedKey(c->db,c->argv[1]);
1151             server.dirty++;
1152         }
1153         addReplyLongLong(c,card);
1154     }
1155 }
1156 
1157 /* PFMERGE dest src1 src2 src3 ... srcN => OK */
1158 void pfmergeCommand(redisClient *c) {
1159     uint8_t max[HLL_REGISTERS];
1160     struct hllhdr *hdr;
1161     int j, i;
1162 
1163     /* Compute an HLL with M[i] = MAX(M[i]_j).
1164      * We we the maximum into the max array of registers. We'll write
1165      * it to the target variable later. */
1166     memset(max,0,sizeof(max));
1167     for (j = 1; j < c->argc; j++) {
1168         /* Check type and size. */
1169         robj *o = lookupKeyRead(c->db,c->argv[j]);
1170         if (o == NULL) continue; /* Assume empty HLL for non existing var. */
1171         if (isHLLObjectOrReply(c,o) != REDIS_OK) return;
1172 
1173         /* Merge with this HLL with our 'max' HHL by setting max[i]
1174          * to MAX(max[i],hll[i]). */
1175         hdr = o->ptr;
1176         if (hdr->encoding == HLL_DENSE) {
1177             uint8_t val;
1178 
1179             for (i = 0; i < HLL_REGISTERS; i++) {
1180                 HLL_DENSE_GET_REGISTER(val,hdr->registers,i);
1181                 if (val > max[i]) max[i] = val;
1182             }
1183         } else {
1184             uint8_t *p = o->ptr, *end = p + sdslen(o->ptr);
1185             long runlen, regval;
1186 
1187             p += HLL_HDR_SIZE;
1188             i = 0;
1189             while(p < end) {
1190                 if (HLL_SPARSE_IS_ZERO(p)) {
1191                     runlen = HLL_SPARSE_ZERO_LEN(p);
1192                     i += runlen;
1193                     p++;
1194                 } else if (HLL_SPARSE_IS_XZERO(p)) {
1195                     runlen = HLL_SPARSE_XZERO_LEN(p);
1196                     i += runlen;
1197                     p += 2;
1198                 } else {
1199                     runlen = HLL_SPARSE_VAL_LEN(p);
1200                     regval = HLL_SPARSE_VAL_VALUE(p);
1201                     while(runlen--) {
1202                         if (regval > max[i]) max[i] = regval;
1203                         i++;
1204                     }
1205                     p++;
1206                 }
1207             }
1208             if (i != HLL_REGISTERS) {
1209                 addReplyError(c,invalid_hll_err);
1210                 return;
1211             }
1212         }
1213     }
1214 
1215     /* Create / unshare the destination key's value if needed. */
1216     robj *o = lookupKeyWrite(c->db,c->argv[1]);
1217     if (o == NULL) {
1218         /* Create the key with a string value of the exact length to
1219          * hold our HLL data structure. sdsnewlen() when NULL is passed
1220          * is guaranteed to return bytes initialized to zero. */
1221         o = createHLLObject();
1222         dbAdd(c->db,c->argv[1],o);
1223     } else {
1224         /* If key exists we are sure it's of the right type/size
1225          * since we checked when merging the different HLLs, so we
1226          * don't check again. */
1227         o = dbUnshareStringValue(c->db,c->argv[1],o);
1228     }
1229 
1230     /* Only support dense objects as destination. */
1231     if (hllSparseToDense(o) == REDIS_ERR) {
1232         addReplyError(c,invalid_hll_err);
1233         return;
1234     }
1235 
1236     /* Write the resulting HLL to the destination HLL registers and
1237      * invalidate the cached value. */
1238     hdr = o->ptr;
1239     for (j = 0; j < HLL_REGISTERS; j++) {
1240         HLL_DENSE_SET_REGISTER(hdr->registers,j,max[j]);
1241     }
1242     HLL_INVALIDATE_CACHE(hdr);
1243 
1244     signalModifiedKey(c->db,c->argv[1]);
1245     /* We generate an HLLADD event for HLLMERGE for semantical simplicity
1246      * since in theory this is a mass-add of elements. */
1247     notifyKeyspaceEvent(REDIS_NOTIFY_STRING,"pfadd",c->argv[1],c->db->id);
1248     server.dirty++;
1249     addReply(c,shared.ok);
1250 }
1251 
1252 /* ========================== Testing / Debugging  ========================== */
1253 
1254 /* PFSELFTEST
1255  * This command performs a self-test of the HLL registers implementation.
1256  * Something that is not easy to test from within the outside. */
1257 #define HLL_TEST_CYCLES 1000
1258 void pfselftestCommand(redisClient *c) {
1259     int j, i;
1260     sds bitcounters = sdsnewlen(NULL,HLL_DENSE_SIZE);
1261     struct hllhdr *hdr = (struct hllhdr*) bitcounters;
1262     uint8_t bytecounters[HLL_REGISTERS];
1263 
1264     /* Test 1: access registers.
1265      * The test is conceived to test that the different counters of our data
1266      * structure are accessible and that setting their values both result in
1267      * the correct value to be retained and not affect adjacent values. */
1268     for (j = 0; j < HLL_TEST_CYCLES; j++) {
1269         /* Set the HLL counters and an array of unsigned byes of the
1270          * same size to the same set of random values. */
1271         for (i = 0; i < HLL_REGISTERS; i++) {
1272             unsigned int r = rand() & HLL_REGISTER_MAX;
1273 
1274             bytecounters[i] = r;
1275             HLL_DENSE_SET_REGISTER(hdr->registers,i,r);
1276         }
1277         /* Check that we are able to retrieve the same values. */
1278         for (i = 0; i < HLL_REGISTERS; i++) {
1279             unsigned int val;
1280 
1281             HLL_DENSE_GET_REGISTER(val,hdr->registers,i);
1282             if (val != bytecounters[i]) {
1283                 addReplyErrorFormat(c,
1284                     "TESTFAILED Register %d should be %d but is %d",
1285                     i, (int) bytecounters[i], (int) val);
1286                 goto cleanup;
1287             }
1288         }
1289     }
1290 
1291     /* Test 2: approximation error.
1292      * The test is adds unique elements and check that the estimated value
1293      * is always reasonable bounds.
1294      *
1295      * We check that the error is smaller than 4 times than the expected
1296      * standard error, to make it very unlikely for the test to fail because
1297      * of a "bad" run. */
1298     memset(hdr->registers,0,HLL_DENSE_SIZE-HLL_HDR_SIZE);
1299     double relerr = 1.04/sqrt(HLL_REGISTERS);
1300     int64_t checkpoint = 1000;
1301     uint64_t seed = (uint64_t)rand() | (uint64_t)rand() << 32;
1302     uint64_t ele;
1303     for (j = 1; j <= 10000000; j++) {
1304         ele = j ^ seed;
1305         hllDenseAdd(hdr->registers,(unsigned char*)&ele,sizeof(ele));
1306         if (j == checkpoint) {
1307             int64_t abserr = checkpoint - (int64_t)hllCount(hdr,NULL);
1308             if (abserr < 0) abserr = -abserr;
1309             if (abserr > (uint64_t)(relerr*4*checkpoint)) {
1310                 addReplyErrorFormat(c,
1311                     "TESTFAILED Too big error. card:%llu abserr:%llu",
1312                     (unsigned long long) checkpoint,
1313                     (unsigned long long) abserr);
1314                 goto cleanup;
1315             }
1316             checkpoint *= 10;
1317         }
1318     }
1319 
1320     /* Success! */
1321     addReply(c,shared.ok);
1322 
1323 cleanup:
1324     sdsfree(bitcounters);
1325 }
1326 
1327 /* PFDEBUG <subcommand> <key> ... args ...
1328  * Different debugging related operations about the HLL implementation. */
1329 void pfdebugCommand(redisClient *c) {
1330     char *cmd = c->argv[1]->ptr;
1331     struct hllhdr *hdr;
1332     robj *o;
1333     int j;
1334 
1335     o = lookupKeyRead(c->db,c->argv[2]);
1336     if (o == NULL) {
1337         addReplyError(c,"The specified key does not exist");
1338         return;
1339     }
1340     if (isHLLObjectOrReply(c,o) != REDIS_OK) return;
1341     o = dbUnshareStringValue(c->db,c->argv[2],o);
1342     hdr = o->ptr;
1343 
1344     /* PFDEBUG GETREG <key> */
1345     if (!strcasecmp(cmd,"getreg")) {
1346         if (c->argc != 3) goto arityerr;
1347 
1348         if (hdr->encoding == HLL_SPARSE) {
1349             if (hllSparseToDense(o) == REDIS_ERR) {
1350                 addReplyError(c,invalid_hll_err);
1351                 return;
1352             }
1353             server.dirty++; /* Force propagation on encoding change. */
1354         }
1355 
1356         hdr = o->ptr;
1357         addReplyMultiBulkLen(c,HLL_REGISTERS);
1358         for (j = 0; j < HLL_REGISTERS; j++) {
1359             uint8_t val;
1360 
1361             HLL_DENSE_GET_REGISTER(val,hdr->registers,j);
1362             addReplyLongLong(c,val);
1363         }
1364     }
1365     /* PFDEBUG DECODE <key> */
1366     else if (!strcasecmp(cmd,"decode")) {
1367         if (c->argc != 3) goto arityerr;
1368 
1369         uint8_t *p = o->ptr, *end = p+sdslen(o->ptr);
1370         sds decoded = sdsempty();
1371 
1372         if (hdr->encoding != HLL_SPARSE) {
1373             addReplyError(c,"HLL encoding is not sparse");
1374             return;
1375         }
1376 
1377         p += HLL_HDR_SIZE;
1378         while(p < end) {
1379             int runlen, regval;
1380 
1381             if (HLL_SPARSE_IS_ZERO(p)) {
1382                 runlen = HLL_SPARSE_ZERO_LEN(p);
1383                 p++;
1384                 decoded = sdscatprintf(decoded,"z:%d ",runlen);
1385             } else if (HLL_SPARSE_IS_XZERO(p)) {
1386                 runlen = HLL_SPARSE_XZERO_LEN(p);
1387                 p += 2;
1388                 decoded = sdscatprintf(decoded,"Z:%d ",runlen);
1389             } else {
1390                 runlen = HLL_SPARSE_VAL_LEN(p);
1391                 regval = HLL_SPARSE_VAL_VALUE(p);
1392                 p++;
1393                 decoded = sdscatprintf(decoded,"v:%d,%d ",regval,runlen);
1394             }
1395         }
1396         decoded = sdstrim(decoded," ");
1397         addReplyBulkCBuffer(c,decoded,sdslen(decoded));
1398         sdsfree(decoded);
1399     }
1400     /* PFDEBUG ENCODING <key> */
1401     else if (!strcasecmp(cmd,"encoding")) {
1402         char *encodingstr[2] = {"dense","sparse"};
1403         if (c->argc != 3) goto arityerr;
1404 
1405         addReplyStatus(c,encodingstr[hdr->encoding]);
1406     } else {
1407         addReplyErrorFormat(c,"Unknown PFDEBUG subcommand '%s'", cmd);
1408     }
1409     return;
1410 
1411 arityerr:
1412     addReplyErrorFormat(c,
1413         "Wrong number of arguments for the '%s' subcommand",cmd);
1414 }
1415 
1416