diff --git a/LICENSE b/LICENSE index 2a30395d..3965c5eb 100644 --- a/LICENSE +++ b/LICENSE @@ -296,3 +296,17 @@ APPENDIX B: Additional licenses relevant to this product. Code Locations: * common/include/ceiling_power_of_2.hpp that is adapted from the above. + + ============================================================= + FDLIBM + ============================================================= + Original source code: + Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + Developed at SunSoft, a Sun Microsystems, Inc. business. + + Permission to use, copy, modify, and distribute this software is freely + granted, provided that this notice is preserved. + + Code Locations: + common/include/fdlibm_log.hpp + that is adapted from __ieee754_log in FDLIBM 5.3. diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 8514433b..bb316d09 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -40,6 +40,7 @@ install(FILES include/conditional_back_inserter.hpp include/conditional_forward.hpp include/count_zeros.hpp + include/fdlibm_log.hpp include/inv_pow2_table.hpp include/kolmogorov_smirnov_impl.hpp include/kolmogorov_smirnov.hpp diff --git a/common/include/fdlibm_log.hpp b/common/include/fdlibm_log.hpp new file mode 100644 index 00000000..86654806 --- /dev/null +++ b/common/include/fdlibm_log.hpp @@ -0,0 +1,101 @@ +// fdlibm __ieee754_log, used by Java's StrictMath.log (and by Math.log on most JVMs). +// Derived from FDLIBM 5.3, Copyright (C) 1993 by Sun Microsystems, Inc. +// "Permission to use, copy, modify, and distribute this software is freely granted, +// provided that this notice is preserved." +#ifndef FDLIBM_LOG_HPP +#define FDLIBM_LOG_HPP +#include +#include +#include + +namespace fdlibm { + +inline int32_t hi_word(double x){ uint64_t u; std::memcpy(&u,&x,8); return (int32_t)(uint32_t)(u>>32); } +inline uint32_t lo_word(double x){ uint64_t u; std::memcpy(&u,&x,8); return (uint32_t)u; } +inline void set_hi_word(double& x, uint32_t hi){ uint64_t u; std::memcpy(&u,&x,8); + u = (u & 0x00000000ffffffffULL) | ((uint64_t)hi<<32); std::memcpy(&x,&u,8); } + +// Forces a value to be rounded to a double before it is used again. fdlibm needs strict +// IEEE-754 evaluation: a fused multiply-add anywhere in the polynomial below changes the +// result. Pragmas are overridden by an explicit -ffp-contract=fast, so use a volatile +// round-trip, which the standard requires the compiler to honour. +inline double rnd(double v) { volatile double t = v; return t; } + +inline double log(double x) { +// fdlibm depends on strict IEEE-754 evaluation: a fused multiply-add would change the result +// of the polynomial evaluation below, so contraction must be off for this function. +#if defined(__clang__) +#pragma clang fp contract(off) +#endif + static const double + ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */ + ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */ + two54 = 1.80143985094819840000e+16, /* 43500000 00000000 */ + Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ + Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ + Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ + Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ + Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ + Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ + Lg7 = 1.479819860511658591e-01, /* 3FC2F112 DF3E5244 */ + zero = 0.0; + + double hfsq,f,s,z,R,w,t1,t2,dk; + int32_t k,hx,i,j; + uint32_t lx; + + hx = hi_word(x); + lx = lo_word(x); + + k = 0; + if (hx < 0x00100000) { /* x < 2**-1022 */ + // fdlibm writes these as -two54/zero and (x-x)/zero, which also raise the divide-by-zero + // and invalid flags. MSVC rejects a compile-time division by a zero constant (C2124), so + // return the same values directly. The estimators never call log() with these inputs. + if (((hx & 0x7fffffff) | lx) == 0) { /* log(+-0) = -inf */ + return -std::numeric_limits::infinity(); + } + if (hx < 0) { /* log(-#) = NaN */ + return std::numeric_limits::quiet_NaN(); + } + k -= 54; x *= two54; /* subnormal: scale up */ + hx = hi_word(x); + } + if (hx >= 0x7ff00000) { return x+x; } + k += (hx>>20) - 1023; + hx &= 0x000fffff; + i = (hx + 0x95f64) & 0x100000; + set_hi_word(x, (uint32_t)(hx | (i ^ 0x3ff00000))); /* normalize x or x/2 */ + k += (i>>20); + f = x - 1.0; + if ((0x000fffff & (2+hx)) < 3) { /* |f| < 2**-20 */ + if (f == zero) { + if (k == 0) { return zero; } + dk = (double)k; return rnd(dk*ln2_hi) + rnd(dk*ln2_lo); + } + R = rnd(rnd(f*f)*rnd(0.5 - rnd(0.33333333333333333*f))); + if (k == 0) { return f-R; } + dk = (double)k; return rnd(dk*ln2_hi) - (rnd(R - rnd(dk*ln2_lo)) - f); + } + s = f/(2.0+f); + dk = (double)k; + z = s*s; + i = hx - 0x6147a; + w = z*z; + j = 0x6b851 - hx; + t1 = rnd(w*rnd(Lg2 + rnd(w*rnd(Lg4 + rnd(w*Lg6))))); + t2 = rnd(z*rnd(Lg1 + rnd(w*rnd(Lg3 + rnd(w*rnd(Lg5 + rnd(w*Lg7))))))); + i |= j; + R = t2 + t1; + if (i > 0) { + hfsq = rnd(0.5*f)*f; + if (k == 0) { return f - rnd(hfsq - rnd(s*(hfsq+R))); } + return rnd(dk*ln2_hi) - (rnd(hfsq - rnd(rnd(s*(hfsq+R)) + rnd(dk*ln2_lo))) - f); + } else { + if (k == 0) { return f - rnd(s*(f-R)); } + return rnd(dk*ln2_hi) - (rnd(rnd(s*(f-R)) - rnd(dk*ln2_lo)) - f); + } +} + +} // namespace fdlibm +#endif diff --git a/hll/include/CouponList-internal.hpp b/hll/include/CouponList-internal.hpp index 5b067a59..de48239f 100644 --- a/hll/include/CouponList-internal.hpp +++ b/hll/include/CouponList-internal.hpp @@ -33,7 +33,7 @@ namespace datasketches { template CouponList::CouponList(uint8_t lgConfigK, target_hll_type tgtHllType, hll_mode mode, const A& allocator): -HllSketchImpl(lgConfigK, tgtHllType, mode, false), +HllSketchImpl(lgConfigK, tgtHllType, mode), couponCount_(0), oooFlag_(false), coupons_(1ULL << (mode == hll_mode::LIST ? hll_constants::LG_INIT_LIST_SIZE : hll_constants::LG_INIT_SET_SIZE), 0, allocator) @@ -41,7 +41,7 @@ coupons_(1ULL << (mode == hll_mode::LIST ? hll_constants::LG_INIT_LIST_SIZE : hl template CouponList::CouponList(const CouponList& that, const target_hll_type tgtHllType): -HllSketchImpl(that.lgConfigK_, tgtHllType, that.mode_, false), +HllSketchImpl(that.lgConfigK_, tgtHllType, that.mode_), couponCount_(that.couponCount_), oooFlag_(that.oooFlag_), coupons_(that.coupons_) diff --git a/hll/include/HarmonicNumbers-internal.hpp b/hll/include/HarmonicNumbers-internal.hpp index 4ac1e726..b79e0988 100644 --- a/hll/include/HarmonicNumbers-internal.hpp +++ b/hll/include/HarmonicNumbers-internal.hpp @@ -21,6 +21,7 @@ #define _HARMONICNUMBERS_INTERNAL_HPP_ #include "HarmonicNumbers.hpp" +#include "fdlibm_log.hpp" #include @@ -70,7 +71,7 @@ double HarmonicNumbers::harmonicNumber(const uint64_t x_i) { } else { double x = static_cast(x_i); double invSq = 1.0 / (x * x); - double sum = log(x) + EULER_MASCHERONI_CONSTANT + (1.0 / (2.0 * x)); + double sum = fdlibm::log(x) + EULER_MASCHERONI_CONSTANT + (1.0 / (2.0 * x)); /* note: the number of terms included from this series expansion is appropriate for the size of the exact table (25) and the precision of doubles */ double pow = invSq; // now n^-2 diff --git a/hll/include/Hll4Array-internal.hpp b/hll/include/Hll4Array-internal.hpp index 082f168f..adfed74a 100644 --- a/hll/include/Hll4Array-internal.hpp +++ b/hll/include/Hll4Array-internal.hpp @@ -30,8 +30,8 @@ namespace datasketches { template -Hll4Array::Hll4Array(uint8_t lgConfigK, bool startFullSize, const A& allocator): -HllArray(lgConfigK, target_hll_type::HLL_4, startFullSize, allocator), +Hll4Array::Hll4Array(uint8_t lgConfigK, const A& allocator): +HllArray(lgConfigK, target_hll_type::HLL_4, allocator), auxHashMap_(nullptr) { const uint32_t numBytes = this->hll4ArrBytes(lgConfigK); @@ -53,7 +53,7 @@ Hll4Array::Hll4Array(const Hll4Array& that) : template Hll4Array::Hll4Array(const HllArray& other) : - HllArray(other.getLgConfigK(), target_hll_type::HLL_4, other.isStartFullSize(), other.getAllocator()), + HllArray(other.getLgConfigK(), target_hll_type::HLL_4, other.getAllocator()), auxHashMap_(nullptr) { const int numBytes = this->hll4ArrBytes(this->lgConfigK_); diff --git a/hll/include/Hll4Array.hpp b/hll/include/Hll4Array.hpp index 0e3e2cd8..7edfb051 100644 --- a/hll/include/Hll4Array.hpp +++ b/hll/include/Hll4Array.hpp @@ -28,7 +28,7 @@ namespace datasketches { template class Hll4Array final : public HllArray { public: - explicit Hll4Array(uint8_t lgConfigK, bool startFullSize, const A& allocator); + explicit Hll4Array(uint8_t lgConfigK, const A& allocator); explicit Hll4Array(const Hll4Array& that); explicit Hll4Array(const HllArray& that); diff --git a/hll/include/Hll6Array-internal.hpp b/hll/include/Hll6Array-internal.hpp index b8b4d6bb..34c72438 100644 --- a/hll/include/Hll6Array-internal.hpp +++ b/hll/include/Hll6Array-internal.hpp @@ -27,8 +27,8 @@ namespace datasketches { template -Hll6Array::Hll6Array(uint8_t lgConfigK, bool startFullSize, const A& allocator): -HllArray(lgConfigK, target_hll_type::HLL_6, startFullSize, allocator) +Hll6Array::Hll6Array(uint8_t lgConfigK, const A& allocator): +HllArray(lgConfigK, target_hll_type::HLL_6, allocator) { const int numBytes = this->hll6ArrBytes(lgConfigK); this->hllByteArr_.resize(numBytes, 0); @@ -36,7 +36,7 @@ HllArray(lgConfigK, target_hll_type::HLL_6, startFullSize, allocator) template Hll6Array::Hll6Array(const HllArray& other) : - HllArray(other.getLgConfigK(), target_hll_type::HLL_6, other.isStartFullSize(), other.getAllocator()) + HllArray(other.getLgConfigK(), target_hll_type::HLL_6, other.getAllocator()) { const int numBytes = this->hll6ArrBytes(this->lgConfigK_); this->hllByteArr_.resize(numBytes, 0); diff --git a/hll/include/Hll6Array.hpp b/hll/include/Hll6Array.hpp index 4921976d..82286d87 100644 --- a/hll/include/Hll6Array.hpp +++ b/hll/include/Hll6Array.hpp @@ -30,7 +30,7 @@ class Hll6Iterator; template class Hll6Array final : public HllArray { public: - Hll6Array(uint8_t lgConfigK, bool startFullSize, const A& allocator); + Hll6Array(uint8_t lgConfigK, const A& allocator); explicit Hll6Array(const HllArray& that); virtual ~Hll6Array() = default; diff --git a/hll/include/Hll8Array-internal.hpp b/hll/include/Hll8Array-internal.hpp index 14a2bbd7..5e4239ec 100644 --- a/hll/include/Hll8Array-internal.hpp +++ b/hll/include/Hll8Array-internal.hpp @@ -25,8 +25,8 @@ namespace datasketches { template -Hll8Array::Hll8Array(uint8_t lgConfigK, bool startFullSize, const A& allocator): -HllArray(lgConfigK, target_hll_type::HLL_8, startFullSize, allocator) +Hll8Array::Hll8Array(uint8_t lgConfigK, const A& allocator): +HllArray(lgConfigK, target_hll_type::HLL_8, allocator) { const int numBytes = this->hll8ArrBytes(lgConfigK); this->hllByteArr_.resize(numBytes, 0); @@ -34,7 +34,7 @@ HllArray(lgConfigK, target_hll_type::HLL_8, startFullSize, allocator) template Hll8Array::Hll8Array(const HllArray& other): - HllArray(other.getLgConfigK(), target_hll_type::HLL_8, other.isStartFullSize(), other.getAllocator()) + HllArray(other.getLgConfigK(), target_hll_type::HLL_8, other.getAllocator()) { const int numBytes = this->hll8ArrBytes(this->lgConfigK_); this->hllByteArr_.resize(numBytes, 0); diff --git a/hll/include/Hll8Array.hpp b/hll/include/Hll8Array.hpp index 655baf9f..1630be4c 100644 --- a/hll/include/Hll8Array.hpp +++ b/hll/include/Hll8Array.hpp @@ -30,7 +30,7 @@ class Hll8Iterator; template class Hll8Array final : public HllArray { public: - Hll8Array(uint8_t lgConfigK, bool startFullSize, const A& allocator); + Hll8Array(uint8_t lgConfigK, const A& allocator); explicit Hll8Array(const HllArray& that); virtual ~Hll8Array() = default; diff --git a/hll/include/HllArray-internal.hpp b/hll/include/HllArray-internal.hpp index 92dbe8b2..1da49cab 100644 --- a/hll/include/HllArray-internal.hpp +++ b/hll/include/HllArray-internal.hpp @@ -21,6 +21,7 @@ #define _HLLARRAY_INTERNAL_HPP_ #include "HllArray.hpp" +#include "fdlibm_log.hpp" #include "HllUtil.hpp" #include "HarmonicNumbers.hpp" #include "CubicInterpolation.hpp" @@ -35,8 +36,8 @@ namespace datasketches { template -HllArray::HllArray(uint8_t lgConfigK, target_hll_type tgtHllType, bool startFullSize, const A& allocator): -HllSketchImpl(lgConfigK, tgtHllType, hll_mode::HLL, startFullSize), +HllArray::HllArray(uint8_t lgConfigK, target_hll_type tgtHllType, const A& allocator): +HllSketchImpl(lgConfigK, tgtHllType, hll_mode::HLL), hipAccum_(0.0), kxq0_(1 << lgConfigK), kxq1_(0.0), @@ -49,7 +50,7 @@ rebuild_kxq_curmin_(false) template HllArray::HllArray(const HllArray& other, target_hll_type tgtHllType) : - HllSketchImpl(other.getLgConfigK(), tgtHllType, hll_mode::HLL, other.isStartFullSize()), + HllSketchImpl(other.getLgConfigK(), tgtHllType, hll_mode::HLL), // remaining fields are initialized to empty sketch defaults // and left to subclass constructor to populate hipAccum_(0.0), @@ -109,7 +110,6 @@ HllArray* HllArray::newHll(const void* bytes, size_t len, const A& allocat const target_hll_type tgtHllType = HllSketchImpl::extractTgtHllType(data[hll_constants::MODE_BYTE]); const bool oooFlag = ((data[hll_constants::FLAGS_BYTE] & hll_constants::OUT_OF_ORDER_FLAG_MASK) ? true : false); const bool comapctFlag = ((data[hll_constants::FLAGS_BYTE] & hll_constants::COMPACT_FLAG_MASK) ? true : false); - const bool startFullSizeFlag = ((data[hll_constants::FLAGS_BYTE] & hll_constants::FULL_SIZE_FLAG_MASK) ? true : false); const uint8_t lgK = data[hll_constants::LG_K_BYTE]; const uint8_t curMin = data[hll_constants::HLL_CUR_MIN_BYTE]; @@ -139,7 +139,7 @@ HllArray* HllArray::newHll(const void* bytes, size_t len, const A& allocat aux_ptr = aux_hash_map_ptr(auxHashMap, auxHashMap->make_deleter()); } - HllArray* sketch = HllSketchImplFactory::newHll(lgK, tgtHllType, startFullSizeFlag, allocator); + HllArray* sketch = HllSketchImplFactory::newHll(lgK, tgtHllType, allocator); sketch->putCurMin(curMin); sketch->putOutOfOrderFlag(oooFlag); if (!oooFlag) { sketch->putHipAccum(hip); } @@ -180,12 +180,11 @@ HllArray* HllArray::newHll(std::istream& is, const A& allocator) { const target_hll_type tgtHllType = HllSketchImpl::extractTgtHllType(listHeader[hll_constants::MODE_BYTE]); const bool oooFlag = ((listHeader[hll_constants::FLAGS_BYTE] & hll_constants::OUT_OF_ORDER_FLAG_MASK) ? true : false); const bool comapctFlag = ((listHeader[hll_constants::FLAGS_BYTE] & hll_constants::COMPACT_FLAG_MASK) ? true : false); - const bool startFullSizeFlag = ((listHeader[hll_constants::FLAGS_BYTE] & hll_constants::FULL_SIZE_FLAG_MASK) ? true : false); const uint8_t lgK = listHeader[hll_constants::LG_K_BYTE]; const uint8_t curMin = listHeader[hll_constants::HLL_CUR_MIN_BYTE]; - HllArray* sketch = HllSketchImplFactory::newHll(lgK, tgtHllType, startFullSizeFlag, allocator); + HllArray* sketch = HllSketchImplFactory::newHll(lgK, tgtHllType, allocator); typedef std::unique_ptr, std::function*)>> hll_array_ptr; hll_array_ptr sketch_ptr(sketch, sketch->get_deleter()); sketch->putCurMin(curMin); @@ -570,7 +569,7 @@ double HllArray::getHllBitMapEstimate() const { //This will eventually go away. if (numUnhitBuckets == 0) { - return configK * log(configK / 0.5); + return configK * fdlibm::log(configK / 0.5); } const uint32_t numHitBuckets = configK - numUnhitBuckets; @@ -603,34 +602,37 @@ bool HllArray::isRebuildKxqCurminFlag() const { template void HllArray::check_rebuild_kxq_cur_min() { if (!rebuild_kxq_curmin_) { return; } + // the deferred rebuild is only ever set on an HLL_8 union gadget. Guarding here also keeps + // this from ever rewriting curMin_ on an HLL_4 array, whose nibbles are stored relative to it. + if (this->getCurMode() != hll_mode::HLL || this->getTgtHllType() != target_hll_type::HLL_8) { + rebuild_kxq_curmin_ = false; + return; + } - uint8_t cur_min = 64; - uint32_t num_at_cur_min = 0; + uint32_t num_zeros = 0; double kxq0 = 1 << this->lgConfigK_; double kxq1 = 0; - auto it = this->begin(true); // want all points to adjust cur_min + auto it = this->begin(true); // want all slots, including the empty ones const auto end = this->end(); while (it != end) { uint8_t v = HllUtil::getValue(*it); if (v > 0) { if (v < 32) { kxq0 += INVERSE_POWERS_OF_2[v] - 1.0; } else { kxq1 += INVERSE_POWERS_OF_2[v] - 1.0; } - } - if (v > cur_min) { ++it; continue; } - if (v < cur_min) { - cur_min = v; - num_at_cur_min = 1; } else { - ++num_at_cur_min; - } + ++num_zeros; + } ++it; } kxq0_ = kxq0; kxq1_ = kxq1; - curMin_ = cur_min; - numAtCurMin_ = num_at_cur_min; + // HLL_8 convention: curMin is always 0 and numAtCurMin is the number of zero registers. + // That is the representation the incremental update path maintains, so the rebuilt state is + // indistinguishable from it and the timing of this rebuild is not observable in the image. + curMin_ = 0; + numAtCurMin_ = num_zeros; rebuild_kxq_curmin_ = false; // HipAccum is not affected diff --git a/hll/include/HllArray.hpp b/hll/include/HllArray.hpp index 471a1402..87994cb6 100644 --- a/hll/include/HllArray.hpp +++ b/hll/include/HllArray.hpp @@ -33,7 +33,7 @@ class HllArray : public HllSketchImpl { public: using vector_bytes = std::vector::template rebind_alloc>; - HllArray(uint8_t lgConfigK, target_hll_type tgtHllType, bool startFullSize, const A& allocator); + HllArray(uint8_t lgConfigK, target_hll_type tgtHllType, const A& allocator); explicit HllArray(const HllArray& other, target_hll_type tgtHllType); static HllArray* newHll(const void* bytes, size_t len, const A& allocator); diff --git a/hll/include/HllSketch-internal.hpp b/hll/include/HllSketch-internal.hpp index e60f08d0..bbd5d29d 100644 --- a/hll/include/HllSketch-internal.hpp +++ b/hll/include/HllSketch-internal.hpp @@ -45,7 +45,7 @@ template hll_sketch_alloc::hll_sketch_alloc(uint8_t lg_config_k, target_hll_type tgt_type, bool start_full_size, const A& allocator) { HllUtil::checkLgK(lg_config_k); if (start_full_size) { - sketch_impl = HllSketchImplFactory::newHll(lg_config_k, tgt_type, start_full_size, allocator); + sketch_impl = HllSketchImplFactory::newHll(lg_config_k, tgt_type, allocator); } else { typedef typename std::allocator_traits::template rebind_alloc> clAlloc; sketch_impl = new (clAlloc(allocator).allocate(1)) CouponList(lg_config_k, tgt_type, hll_mode::LIST, allocator); @@ -107,10 +107,8 @@ hll_sketch_alloc& hll_sketch_alloc::operator=(hll_sketch_alloc&& other) } template -void hll_sketch_alloc::reset() { - // TODO: need to allow starting from a full-sized sketch - // (either here or in other implementation) - sketch_impl = sketch_impl->reset(); +void hll_sketch_alloc::reset(bool full_size) { + sketch_impl = sketch_impl->reset(full_size); } template diff --git a/hll/include/HllSketchImpl-internal.hpp b/hll/include/HllSketchImpl-internal.hpp index 6b11e7ce..c4dd83cc 100644 --- a/hll/include/HllSketchImpl-internal.hpp +++ b/hll/include/HllSketchImpl-internal.hpp @@ -29,11 +29,10 @@ namespace datasketches { template HllSketchImpl::HllSketchImpl(uint8_t lgConfigK, target_hll_type tgtHllType, - hll_mode mode, bool startFullSize) + hll_mode mode) : lgConfigK_(lgConfigK), tgtHllType_(tgtHllType), - mode_(mode), - startFullSize_(startFullSize) + mode_(mode) { } @@ -75,7 +74,7 @@ uint8_t HllSketchImpl::makeFlagsByte(bool compact) const { flags |= (isEmpty() ? hll_constants::EMPTY_FLAG_MASK : 0); flags |= (compact ? hll_constants::COMPACT_FLAG_MASK : 0); flags |= (isOutOfOrderFlag() ? hll_constants::OUT_OF_ORDER_FLAG_MASK : 0); - flags |= (startFullSize_ ? hll_constants::FULL_SIZE_FLAG_MASK : 0); + // bit 32 is reserved: see RESERVED_FLAG_MASK_32 in HllUtil.hpp return flags; } @@ -122,8 +121,8 @@ uint8_t HllSketchImpl::makeModeByte() const { } template -HllSketchImpl* HllSketchImpl::reset() { - return HllSketchImplFactory::reset(this, startFullSize_); +HllSketchImpl* HllSketchImpl::reset(bool full_size) { + return HllSketchImplFactory::reset(this, full_size); } template @@ -141,11 +140,6 @@ hll_mode HllSketchImpl::getCurMode() const { return mode_; } -template -bool HllSketchImpl::isStartFullSize() const { - return startFullSize_; -} - } #endif // _HLLSKETCHIMPL_INTERNAL_HPP_ diff --git a/hll/include/HllSketchImpl.hpp b/hll/include/HllSketchImpl.hpp index 80667199..bdd4407b 100644 --- a/hll/include/HllSketchImpl.hpp +++ b/hll/include/HllSketchImpl.hpp @@ -32,7 +32,7 @@ class HllSketchImpl { public: using vector_bytes = std::vector::template rebind_alloc>; - HllSketchImpl(uint8_t lgConfigK, target_hll_type tgtHllType, hll_mode mode, bool startFullSize); + HllSketchImpl(uint8_t lgConfigK, target_hll_type tgtHllType, hll_mode mode); virtual ~HllSketchImpl(); virtual void serialize(std::ostream& os, bool compact) const = 0; @@ -40,7 +40,7 @@ class HllSketchImpl { virtual HllSketchImpl* copy() const = 0; virtual HllSketchImpl* copyAs(target_hll_type tgtHllType) const = 0; - HllSketchImpl* reset(); + HllSketchImpl* reset(bool full_size); virtual std::function*)> get_deleter() const = 0; @@ -69,7 +69,6 @@ class HllSketchImpl { virtual bool isOutOfOrderFlag() const = 0; virtual void putOutOfOrderFlag(bool oooFlag) = 0; virtual A getAllocator() const = 0; - bool isStartFullSize() const; protected: static target_hll_type extractTgtHllType(uint8_t modeByte); @@ -80,7 +79,6 @@ class HllSketchImpl { const uint8_t lgConfigK_; const target_hll_type tgtHllType_; const hll_mode mode_; - const bool startFullSize_; }; } diff --git a/hll/include/HllSketchImplFactory.hpp b/hll/include/HllSketchImplFactory.hpp index aa2eafa8..2142b535 100644 --- a/hll/include/HllSketchImplFactory.hpp +++ b/hll/include/HllSketchImplFactory.hpp @@ -41,10 +41,11 @@ class HllSketchImplFactory final { static CouponHashSet* promoteListToSet(const CouponList& list); static HllArray* promoteListOrSetToHll(const CouponList& list); - static HllArray* newHll(uint8_t lgConfigK, target_hll_type tgtHllType, bool startFullSize, const A& allocator); + static HllArray* newHll(uint8_t lgConfigK, target_hll_type tgtHllType, const A& allocator); // resets the input impl, deleting the input pointer and returning a new pointer - static HllSketchImpl* reset(HllSketchImpl* impl, bool startFullSize); + // full_size selects the state to reset to: an empty HLL array, or LIST (coupon) mode + static HllSketchImpl* reset(HllSketchImpl* impl, bool full_size); static Hll4Array* convertToHll4(const HllArray& srcHllArr); static Hll6Array* convertToHll6(const HllArray& srcHllArr); @@ -63,7 +64,7 @@ CouponHashSet* HllSketchImplFactory::promoteListToSet(const CouponList& template HllArray* HllSketchImplFactory::promoteListOrSetToHll(const CouponList& src) { - HllArray* tgtHllArr = HllSketchImplFactory::newHll(src.getLgConfigK(), src.getTgtHllType(), false, src.getAllocator()); + HllArray* tgtHllArr = HllSketchImplFactory::newHll(src.getLgConfigK(), src.getTgtHllType(), src.getAllocator()); tgtHllArr->putKxQ0(1 << src.getLgConfigK()); for (const auto coupon: src) { tgtHllArr->couponUpdate(coupon); @@ -105,25 +106,25 @@ HllSketchImpl* HllSketchImplFactory::deserialize(const void* bytes, size_t } template -HllArray* HllSketchImplFactory::newHll(uint8_t lgConfigK, target_hll_type tgtHllType, bool startFullSize, const A& allocator) { +HllArray* HllSketchImplFactory::newHll(uint8_t lgConfigK, target_hll_type tgtHllType, const A& allocator) { switch (tgtHllType) { case HLL_8: using Hll8Alloc = typename std::allocator_traits::template rebind_alloc>; - return new (Hll8Alloc(allocator).allocate(1)) Hll8Array(lgConfigK, startFullSize, allocator); + return new (Hll8Alloc(allocator).allocate(1)) Hll8Array(lgConfigK, allocator); case HLL_6: using Hll6Alloc = typename std::allocator_traits::template rebind_alloc>; - return new (Hll6Alloc(allocator).allocate(1)) Hll6Array(lgConfigK, startFullSize, allocator); + return new (Hll6Alloc(allocator).allocate(1)) Hll6Array(lgConfigK, allocator); case HLL_4: using Hll4Alloc = typename std::allocator_traits::template rebind_alloc>; - return new (Hll4Alloc(allocator).allocate(1)) Hll4Array(lgConfigK, startFullSize, allocator); + return new (Hll4Alloc(allocator).allocate(1)) Hll4Array(lgConfigK, allocator); } throw std::logic_error("Invalid target_hll_type"); } template -HllSketchImpl* HllSketchImplFactory::reset(HllSketchImpl* impl, bool startFullSize) { - if (startFullSize) { - HllArray* hll = newHll(impl->getLgConfigK(), impl->getTgtHllType(), startFullSize, impl->getAllocator()); +HllSketchImpl* HllSketchImplFactory::reset(HllSketchImpl* impl, bool full_size) { + if (full_size) { + HllArray* hll = newHll(impl->getLgConfigK(), impl->getTgtHllType(), impl->getAllocator()); impl->get_deleter()(impl); return hll; } else { diff --git a/hll/include/HllUnion-internal.hpp b/hll/include/HllUnion-internal.hpp index a469a2d0..d83340de 100644 --- a/hll/include/HllUnion-internal.hpp +++ b/hll/include/HllUnion-internal.hpp @@ -171,7 +171,9 @@ uint8_t hll_union_alloc::get_lg_config_k() const { template void hll_union_alloc::reset() { - gadget_.reset(); + // always coupon collection mode: the gadget is an internal detail and must not + // inherit a full-size state from whatever sketches happen to have been unioned in + gadget_.reset(false); } template @@ -216,7 +218,7 @@ HllSketchImpl* hll_union_alloc::copy_or_downsample(const HllSketchImpl* return src->copyAs(HLL_8); } typedef typename std::allocator_traits::template rebind_alloc> hll8Alloc; - Hll8Array* tgtHllArr = new (hll8Alloc(src->getAllocator()).allocate(1)) Hll8Array(tgt_lg_k, false, src->getAllocator()); + Hll8Array* tgtHllArr = new (hll8Alloc(src->getAllocator()).allocate(1)) Hll8Array(tgt_lg_k, src->getAllocator()); tgtHllArr->mergeHll(*src); //both of these are required for isomorphism tgtHllArr->putHipAccum(src->getHipAccum()); diff --git a/hll/include/HllUtil.hpp b/hll/include/HllUtil.hpp index b81c014a..1e207d73 100644 --- a/hll/include/HllUtil.hpp +++ b/hll/include/HllUtil.hpp @@ -43,7 +43,12 @@ static const uint8_t FAMILY_ID = 7; static const uint8_t EMPTY_FLAG_MASK = 4; static const uint8_t COMPACT_FLAG_MASK = 8; static const uint8_t OUT_OF_ORDER_FLAG_MASK = 16; -static const uint8_t FULL_SIZE_FLAG_MASK = 32; +// Bit 32 is RESERVED and must not be written or interpreted. +// It was formerly FULL_SIZE_FLAG_MASK here, while datasketches-java uses the same bit as +// REBUILD_CURMIN_NUM_KXQ_MASK for its union gadget. The two meanings collided across +// implementations, so this side no longer writes or reads it. Do not reuse: bits 64 and 128 +// are free. +static const uint8_t RESERVED_FLAG_MASK_32 = 32; static const uint32_t PREAMBLE_INTS_BYTE = 0; static const uint32_t SER_VER_BYTE = 1; @@ -82,8 +87,8 @@ static const uint32_t EMPTY = 0; static const uint8_t MIN_LOG_K = 4; static const uint8_t MAX_LOG_K = 21; -static const double HLL_HIP_RSE_FACTOR = 0.8325546; // sqrt(ln(2)) -static const double HLL_NON_HIP_RSE_FACTOR = 1.03896; // sqrt((3 * ln(2)) - 1) +static const double HLL_HIP_RSE_FACTOR = 0.8325546111576977; // sqrt(ln(2)) +static const double HLL_NON_HIP_RSE_FACTOR = 1.0389617614136892; // sqrt((3 * ln(2)) - 1) static const double COUPON_RSE_FACTOR = 0.409; // at transition point not the asymptote static const double COUPON_RSE = COUPON_RSE_FACTOR / (1 << 13); diff --git a/hll/include/hll.hpp b/hll/include/hll.hpp index 5fc49629..9950eec0 100644 --- a/hll/include/hll.hpp +++ b/hll/include/hll.hpp @@ -120,7 +120,10 @@ class hll_sketch_alloc final { * @param tgt_type The HLL mode to use, if/when the sketch reaches that state * @param start_full_size Indicates whether to start in HLL mode, * keeping memory use constant (if HLL_6 or HLL_8) at the cost of - * starting out using much more memory + * starting out using much more memory. This is a property of this + * constructor call only: it is not retained by the sketch and is not + * serialized, so reset() returns to coupon collection mode unless + * reset(true) is used. * @param allocator instance of an Allocator */ explicit hll_sketch_alloc(uint8_t lg_config_k, target_hll_type tgt_type = HLL_4, bool start_full_size = false, const A& allocator = A()); @@ -177,10 +180,14 @@ class hll_sketch_alloc final { hll_sketch_alloc& operator=(hll_sketch_alloc&& other); /** - * Resets the sketch to an empty state in coupon collection mode. + * Resets the sketch to an empty state. * Does not re-use existing internal objects. + * @param full_size if true, reset to an empty full-size HLL array, as + * the start_full_size constructor argument does; otherwise reset to + * coupon collection mode. Full size is not remembered across a reset + * or a serialization round trip, so it must be requested each time. */ - void reset(); + void reset(bool full_size = false); // This is a convenience alias for users // The type returned by the following serialize method diff --git a/hll/test/CMakeLists.txt b/hll/test/CMakeLists.txt index efdc5215..f63d1a50 100644 --- a/hll/test/CMakeLists.txt +++ b/hll/test/CMakeLists.txt @@ -42,6 +42,8 @@ target_sources(hll_test CouponListTest.cpp CrossCountingTest.cpp HllArrayTest.cpp + HllFullSizeTest.cpp + HllKxqRebuildTest.cpp HllSketchTest.cpp HllUnionTest.cpp TablesTest.cpp diff --git a/hll/test/HllFullSizeTest.cpp b/hll/test/HllFullSizeTest.cpp new file mode 100644 index 00000000..360f07f2 --- /dev/null +++ b/hll/test/HllFullSizeTest.cpp @@ -0,0 +1,137 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include + +#include "hll.hpp" + +namespace datasketches { + +// preamble byte 0 is preInts, which identifies the current mode +static const uint8_t LIST_PREINTS = 2; +static const uint8_t HLL_PREINTS = 10; +// preamble byte 5 is the flags byte; bit 32 is reserved and must never be written +static const size_t FLAGS_BYTE = 5; +static const uint8_t RESERVED_BIT_32 = 32; + +static uint8_t preints_of(const hll_sketch& sk) { + return sk.serialize_compact()[0]; +} + +static hll_sketch make(uint8_t lg_k, target_hll_type type, bool full_size, uint64_t n) { + hll_sketch sk(lg_k, type, full_size); + for (uint64_t i = 0; i < n; ++i) sk.update(i); + return sk; +} + +TEST_CASE("hll full size: reserved bit 32 is never written", "[hll_full_size]") { + for (auto type: {HLL_4, HLL_6, HLL_8}) { + for (bool full_size: {false, true}) { + for (uint64_t n: {uint64_t(0), uint64_t(5), uint64_t(5000)}) { + const hll_sketch sk = make(8, type, full_size, n); + REQUIRE((sk.serialize_compact()[FLAGS_BYTE] & RESERVED_BIT_32) == 0); + REQUIRE((sk.serialize_updatable()[FLAGS_BYTE] & RESERVED_BIT_32) == 0); + } + } + } +} + +TEST_CASE("hll full size: start_full_size starts in HLL mode", "[hll_full_size]") { + REQUIRE(preints_of(make(8, HLL_8, true, 0)) == HLL_PREINTS); + REQUIRE(preints_of(make(8, HLL_8, false, 0)) == LIST_PREINTS); +} + +TEST_CASE("hll full size: reset takes the mode as an argument", "[hll_full_size]") { + for (auto type: {HLL_4, HLL_6, HLL_8}) { + // full size is not remembered: a plain reset() returns to coupon collection mode + hll_sketch sk = make(8, type, true, 5000); + sk.reset(); + REQUIRE(sk.is_empty()); + REQUIRE(sk.get_estimate() == 0.0); + REQUIRE(preints_of(sk) == LIST_PREINTS); + + // ...and must be asked for explicitly + hll_sketch sk2 = make(8, type, false, 5000); + sk2.reset(true); + REQUIRE(sk2.is_empty()); + REQUIRE(sk2.get_estimate() == 0.0); + REQUIRE(preints_of(sk2) == HLL_PREINTS); + REQUIRE(sk2.get_lg_config_k() == 8); + REQUIRE(sk2.get_target_type() == type); + + // reset(false) is the same as reset() + hll_sketch sk3 = make(8, type, true, 5000); + sk3.reset(false); + REQUIRE(preints_of(sk3) == LIST_PREINTS); + } +} + +TEST_CASE("hll full size: a reset sketch is usable again", "[hll_full_size]") { + hll_sketch sk = make(8, HLL_8, false, 100); + sk.reset(true); + for (uint64_t i = 0; i < 1000; ++i) sk.update(i); + REQUIRE_FALSE(sk.is_empty()); + REQUIRE(sk.get_estimate() == Approx(1000).epsilon(0.2)); +} + +TEST_CASE("hll full size: an image with the reserved bit set is read as if it were clear", + "[hll_full_size]") { + // an image produced by another implementation may have bit 32 set: datasketches-java uses it + // as its union rebuild flag. It must not change how this implementation reads the sketch. + for (auto type: {HLL_4, HLL_6, HLL_8}) { + const hll_sketch sk = make(8, type, false, 5000); + auto bytes = sk.serialize_updatable(); + auto tampered = bytes; + tampered[FLAGS_BYTE] |= RESERVED_BIT_32; + + const hll_sketch clean = hll_sketch::deserialize(bytes.data(), bytes.size()); + hll_sketch tainted = hll_sketch::deserialize(tampered.data(), tampered.size()); + + REQUIRE(tainted.get_estimate() == clean.get_estimate()); + REQUIRE(tainted.serialize_updatable() == bytes); // the bit is not propagated back out + tainted.reset(); + REQUIRE(preints_of(tainted) == LIST_PREINTS); // and does not alter reset() behaviour + } +} + +TEST_CASE("hll full size: a union never inherits full size from an input sketch", + "[hll_full_size]") { + // the gadget is an internal detail; unioning a full-size sketch must not change how the + // union resets, nor put the reserved bit into the union's result + const hll_sketch full = make(8, HLL_8, true, 5000); + + hll_union u(8); + u.update(full); + const hll_sketch result = u.get_result(HLL_8); + REQUIRE((result.serialize_compact()[FLAGS_BYTE] & RESERVED_BIT_32) == 0); + REQUIRE((result.serialize_updatable()[FLAGS_BYTE] & RESERVED_BIT_32) == 0); + + u.reset(); + REQUIRE(u.is_empty()); + REQUIRE(preints_of(u.get_result(HLL_8)) == LIST_PREINTS); + + // same through the rvalue overload, which moves the sketch into the gadget + hll_union u2(8); + u2.update(make(8, HLL_8, true, 5000)); + u2.reset(); + REQUIRE(u2.is_empty()); + REQUIRE(preints_of(u2.get_result(HLL_8)) == LIST_PREINTS); +} + +} /* namespace datasketches */ diff --git a/hll/test/HllKxqRebuildTest.cpp b/hll/test/HllKxqRebuildTest.cpp new file mode 100644 index 00000000..b5ae1c7e --- /dev/null +++ b/hll/test/HllKxqRebuildTest.cpp @@ -0,0 +1,150 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include +#include +#include +#include + +#include "hll.hpp" +#include "fdlibm_log.hpp" + +namespace datasketches { + +// offsets into the HLL updatable image +static const size_t CUR_MIN_BYTE = 6; +static const size_t NUM_AT_CUR_MIN_INT = 32; +static const size_t HLL_BYTE_ARR_START = 40; + +static hll_sketch make(uint8_t lg_k, target_hll_type type, uint64_t lo, uint64_t hi) { + hll_sketch sk(lg_k, type); + for (uint64_t i = lo; i < hi; ++i) sk.update(i); + return sk; +} +static uint32_t num_at_cur_min_of(const hll_sketch::vector_bytes& img) { + uint32_t v; std::memcpy(&v, img.data() + NUM_AT_CUR_MIN_INT, sizeof(v)); return v; +} + +TEST_CASE("hll kxq rebuild: union result is merge-order independent", "[hll_kxq]") { + // C stays in SET mode, so this exercises the coupon-update path into a gadget with a + // deferred rebuild pending, which is where the stored curMin/numAtCurMin used to drift + const hll_sketch a = make(12, HLL_4, 20000, 30364); + const hll_sketch b = make(10, HLL_8, 5000, 14699); + const hll_sketch c = make(17, HLL_4, 70000, 72598); + const hll_sketch* in[3] = {&a, &b, &c}; + + auto run = [&](int i, int j, int k) { + hll_union u(7); + u.update(*in[i]); u.update(*in[j]); u.update(*in[k]); + return u.get_result(HLL_8).serialize_updatable(); + }; + const auto ref = run(0, 1, 2); + REQUIRE(run(0, 2, 1) == ref); + REQUIRE(run(1, 0, 2) == ref); + REQUIRE(run(1, 2, 0) == ref); + REQUIRE(run(2, 0, 1) == ref); + REQUIRE(run(2, 1, 0) == ref); +} + +TEST_CASE("hll kxq rebuild: reading an estimate does not change a later result", + "[hll_kxq]") { + // the rebuild is lazy; when it fires must not be observable in the serialized image + const hll_sketch p = make(13, HLL_8, 0, 50000); + const hll_sketch q = make(13, HLL_8, 50000, 100000); + + for (uint8_t lg_max_k: {uint8_t(7), uint8_t(8), uint8_t(9)}) { + hll_union peeked(lg_max_k); + peeked.update(p); peeked.update(q); + (void) peeked.get_estimate(); // forces the rebuild here + for (uint64_t v = 9000000; v < 9400000; ++v) peeked.update(v); + + hll_union plain(lg_max_k); + plain.update(p); plain.update(q); + for (uint64_t v = 9000000; v < 9400000; ++v) plain.update(v); + + REQUIRE(peeked.get_result(HLL_8).serialize_updatable() + == plain.get_result(HLL_8).serialize_updatable()); + } +} + +TEST_CASE("hll kxq rebuild: stored curMin and numAtCurMin agree with the registers", + "[hll_kxq]") { + // HLL_8 convention: curMin is always 0 and numAtCurMin counts the zero registers + const hll_sketch a = make(15, HLL_8, 0, 100000); + const hll_sketch b = make(8, HLL_8, 100000, 200000); + hll_union u(8); + u.update(a); u.update(b); + const auto img = u.get_result(HLL_8).serialize_updatable(); + + uint32_t zeros = 0; + for (size_t i = HLL_BYTE_ARR_START; i < img.size(); ++i) if (img[i] == 0) ++zeros; + + REQUIRE(img[CUR_MIN_BYTE] == 0); + REQUIRE(num_at_cur_min_of(img) == zeros); +} + +TEST_CASE("hll kxq rebuild: relative error constants are full precision", "[hll_kxq]") { + // lg_k > 12 uses the closed form rather than the interpolation table, so a constant + // truncated to seven digits is directly observable in the bounds + const double hip = std::sqrt(std::log(2.0)); // sqrt(ln 2) + const double non_hip = std::sqrt((3.0 * std::log(2.0)) - 1.0); // sqrt(3 ln 2 - 1) + + for (uint8_t lg_k: {uint8_t(13), uint8_t(16), uint8_t(21)}) { + const double k = static_cast(1 << lg_k); + for (uint8_t sd = 1; sd <= 3; ++sd) { + const double got_hip = hll_union::get_rel_err(false, false, lg_k, sd); + const double got_non = hll_union::get_rel_err(false, true, lg_k, sd); + REQUIRE(got_hip == Approx(sd * hip / std::sqrt(k)).epsilon(1e-15)); + REQUIRE(got_non == Approx(sd * non_hip / std::sqrt(k)).epsilon(1e-15)); + } + } +} + +TEST_CASE("hll kxq rebuild: log matches the fdlibm reference", "[hll_kxq]") { + // the linear counting estimator subtracts two nearby harmonic numbers, which amplifies a + // 1 ULP difference in log() by more than an order of magnitude. Pin log() to fdlibm, the + // function datasketches-java's StrictMath.log is specified to be. These expected values + // were taken from Java; the platform libm differs from every one of them. + struct { int x; uint64_t bits; } expected[] = { + { 48, 0x400ef8383c50bb74ULL}, + { 74, 0x4011375cd6fcab1cULL}, + { 185, 0x4014e1a4f518c72cULL}, + { 196, 0x40151cca16d7bba8ULL}, + { 299, 0x4016cd411481a020ULL}, + { 308, 0x4016eb9f470ac0b8ULL}, + { 334, 0x40173e9bbe951e9cULL}, + { 343, 0x401759d602a5c3c2ULL}, + { 1261, 0x401c8f031e7e1220ULL}, + }; + for (const auto& e: expected) { + const double got = fdlibm::log(static_cast(e.x)); + uint64_t bits; std::memcpy(&bits, &got, sizeof(bits)); + REQUIRE(bits == e.bits); + } + + // edge cases: fdlibm produces these by dividing by a zero constant, which MSVC rejects at + // compile time, so they are returned directly. Pin the values. + REQUIRE(fdlibm::log(0.0) == -std::numeric_limits::infinity()); + REQUIRE(fdlibm::log(-0.0) == -std::numeric_limits::infinity()); + REQUIRE(std::isnan(fdlibm::log(-1.0))); + REQUIRE(fdlibm::log(1.0) == 0.0); + REQUIRE(fdlibm::log(5e-320) == Approx(-735.2178).epsilon(1e-6)); // subnormal scaling path +} + +} /* namespace datasketches */