All files / utils hyperLogLog.js

100% Statements 33/33
100% Branches 16/16
100% Functions 6/6
100% Lines 28/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88                          5x   5x 5x   5x 5x     29x                 4x 2x   2x       17x         258835x 258835x 258835x     258835x 258835x         3x 49152x         29x 29x 29x 475136x 475136x     29x 29x       29x 27x   2x     5x                  
/**
 * Minimal HyperLogLog sketch (Flajolet et al.) for counting distinct ids
 * approximately, in constant memory.
 *
 * Why: "how many distinct users were active this month" cannot be answered by
 * adding up per-day distinct counts (the same user shows up on many days), and
 * an exact answer needs one stored marker per (user, month). A sketch is a
 * fixed 16 KB whatever the number of users, is idempotent to merge (register-wise
 * max, so a retried daily run changes nothing) and its error is ~0.8%. Small
 * cardinalities are corrected with linear counting, so a young platform with a
 * few dozen users gets an exact-looking number.
 */
 
const { createHash } = require('crypto')
 
const PRECISION = 14
const REGISTER_COUNT = 1 << PRECISION
// Bits left of the 64-bit hash once the register index is taken off.
const REMAINING_BITS = 64 - PRECISION
const REMAINING_MASK = (1n << BigInt(REMAINING_BITS)) - 1n
 
function createSketch() {
  return new Uint8Array(REGISTER_COUNT)
}
 
/**
 * Restores a sketch persisted with `serializeSketch`. Anything that is not a
 * full-size register array (a corrupted or foreign item) is rejected rather
 * than silently producing a wrong estimate.
 */
function deserializeSketch(bytes) {
  if (!bytes || bytes.length !== REGISTER_COUNT) {
    throw new Error(`Invalid HyperLogLog sketch: expected ${REGISTER_COUNT} registers`)
  }
  return Uint8Array.from(bytes)
}
 
function serializeSketch(sketch) {
  return Buffer.from(sketch)
}
 
/** Adds one id to the sketch (in place). Ids are strings, e.g. Cognito subs. */
function addToSketch(sketch, id) {
  const hash = createHash('sha256').update(String(id)).digest().readBigUInt64BE(0)
  const index = Number(hash >> BigInt(REMAINING_BITS))
  const remaining = hash & REMAINING_MASK
  // Position of the first 1-bit among the remaining bits (1-based)
  const rank =
    remaining === 0n ? REMAINING_BITS + 1 : REMAINING_BITS - remaining.toString(2).length + 1
  if (rank > sketch[index]) sketch[index] = rank
}
 
/** Folds `other` into `sketch` (in place): the sketch of the union of both id sets. */
function mergeSketch(sketch, other) {
  for (let i = 0; i < REGISTER_COUNT; i++) {
    if (other[i] > sketch[i]) sketch[i] = other[i]
  }
}
 
function estimateCardinality(sketch) {
  let harmonicSum = 0
  let zeroRegisters = 0
  for (let i = 0; i < REGISTER_COUNT; i++) {
    harmonicSum += Math.pow(2, -sketch[i])
    if (sketch[i] === 0) zeroRegisters++
  }
 
  const alpha = 0.7213 / (1 + 1.079 / REGISTER_COUNT)
  const rawEstimate = (alpha * REGISTER_COUNT * REGISTER_COUNT) / harmonicSum
 
  // Small-range correction: the raw estimator is biased while many registers
  // are still empty, linear counting is accurate there.
  if (rawEstimate <= 2.5 * REGISTER_COUNT && zeroRegisters > 0) {
    return Math.round(REGISTER_COUNT * Math.log(REGISTER_COUNT / zeroRegisters))
  }
  return Math.round(rawEstimate)
}
 
module.exports = {
  REGISTER_COUNT,
  createSketch,
  deserializeSketch,
  serializeSketch,
  addToSketch,
  mergeSketch,
  estimateCardinality
}