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