diff options
| author | Joel Redman <joel.redman@mongodb.com> | 2022-09-20 18:10:04 +0000 |
|---|---|---|
| committer | Evergreen Agent <no-reply@evergreen.mongodb.com> | 2022-09-20 19:45:21 +0000 |
| commit | 9529d985675a29c931c30d0f2272e1153e150d97 (patch) | |
| tree | 3d6f56b057df7d8ff0d04c714970836a10a98e24 /src | |
| parent | c3438171af82aa30fa2b4034f135698eda7d39ec (diff) | |
| download | mongo-9529d985675a29c931c30d0f2272e1153e150d97.tar.gz | |
SERVER-66605 Import spike histogram calculation code from hist_ce branch
Diffstat (limited to 'src')
| -rw-r--r-- | src/mongo/db/query/ce/SConscript | 57 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/array_histogram.cpp | 1 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/histogram_estimation.cpp | 47 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/histogram_estimation.h | 2 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/max_diff.cpp | 325 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/max_diff.h | 82 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/maxdiff_histogram_test.cpp | 259 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/maxdiff_test_utils.cpp | 145 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/maxdiff_test_utils.h | 88 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/rand_utils.cpp | 308 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/rand_utils.h | 167 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/rand_utils_new.cpp | 250 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/rand_utils_new.h | 354 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/value_utils.cpp | 167 | ||||
| -rw-r--r-- | src/mongo/db/query/ce/value_utils.h | 109 |
15 files changed, 2314 insertions, 47 deletions
diff --git a/src/mongo/db/query/ce/SConscript b/src/mongo/db/query/ce/SConscript index db504072718..99b258b4e7f 100644 --- a/src/mongo/db/query/ce/SConscript +++ b/src/mongo/db/query/ce/SConscript @@ -7,12 +7,10 @@ env = env.Clone() env.Library( target="query_ce", source=[ - 'array_histogram.cpp', 'ce_histogram.cpp', 'ce_sampling.cpp', 'collection_statistics_impl.cpp', 'histogram_estimation.cpp', - 'scalar_histogram.cpp', 'stats_cache.cpp', 'stats_cache_loader_impl.cpp', ], @@ -20,6 +18,30 @@ env.Library( '$BUILD_DIR/mongo/db/dbdirectclient', '$BUILD_DIR/mongo/db/exec/sbe/query_sbe_abt', '$BUILD_DIR/mongo/db/query/optimizer/optimizer', + 'query_stats', + 'stats_serialization', + ], +) + +env.Library( + target="query_stats", + source=[ + 'array_histogram.cpp', + 'scalar_histogram.cpp', + 'value_utils.cpp', + ], + LIBDEPS=[ + '$BUILD_DIR/mongo/db/exec/sbe/query_sbe_values', + ], +) + +env.Library( + target="query_stats_gen", + source=[ + 'max_diff.cpp', + ], + LIBDEPS=[ + 'query_stats', 'stats_serialization', ], ) @@ -36,6 +58,7 @@ env.Library( '$BUILD_DIR/mongo/db/query/optimizer/unit_test_utils', "$BUILD_DIR/mongo/unittest/unittest", 'query_ce', + 'query_stats', ], ) @@ -129,9 +152,11 @@ env.CppUnitTest( '$BUILD_DIR/mongo/util/fail_point', '$BUILD_DIR/mongo/util/pcre_wrapper', 'query_ce', + 'query_stats', 'stats_serialization', ], ) + env.CppUnitTest( target="stats_cache_test", source=[ @@ -145,6 +170,7 @@ env.CppUnitTest( 'query_ce', ], ) + env.CppUnitTest( target="stats_path_test", source=[ @@ -154,7 +180,34 @@ env.CppUnitTest( '$BUILD_DIR/mongo/base', '$BUILD_DIR/mongo/db/service_context', 'ce_test_utils', + 'stats_serialization', + ], +) + +env.Library( + target="query_stats_test_utils", + source=[ + 'rand_utils.cpp', + 'rand_utils_new.cpp', + 'maxdiff_test_utils.cpp', + ], + LIBDEPS=[ + '$BUILD_DIR/mongo/base', + '$BUILD_DIR/mongo/db/exec/sbe/sbe_abt_test_util', + "$BUILD_DIR/mongo/unittest/unittest", 'query_ce', + 'query_stats', + 'query_stats_gen', 'stats_serialization', ], ) + +env.CppUnitTest( + target="maxdiff_histogram_test", + source=[ + 'maxdiff_histogram_test.cpp', + ], + LIBDEPS=[ + 'query_stats_test_utils', + ], +) diff --git a/src/mongo/db/query/ce/array_histogram.cpp b/src/mongo/db/query/ce/array_histogram.cpp index 453e31ac047..efbe7404289 100644 --- a/src/mongo/db/query/ce/array_histogram.cpp +++ b/src/mongo/db/query/ce/array_histogram.cpp @@ -28,6 +28,7 @@ */ #include "mongo/db/query/ce/array_histogram.h" +#include "mongo/db/query/ce/value_utils.h" namespace mongo::ce { using namespace sbe; diff --git a/src/mongo/db/query/ce/histogram_estimation.cpp b/src/mongo/db/query/ce/histogram_estimation.cpp index 4fd2d8376db..3009de9cebc 100644 --- a/src/mongo/db/query/ce/histogram_estimation.cpp +++ b/src/mongo/db/query/ce/histogram_estimation.cpp @@ -29,50 +29,11 @@ #include "mongo/db/query/ce/histogram_estimation.h" #include "mongo/db/exec/sbe/abt/abt_lower.h" +#include "mongo/db/query/ce/value_utils.h" #include "mongo/db/query/optimizer/syntax/expr.h" namespace mongo::ce { using namespace sbe; -namespace { - -bool sameTypeBracket(value::TypeTags tag1, value::TypeTags tag2) { - if (tag1 == tag2) { - return true; - } - return ((value::isNumber(tag1) && value::isNumber(tag2)) || - (value::isString(tag1) && value::isString(tag2))); -} - -double valueToDouble(value::TypeTags tag, value::Value val) { - double result = 0; - if (value::isNumber(tag)) { - result = value::numericCast<double>(tag, val); - } else if (value::isString(tag)) { - const StringData sd = value::getStringView(tag, val); - - // Convert a prefix of the string to a double. - const size_t maxPrecision = std::min(sd.size(), sizeof(double)); - for (size_t i = 0; i < maxPrecision; ++i) { - const char ch = sd[i]; - const double charToDbl = ch / std::pow(2, i * 8); - result += charToDbl; - } - } else { - uassert(6844500, "Unexpected value type", false); - } - - return result; -} - -int32_t compareValues3w(value::TypeTags tag1, - value::Value val1, - value::TypeTags tag2, - value::Value val2) { - const auto [compareTag, compareVal] = value::compareValue(tag1, val1, tag2, val2); - uassert(6695716, "Invalid comparison result", compareTag == value::TypeTags::NumberInt32); - return value::bitcastTo<int32_t>(compareVal); -} -} // namespace EstimationResult getTotals(const ScalarHistogram& h) { if (h.empty()) { @@ -170,7 +131,7 @@ EstimationResult estimate(const ScalarHistogram& h, const size_t half = len >> 1; const auto [boundTag, boundVal] = h.getBounds().getAt(bucketIndex + half); - if (compareValues3w(boundTag, boundVal, tag, val) < 0) { + if (compareValues(boundTag, boundVal, tag, val) < 0) { bucketIndex += half + 1; len -= half + 1; } else { @@ -195,7 +156,7 @@ EstimationResult estimate(const ScalarHistogram& h, const Bucket& bucket = h.getBuckets().at(bucketIndex); const auto [boundTag, boundVal] = h.getBounds().getAt(bucketIndex); - const bool isEndpoint = compareValues3w(boundTag, boundVal, tag, val) == 0; + const bool isEndpoint = compareValues(boundTag, boundVal, tag, val) == 0; if (isEndpoint) { switch (type) { @@ -302,7 +263,7 @@ double estimateCardRange(const ArrayHistogram& ah, EstimationAlgo estimationAlgo) { uassert(6695701, "Low bound must not be higher than high", - compareValues3w(tagLow, valLow, tagHigh, valHigh) <= 0); + compareValues(tagLow, valLow, tagHigh, valHigh) <= 0); // Helper lambda to shorten code for legibility. auto estRange = [&](const ScalarHistogram& h) { diff --git a/src/mongo/db/query/ce/histogram_estimation.h b/src/mongo/db/query/ce/histogram_estimation.h index 3225dab1272..8b3cb4c9596 100644 --- a/src/mongo/db/query/ce/histogram_estimation.h +++ b/src/mongo/db/query/ce/histogram_estimation.h @@ -89,11 +89,9 @@ double estimateCardEq(const ArrayHistogram& ah, sbe::value::TypeTags tag, sbe::v */ double estimateCardRange(const ArrayHistogram& ah, bool includeScalar, - /* Define lower bound. */ bool lowInclusive, sbe::value::TypeTags tagLow, sbe::value::Value valLow, - /* Define upper bound. */ bool highInclusive, sbe::value::TypeTags tagHigh, sbe::value::Value valHigh, diff --git a/src/mongo/db/query/ce/max_diff.cpp b/src/mongo/db/query/ce/max_diff.cpp new file mode 100644 index 00000000000..944d43aa4ba --- /dev/null +++ b/src/mongo/db/query/ce/max_diff.cpp @@ -0,0 +1,325 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#include <algorithm> +#include <cmath> +#include <cstddef> +#include <iostream> +#include <limits> +#include <map> +#include <ostream> +#include <queue> + +#include "mongo/base/string_data.h" +#include "mongo/bson/bsonobjbuilder.h" +#include "mongo/bson/bsontypes.h" +#include "mongo/db/exec/sbe/values/bson.h" +#include "mongo/db/exec/sbe/values/value.h" +#include "mongo/db/query/ce/max_diff.h" +#include "mongo/db/query/ce/value_utils.h" +#include "mongo/util/assert_util.h" + + +namespace mongo::ce { + +std::string printDistribution(const DataDistribution& distr, size_t nElems) { + std::ostringstream os; + for (size_t i = 0; i < std::min(nElems, distr._freq.size()); ++i) { + os << "{val: " << distr._bounds[i].get() << ", " << distr._freq[i].toString() << "}\n"; + } + return os.str(); +} + +static double valueSpread(value::TypeTags tag1, + value::Value val1, + value::TypeTags tag2, + value::Value val2) { + double doubleVal1 = valueToDouble(tag1, val1); + double doubleVal2 = valueToDouble(tag2, val2); + uassert(6660502, + "Data distribution values must be monotonically increasing.", + doubleVal2 >= doubleVal1); + return doubleVal2 - doubleVal1; +} + +DataDistribution getDataDistribution(const std::vector<SBEValue>& sortedInput) { + if (sortedInput.empty()) { + return {}; + } + + DataDistribution result; + value::TypeTags prevTag; + value::Value prevValue; + bool first = true; + + // Aggregate the values in a sorted dataset into a frequency distribution. + size_t idx = 0; + for (size_t i = 0; i < sortedInput.size(); i++) { + const auto v = sortedInput[i].get(); + const auto comparison = first ? 1 : compareValues(v.first, v.second, prevTag, prevValue); + first = false; + + if (comparison != 0) { + uassert(6660550, "Input is not sorted", comparison > 0); + prevTag = v.first; + prevValue = v.second; + + const auto [tagCopy, valCopy] = copyValue(v.first, v.second); + result._bounds.emplace_back(tagCopy, valCopy); + result._freq.emplace_back(idx, 1); + ++idx; + } else { + ++result._freq.back()._freq; + } + } + + // Calculate the area for all values in the data distribution. + // The current minimum and maximum areas of the values of a type class. + double maxArea = 0.0; + + for (size_t i = 0; i + 1 < result._freq.size(); ++i) { + const auto v1 = result._bounds[i]; + const auto v2 = result._bounds[i + 1]; + const bool newTypeClass = !sameTypeClass(v1.getTag(), v2.getTag()); + + if (newTypeClass) { + const auto res = result.typeClassBounds.emplace(i, maxArea); + uassert(6660551, "There can't be duplicate type class bounds.", res.second); + maxArea = 0.0; + } else if (i == 0) { + const double spread = + valueSpread(v1.getTag(), v1.getValue(), v2.getTag(), v2.getValue()); + maxArea = result._freq[i]._freq * spread; + } + + if (i == 0 || newTypeClass) { + // Make sure we insert bucket boundaries between different types, and also make sure + // first value is picked for a boundary. + result._freq[i]._area = std::numeric_limits<double>::infinity(); + } else { + const double spread = + valueSpread(v1.getTag(), v1.getValue(), v2.getTag(), v2.getValue()); + result._freq[i]._area = result._freq[i]._freq * spread; + maxArea = std::max(maxArea, result._freq[i]._area); + } + } + + // Make sure last value is picked as a histogram bucket boundary. + result._freq.back()._area = std::numeric_limits<double>::infinity(); + const auto res = result.typeClassBounds.emplace(result._freq.size(), maxArea); + uassert(6660503, "There can't be duplicate type class bounds.", res.second); + + // Compute normalized areas. If the spread is 0, the area may also be 0. This could happen, + // for instance, if there is only a single value of a given type, + size_t beginIdx = 0; + for (const auto [endIdx, area] : result.typeClassBounds) { + for (size_t i = beginIdx; i < endIdx; ++i) { + result._freq[i]._normArea = area > 0.0 ? (result._freq[i]._area / area) : 0.0; + } + beginIdx = endIdx; + } + + // std::cout << "Distribution sorted by value:\n" + // << printDistribution(result, result._freq.size()) << "\n" + // << std::flush; + + return result; +} + +// TODO: This doesn't seem right -- it looks like we're sorting on the frequency, +// not the difference between buckets +static std::vector<ValFreq> generateTopKBuckets(const DataDistribution& dataDistrib, + size_t numBuckets) { + struct AreaComparator { + bool operator()(const ValFreq& a, const ValFreq& b) const { + return a._normArea > b._normArea; + } + }; + std::priority_queue<ValFreq, std::vector<ValFreq>, AreaComparator> pq; + + for (const auto& valFreq : dataDistrib._freq) { + if (pq.size() < numBuckets) { + pq.emplace(valFreq); + } else if (AreaComparator()(valFreq, pq.top())) { + pq.pop(); + pq.emplace(valFreq); + } + } + + std::vector<ValFreq> result; + while (!pq.empty()) { + result.push_back(pq.top()); + pq.pop(); + } + + std::sort(result.begin(), result.end(), [](const ValFreq& a, const ValFreq& b) { + return a._idx < b._idx; + }); + + return result; +} + +ScalarHistogram genMaxDiffHistogram(const DataDistribution& dataDistrib, size_t numBuckets) { + if (dataDistrib._freq.empty()) { + return {}; + } + + std::vector<ValFreq> topKBuckets = generateTopKBuckets(dataDistrib, numBuckets); + uassert(6660504, + "Must have bucket boundary on first value", + topKBuckets[0]._idx == dataDistrib._freq[0]._idx); + uassert(6660505, + "Must have bucket boundary on last value", + topKBuckets.back()._idx == dataDistrib._freq.back()._idx); + + std::vector<Bucket> buckets; + value::Array bounds; + + // Create histogram buckets out of the top-K bucket values. + size_t startBucketIdx = 0; + double cumulativeFreq = 0.0; + double cumulativeNDV = 0.0; + for (size_t i = 0; i < std::min(dataDistrib._freq.size(), numBuckets); i++) { + const size_t bucketBoundIdx = topKBuckets[i]._idx; + const double freq = dataDistrib._freq.at(bucketBoundIdx)._freq; + + // Compute per-bucket statistics. + double rangeFreq = 0.0; + double ndv = 0.0; + while (startBucketIdx < bucketBoundIdx) { + rangeFreq += dataDistrib._freq[startBucketIdx++]._freq; + ++ndv; + } + cumulativeFreq += rangeFreq + freq; + cumulativeNDV += ndv + 1.0; + + // Add a histogram bucket. + const auto v = dataDistrib._bounds[startBucketIdx]; + const auto [copyTag, copyVal] = value::copyValue(v.getTag(), v.getValue()); + bounds.push_back(copyTag, copyVal); + buckets.emplace_back(freq, rangeFreq, cumulativeFreq, ndv, cumulativeNDV); + startBucketIdx++; + } + + return {std::move(bounds), std::move(buckets)}; +} + +ArrayHistogram createArrayEstimator(const std::vector<SBEValue>& arrayData, size_t nBuckets) { + std::vector<SBEValue> scalarData; + std::vector<SBEValue> arrayMinData; + std::vector<SBEValue> arrayMaxData; + std::vector<SBEValue> arrayUniqueData; + std::map<value::TypeTags, size_t> typeCounts; + std::map<value::TypeTags, size_t> arrayTypeCounts; + + for (const auto& v : arrayData) { + auto tagCount = typeCounts.insert({v.getTag(), 1}); + if (!tagCount.second) { + ++tagCount.first->second; + } + if (v.getTag() == value::TypeTags::Null) { + continue; // nulls are accounted for in typeCounts + } + if (v.getTag() == value::TypeTags::Array) { + std::vector<SBEValue> arrayElements; + value::Array* arr = value::getArrayView(v.getValue()); + for (size_t i = 0; i < arr->size(); i++) { + const auto [tag, val] = arr->getAt(i); + auto arrTagCount = arrayTypeCounts.insert({tag, 1}); + if (!arrTagCount.second) { + ++arrTagCount.first->second; + } + if (tag == value::TypeTags::Null) { + continue; // nulls are accounted for in arrayTypeCounts + } + const auto [tagCopy, valCopy] = value::copyValue(tag, val); + arrayElements.emplace_back(tagCopy, valCopy); + } + + sortValueVector(arrayElements); + + { + // Emit values for arrayMin and arrayMax histograms. + boost::optional<SBEValue> prev; + for (const auto& element : arrayElements) { + uassert(6660506, + "Multi-level array nesting is not supported yet", + element.getTag() != value::TypeTags::Array); + if (!prev) { + arrayMinData.push_back(element); + } else if (!sameTypeClass(prev->getTag(), element.getTag())) { + arrayMaxData.push_back(*prev); + arrayMinData.push_back(element); + } + prev = element; + } + if (prev) { + arrayMaxData.push_back(*prev); + } + } + { + // Emit values for arrayUnique histogram. + boost::optional<SBEValue> prev; + for (const auto& element : arrayElements) { + if (!prev || + compareValues(prev->getTag(), + prev->getValue(), + element.getTag(), + element.getValue()) < 0) { + arrayUniqueData.push_back(element); + prev = element; + } + } + } + } else { + // Assume non-arrays are scalars. Emit values for scalar histogram. + scalarData.push_back(v); + } + } + + sortValueVector(scalarData); + sortValueVector(arrayMinData); + sortValueVector(arrayMaxData); + sortValueVector(arrayUniqueData); + + ScalarHistogram scalarHist = genMaxDiffHistogram(getDataDistribution(scalarData), nBuckets); + ScalarHistogram arrayMinHist = genMaxDiffHistogram(getDataDistribution(arrayMinData), nBuckets); + ScalarHistogram arrayMaxHist = genMaxDiffHistogram(getDataDistribution(arrayMaxData), nBuckets); + ScalarHistogram arrayUniqueHist = + genMaxDiffHistogram(getDataDistribution(arrayUniqueData), nBuckets); + + return {std::move(scalarHist), + std::move(typeCounts), + std::move(arrayUniqueHist), + std::move(arrayMinHist), + std::move(arrayMaxHist), + std::move(arrayTypeCounts)}; +} + +} // namespace mongo::ce diff --git a/src/mongo/db/query/ce/max_diff.h b/src/mongo/db/query/ce/max_diff.h new file mode 100644 index 00000000000..267f304c089 --- /dev/null +++ b/src/mongo/db/query/ce/max_diff.h @@ -0,0 +1,82 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#pragma once + +#include <utility> +#include <vector> + +#include "mongo/db/exec/sbe/values/value.h" +#include "mongo/db/query/ce/array_histogram.h" +#include "mongo/db/query/ce/scalar_histogram.h" +#include "mongo/db/query/ce/value_utils.h" + +namespace mongo::ce { + +struct ValFreq { + ValFreq(size_t idx, size_t freq) : _idx(idx), _freq(freq), _area(-1.0), _normArea(-1) {} + + const std::string toString() const { + std::ostringstream os; + os << "idx: " << _idx << ", freq: " << _freq << ", area: " << _area + << ", normArea: " << _normArea; + return os.str(); + } + + size_t _idx; // Original index according to value order. + size_t _freq; // Frequency of the value. + double _area; // Derived as: spread * frequency + double _normArea; // Area normalized to the maximum in a type class. +}; + +struct DataDistribution { + std::vector<SBEValue> _bounds; + std::vector<ValFreq> _freq; + // The min/max areas of each type class. The key is the index of the last boundary of the class. + std::map<size_t, double> typeClassBounds; +}; + +/** + Given a set of values sorted in BSON order, generate a data distribution consisting of + counts for each value with the values in sorted order +*/ +DataDistribution getDataDistribution(const std::vector<SBEValue>& sortedInput); + +/** + Given a data distribution, generate a scalar histogram with the supplied number of buckets +*/ +ScalarHistogram genMaxDiffHistogram(const DataDistribution& dataDistrib, size_t numBuckets); + +/** + Given a vector containing SBEValues, generate a set of statistics to summarize the supplied + data. Histograms will use the supplied number of buckets +*/ +ArrayHistogram createArrayEstimator(const std::vector<SBEValue>& arrayData, size_t nBuckets); + +} // namespace mongo::ce diff --git a/src/mongo/db/query/ce/maxdiff_histogram_test.cpp b/src/mongo/db/query/ce/maxdiff_histogram_test.cpp new file mode 100644 index 00000000000..aacaa8819bb --- /dev/null +++ b/src/mongo/db/query/ce/maxdiff_histogram_test.cpp @@ -0,0 +1,259 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#include <string> +#include <vector> + +#include "mongo/db/concurrency/lock_state.h" +#include "mongo/db/exec/sbe/abt/sbe_abt_test_util.h" +#include "mongo/db/exec/sbe/values/value.h" +#include "mongo/db/query/ce/array_histogram.h" +#include "mongo/db/query/ce/histogram_estimation.h" +#include "mongo/db/query/ce/max_diff.h" +#include "mongo/db/query/ce/maxdiff_test_utils.h" +#include "mongo/db/query/ce/rand_utils.h" +#include "mongo/db/query/ce/rand_utils_new.h" +#include "mongo/db/query/ce/scalar_histogram.h" +#include "mongo/db/query/optimizer/utils/unit_test_utils.h" +#include "mongo/logv2/log_component.h" +#include "mongo/logv2/log_component_settings.h" +#include "mongo/logv2/log_severity.h" +#include "mongo/unittest/unittest.h" + +namespace mongo::ce::statistics { +namespace { + +using namespace sbe; +const double kTolerance = 0.001; + +class HistogramTest : public ServiceContextTest {}; +class HistogramTestLarge : public ServiceContextTest {}; + +class TestObserver : public ServiceContext::ClientObserver { +public: + TestObserver() = default; + ~TestObserver() = default; + + void onCreateClient(Client* client) final {} + + void onDestroyClient(Client* client) final {} + + void onCreateOperationContext(OperationContext* opCtx) override { + opCtx->setLockState(std::make_unique<LockerImpl>(opCtx->getServiceContext())); + } + + void onDestroyOperationContext(OperationContext* opCtx) final {} +}; + +const ServiceContext::ConstructorActionRegisterer clientObserverRegisterer{ + "TestObserver", + [](ServiceContext* service) { + service->registerClientObserver(std::make_unique<TestObserver>()); + }, + [](ServiceContext* serviceContext) {}}; + +static double estimateCard(const ScalarHistogram& hist, const int v, const EstimationType type) { + const auto [tag, val] = makeInt64Value(v); + return estimate(hist, tag, val, type).card; +}; + +TEST_F(HistogramTest, BasicCreate) { + std::vector<BucketData> data{{0, 1.0, 11.0, 1.0}, + {10, 2.0, 12.0, 2.0}, + {20, 3.0, 13.0, 3.0}, + {30, 4.0, 14.0, 4.0}, + {40, 5.0, 15.0, 5.0}, + {50, 6.0, 16.0, 6.0}}; + const ScalarHistogram hist = createHistogram(data); + + ASSERT_EQ(102.0, getTotals(hist).card); + + ASSERT_APPROX_EQUAL(1.0, estimateCard(hist, 0, EstimationType::kEqual), kTolerance); + ASSERT_APPROX_EQUAL(6.0, estimateCard(hist, 5, EstimationType::kEqual), kTolerance); + ASSERT_APPROX_EQUAL(0.0, estimateCard(hist, 55, EstimationType::kEqual), kTolerance); + + ASSERT_APPROX_EQUAL(28.1667, estimateCard(hist, 15, EstimationType::kLess), kTolerance); + ASSERT_APPROX_EQUAL(32.5, estimateCard(hist, 15, EstimationType::kLessOrEqual), kTolerance); + ASSERT_APPROX_EQUAL(39, estimateCard(hist, 20, EstimationType::kLess), kTolerance); + ASSERT_APPROX_EQUAL(42.0, estimateCard(hist, 20, EstimationType::kLessOrEqual), kTolerance); + + ASSERT_APPROX_EQUAL(69.5, estimateCard(hist, 15, EstimationType::kGreater), kTolerance); +} + +TEST_F(HistogramTest, CreateFixed) { + std::vector<BucketData> data; + for (int i = 0; i < 100; i++) { + data.push_back(BucketData{i * 10, 1.0, 0.0, 0.0}); + } + const ScalarHistogram hist = createHistogram(data); + + ASSERT_APPROX_EQUAL(50.0, estimateCard(hist, 50 * 10, EstimationType::kLess), kTolerance); +} + +TEST_F(HistogramTest, MaxDiffTestInt) { + constexpr size_t nElems = 100; + constexpr size_t nBuckets = 10; + constexpr size_t seed = 0; + + std::vector<SBEValue> randData = genRandomValueArray(nElems, 1.0, 0.0, seed); + + auto opCtx = makeOperationContext(); + const size_t actualCard = getActualCard(opCtx.get(), randData, "[{$match: {a: {$lt: 10}}}]"); + + const ScalarHistogram& hist = makeHistogram(randData, nBuckets); + std::cout << hist.toString(); + + ASSERT_GTE(hist.getBuckets().size(), nBuckets); + const double expectedCard = estimateCard(hist, 10, EstimationType::kLess); + + ASSERT_EQ(36, actualCard); + ASSERT_APPROX_EQUAL(32.8667, expectedCard, kTolerance); +} + +TEST_F(HistogramTest, MaxDiffTestString) { + constexpr size_t nElems = 100; + constexpr size_t nBuckets = 10; + constexpr size_t seed = 0; + + auto randData = genRandomValueArray(nElems, 0.0, 1.0, seed); + std::cout << "Generated " << nElems << " random values:\n" + << printValueArray(randData) << "\n" + << std::flush; + + auto opCtx = makeOperationContext(); + const size_t actualCard = + getActualCard(opCtx.get(), randData, "[{$match: {a: {$lt: '91YgOvBB'}}}]"); + + sortValueVector(randData); + const DataDistribution& dataDistrib = getDataDistribution(randData); + + const ScalarHistogram& hist = genMaxDiffHistogram(dataDistrib, nBuckets); + std::cout << hist.toString(); + ASSERT_GTE(hist.getBuckets().size(), nBuckets); + + const auto [tag, val] = value::makeNewString("91YgOvBB"_sd); + value::ValueGuard vg(tag, val); + const double expectedCard = estimate(hist, tag, val, EstimationType::kLess).card; + + ASSERT_EQ(13, actualCard); + ASSERT_APPROX_EQUAL(11.0783, expectedCard, kTolerance); +} + +TEST_F(HistogramTest, MaxDiffTestMixedTypes) { + constexpr size_t nElems = 100; + constexpr size_t nBuckets = 10; + constexpr size_t seed = 0; + + auto randData = genRandomValueArray(nElems, 0.5, 0.5, seed); + std::cout << "Generated " << nElems << " random values:\n" + << printValueArray(randData) << "\n" + << std::flush; + + auto opCtx = makeOperationContext(); + const size_t actualCard = getActualCard(opCtx.get(), randData, "[{$match: {a: {$lt: 10}}}]"); + + sortValueVector(randData); + const DataDistribution& dataDistrib = getDataDistribution(randData); + + const ScalarHistogram& hist = genMaxDiffHistogram(dataDistrib, nBuckets); + std::cout << hist.toString(); + ASSERT_GTE(hist.getBuckets().size(), nBuckets); + const double expectedCard = estimateCard(hist, 10, EstimationType::kLess); + + ASSERT_EQ(18, actualCard); + ASSERT_APPROX_EQUAL(17.0833, expectedCard, kTolerance); +} + +TEST_F(HistogramTest, MaxDiffIntArrays) { + constexpr size_t nElems = 100; + constexpr size_t nBuckets = 10; + constexpr size_t seed = 0; + + auto rawData = genRandomValueArray(nElems, 1.0, 0.0, seed); + auto arrayData = genRandomValueArrayWithArrays(rawData); + + ArrayHistogram estimator = createArrayEstimator(arrayData, nBuckets); + + auto opCtx = makeOperationContext(); + { + const size_t actualCard = + getActualCard(opCtx.get(), arrayData, "[{$match: {a: {$eq: 2}}}]"); + + const auto [tag, val] = makeInt64Value(2); + value::ValueGuard vg(tag, val); + const double expectedCard = estimateCardEq(estimator, tag, val); + + ASSERT_APPROX_EQUAL(4.0, expectedCard, kTolerance); + ASSERT_EQ(4, actualCard); + } + + { + const size_t actualCard = + getActualCard(opCtx.get(), arrayData, "[{$match: {a: {$lt: 3}}}]"); + + const auto [tag, val] = makeInt64Value(3); + value::ValueGuard vg(tag, val); + const double expectedCard = estimateCardRange(estimator, + true /*includeScalar*/, + false /*lowInclusive*/, + value::TypeTags::MinKey, + 0, + false /*highInclusive*/, + tag, + val); + + ASSERT_APPROX_EQUAL(4.6667, expectedCard, kTolerance); + ASSERT_EQ(6, actualCard); + } + + { + const size_t actualCard = getActualCard( + opCtx.get(), arrayData, "[{$match: {a: {$elemMatch: {$gt: 2, $lt: 5}}}}]"); + + const auto [lowTag, lowVal] = makeInt64Value(2); + value::ValueGuard vgLow(lowTag, lowVal); + const auto [highTag, highVal] = makeInt64Value(5); + value::ValueGuard vgHigh(highTag, highVal); + + const double expectedCard = estimateCardRange(estimator, + false /*includeScalar*/, + false /*lowInclusive*/, + lowTag, + lowVal, + false /*highInclusive*/, + highTag, + highVal); + + ASSERT_APPROX_EQUAL(1.76505, expectedCard, kTolerance); + ASSERT_EQ(3, actualCard); + } +} + +} // namespace +} // namespace mongo::ce::statistics diff --git a/src/mongo/db/query/ce/maxdiff_test_utils.cpp b/src/mongo/db/query/ce/maxdiff_test_utils.cpp new file mode 100644 index 00000000000..5dfb5b105de --- /dev/null +++ b/src/mongo/db/query/ce/maxdiff_test_utils.cpp @@ -0,0 +1,145 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#include "mongo/db/query/ce/maxdiff_test_utils.h" + +#include "mongo/db/query/ce/array_histogram.h" +#include "mongo/db/query/ce/max_diff.h" + +namespace mongo::ce { + +ScalarHistogram createHistogram(const std::vector<BucketData>& data) { + sbe::value::Array array; + for (const auto& item : data) { + const auto [tag, val] = makeInt64Value(item._v); + array.push_back(tag, val); + } + + value::Array bounds; + std::vector<Bucket> buckets; + + double cumulativeFreq = 0.0; + double cumulativeNDV = 0.0; + + for (size_t i = 0; i < data.size(); i++) { + const auto [tag, val] = array.getAt(i); + bounds.push_back(tag, val); + + const auto& item = data.at(i); + cumulativeFreq += item._equalFreq + item._rangeFreq; + cumulativeNDV += item._ndv + 1.0; + buckets.emplace_back( + item._equalFreq, item._rangeFreq, cumulativeFreq, item._ndv, cumulativeNDV); + } + + return {std::move(bounds), std::move(buckets)}; +} + + +static std::vector<std::string> convertToJSON(const std::vector<SBEValue>& input) { + std::vector<std::string> result; + + for (size_t i = 0; i < input.size(); i++) { + const auto [objTag, objVal] = value::makeNewObject(); + value::ValueGuard vg(objTag, objVal); + + const auto [tag, val] = input[i].get(); + // Copy the value because objVal owns its value, and the ValueGuard releases not only + // objVal, but also its Value (in the case below - copyVal). + const auto [copyTag, copyVal] = value::copyValue(tag, val); + value::getObjectView(objVal)->push_back("a", copyTag, copyVal); + + std::ostringstream os; + os << std::make_pair(objTag, objVal); + result.push_back(os.str()); + } + + return result; +} + +size_t getActualCard(OperationContext* opCtx, + const std::vector<SBEValue>& input, + const std::string& query) { + return mongo::optimizer::runPipeline(opCtx, query, convertToJSON(input)).size(); +} + +std::string makeMatchExpr(const SBEValue& val, EstimationType cmpOp) { + std::stringstream matchExpr; + std::string cmpOpName = estimationTypeName.at(cmpOp); + matchExpr << "[{$match: {a: {$" << cmpOpName << ": " << val.get() << "}}}]"; + return matchExpr.str(); +} + +const ScalarHistogram makeHistogram(std::vector<SBEValue>& randData, size_t nBuckets) { + sortValueVector(randData); + const DataDistribution& dataDistrib = getDataDistribution(randData); + return genMaxDiffHistogram(dataDistrib, nBuckets); +} + +std::string printValueArray(const std::vector<SBEValue>& values) { + std::stringstream strStream; + for (size_t i = 0; i < values.size(); ++i) { + strStream << " " << values[i].get(); + } + return strStream.str(); +} + +std::string plotArrayEstimator(const ArrayHistogram& estimator, const std::string& header) { + std::ostringstream os; + os << header << "\n"; + if (!estimator.getScalar().empty()) { + os << "Scalar histogram:\n" << estimator.getScalar().plot(); + } + if (!estimator.getArrayUnique().empty()) { + os << "Array unique histogram:\n" << estimator.getArrayUnique().plot(); + } + if (!estimator.getArrayMin().empty()) { + os << "Array min histogram:\n" << estimator.getArrayMin().plot(); + } + if (!estimator.getArrayMax().empty()) { + os << "Array max histogram:\n" << estimator.getArrayMax().plot(); + } + if (!estimator.getTypeCounts().empty()) { + os << "Per scalar data type value counts: "; + for (auto tagCount : estimator.getTypeCounts()) { + os << tagCount.first << "=" << tagCount.second << " "; + } + } + if (!estimator.getArrayTypeCounts().empty()) { + os << "\nPer array data type value counts: "; + for (auto tagCount : estimator.getArrayTypeCounts()) { + os << tagCount.first << "=" << tagCount.second << " "; + } + } + os << "\n"; + + return os.str(); +} + +} // namespace mongo::ce diff --git a/src/mongo/db/query/ce/maxdiff_test_utils.h b/src/mongo/db/query/ce/maxdiff_test_utils.h new file mode 100644 index 00000000000..e95aaf78315 --- /dev/null +++ b/src/mongo/db/query/ce/maxdiff_test_utils.h @@ -0,0 +1,88 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#pragma once + +#include <string> +#include <vector> + + +#include "mongo/db/exec/sbe/abt/sbe_abt_test_util.h" +#include "mongo/db/exec/sbe/values/value.h" +#include "mongo/db/query/ce/histogram_estimation.h" +#include "mongo/db/query/ce/scalar_histogram.h" +#include "mongo/db/query/ce/value_utils.h" + +namespace mongo::ce { + +class ArrayHistogram; + +struct BucketData { + int _v; + double _equalFreq; + double _rangeFreq; + double _ndv; +}; + +/** + Convert an array of bucket data into a histogram + */ +ScalarHistogram createHistogram(const std::vector<BucketData>& data); + +/** + Given a list of SBE values and a query, create a collection containing the data, + and count the results from the supplied query. + */ +size_t getActualCard(OperationContext* opCtx, + const std::vector<SBEValue>& input, + const std::string& query); + +/** + Given a value and a comparison operator, generate a match expression reflecting + x cmpOp val. +*/ +std::string makeMatchExpr(const SBEValue& val, EstimationType cmpOp); + +/** + Given a vector of values, create a histogram reflection the distribution of the vector + with the supplied number of buckets. +*/ +const ScalarHistogram makeHistogram(std::vector<SBEValue>& randData, size_t nBuckets); + +/** + Serialize a vector of values. +*/ +std::string printValueArray(const std::vector<SBEValue>& values); + +/** + Plot a set of statistics as stored in ArrayHistogram. +*/ +std::string plotArrayEstimator(const ArrayHistogram& estimator, const std::string& header); + +} // namespace mongo::ce diff --git a/src/mongo/db/query/ce/rand_utils.cpp b/src/mongo/db/query/ce/rand_utils.cpp new file mode 100644 index 00000000000..e4c4a75616d --- /dev/null +++ b/src/mongo/db/query/ce/rand_utils.cpp @@ -0,0 +1,308 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#include <algorithm> +#include <cstddef> +#include <string> +#include <vector> + +#include "mongo/db/query/ce/rand_utils.h" + +#include "mongo/db/exec/sbe/values/value.h" +#include "mongo/util/assert_util.h" + +namespace mongo::ce { + +const std::string DatasetDescriptor::_alphabet = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + +DatasetDescriptor::DatasetDescriptor(const DataTypeDistribution& dataTypeDistribution, + size_t intNDV, + int minInt, + int maxInt, + size_t strNDV, + size_t minStrLen, + size_t maxStrLen, + std::shared_ptr<DatasetDescriptor> nestedDataDescriptor, + double reuseScalarsRatio, + size_t arrNDV, + size_t minArrLen, + size_t maxArrLen) + : _gen{42}, + _reuseScalarsRatio(reuseScalarsRatio), + _intNDV(std::min(intNDV, static_cast<size_t>(std::abs(maxInt - minInt)))), + _uniformIntDist{minInt, maxInt}, + _arrNDV(arrNDV), + _uniformArrSizeDist{minArrLen, maxArrLen}, + _nestedDataDescriptor(nestedDataDescriptor) { + uassert(6660520, "Maximum integer number must be >= the minimum one.", (maxInt >= minInt)); + uassert(6660521, "Maximum string size must be >= the minimum one.", (maxStrLen >= minStrLen)); + uassert(6660522, + "Array specs must be 0 if there is no array data descriptor.", + _nestedDataDescriptor || (arrNDV == 0 && minArrLen == 0 && maxArrLen == 0)); + uassert(6660523, + "Nested arrays requires sensible array lengths", + !_nestedDataDescriptor || maxArrLen >= minArrLen); + uassert(6660524, "Recursive descriptors are not allowed.", nestedDataDescriptor.get() != this); + uassert(6660525, + "reuseScalarsRatio is a probability, must be in [0, 1].", + reuseScalarsRatio >= 0 && reuseScalarsRatio <= 1.0); + + // Compute absolute ranges given relative weights of each value type. + double sumWeights = 0; + for (const auto& weightedType : dataTypeDistribution) { + sumWeights += weightedType.second; + } + double sumRelativeWeights = 0; + auto lastKey = dataTypeDistribution.crbegin()->first; + for (auto it = dataTypeDistribution.cbegin(); it != dataTypeDistribution.cend(); ++it) { + const auto weightedType = *it; + if (weightedType.first != lastKey) { + sumRelativeWeights += weightedType.second / sumWeights; + uassert(6660526, "The sum of weights can't be >= 1", sumRelativeWeights < 1); + } else { + // Due to rounding errors the last relative weight may not be exactly 1.0. Set it + // to 1.0. + sumRelativeWeights = 1.0; + } + _dataTypeDistribution.emplace(sumRelativeWeights, weightedType.first); + } + + // Generate a set of random integers. + mongo::stdx::unordered_set<int> tmpIntSet; + tmpIntSet.reserve(_intNDV); + if (_intNDV == intNDV) { + for (int i = minInt; i <= maxInt; ++i) { + tmpIntSet.insert(i); // This is a dense set of all ints the range. + } + } else { + size_t randCount = 0; + while (tmpIntSet.size() < _intNDV && randCount < 10 * _intNDV) { + int randInt = _uniformIntDist(_gen); + ++randCount; + tmpIntSet.insert(randInt); + } + } + uassert( + 6660527, "Too few integers generated.", (double)tmpIntSet.size() / (double)_intNDV > 0.99); + _intSet.reserve(tmpIntSet.size()); + _intSet.insert(_intSet.end(), tmpIntSet.begin(), tmpIntSet.end()); + _uniformIntIdxDist.param( + std::uniform_int_distribution<size_t>::param_type(0, _intSet.size() - 1)); + + // Generate a set of random strings with random sizes so that each string can be chosen + // multiple times in the test data set. + _stringSet.reserve(strNDV); + std::uniform_int_distribution<size_t> uniformStrSizeDistr{minStrLen, maxStrLen}; + for (size_t i = 0; i < strNDV; ++i) { + size_t len = uniformStrSizeDistr(_gen); + const auto randStr = genRandomString(len); + _stringSet.push_back(randStr); + } + _uniformStrIdxDist.param( + std::uniform_int_distribution<size_t>::param_type(0, _stringSet.size() - 1)); + + // Generate a set of random arrays that are chosen from when generating array data. + fillRandomArraySet(); +} + +std::vector<SBEValue> DatasetDescriptor::genRandomDataset(size_t nElems, + DatasetDescriptor* parentDesc) { + std::vector<SBEValue> randValues; + randValues.reserve(nElems); + DatasetDescriptor* curDesc = this; + + if (parentDesc) { + double reuseProb = _uniformRandProbability(_gen); + if (reuseProb < parentDesc->_reuseScalarsRatio) { + curDesc = parentDesc; + } + } + + for (size_t i = 0; i < nElems; ++i) { + // Get the data type of the current value to be generated. + value::TypeTags genTag = this->getRandDataType(); + // Generate a random value of the corresponding type. + switch (genTag) { + case value::TypeTags::NumberInt64: { + size_t idx = curDesc->_uniformIntIdxDist(_gen); + auto randInt = curDesc->_intSet.at(idx); + const auto [tag, val] = makeInt64Value(randInt); + randValues.emplace_back(tag, val); + break; + } + case value::TypeTags::StringBig: + case value::TypeTags::StringSmall: { + size_t idx = curDesc->_uniformStrIdxDist(_gen); + const auto randStr = curDesc->_stringSet.at(idx); + const auto [tag, val] = value::makeNewString(randStr); + const auto [copyTag, copyVal] = value::copyValue(tag, val); + randValues.emplace_back(copyTag, copyVal); + break; + } + case value::TypeTags::Array: { + if (_nestedDataDescriptor) { + const auto randArray = genRandomArray(); + auto [arrayTag, arrayVal] = value::makeNewArray(); + value::Array* arr = value::getArrayView(arrayVal); + for (const auto& elem : randArray) { + const auto [copyTag, copyVal] = + value::copyValue(elem.getTag(), elem.getValue()); + arr->push_back(copyTag, copyVal); + } + randValues.emplace_back(arrayTag, arrayVal); + } + break; + } + default: + uasserted(6660528, "Unsupported data type"); + } + } + + return randValues; +} + +std::string DatasetDescriptor::genRandomString(size_t len) { + std::string randStr; + randStr.reserve(len); + for (size_t i = 0; i < len; ++i) { + size_t idx = _uniformCharIdxDist(_gen); + const char ch = _alphabet[idx]; + randStr += ch; + } + + return randStr; +} + +std::vector<SBEValue> DatasetDescriptor::genRandomArray() { + uassert(6660529, + "There must be a nested data descriptor for random array generation.", + _nestedDataDescriptor); + if (_arrNDV == 0) { + size_t randArraySize = _uniformArrSizeDist(_gen); + return _nestedDataDescriptor->genRandomDataset(randArraySize, this); + } else { + size_t idx = _uniformArrIdxDist(_gen); + return _arraySet.at(idx); + } +} + +void DatasetDescriptor::fillRandomArraySet() { + for (size_t i = 0; i < _arrNDV; ++i) { + size_t randArraySize = _uniformArrSizeDist(_gen); + const auto randArray = _nestedDataDescriptor->genRandomDataset(randArraySize, this); + _arraySet.push_back(randArray); + } + + if (_arrNDV > 0) { + _uniformArrIdxDist.param( + std::uniform_int_distribution<size_t>::param_type(0, _arraySet.size() - 1)); + } +} + +///// Old implementation ////// +auto genRandomString(size_t len, std::mt19937_64& gen, size_t seed) { + std::string randStr; + randStr.reserve(len); + const constexpr char* kAlphabet = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + std::uniform_int_distribution<size_t> uniformDist{0, std::strlen(kAlphabet) - 1}; + + for (size_t i = 0; i < len; ++i) { + size_t idx = uniformDist(gen); + const char ch = kAlphabet[idx]; + randStr += ch; + } + + return randStr; +} + +std::vector<SBEValue> genRandomValueArray(size_t nElems, + double intRatio, + double strRatio, + size_t seed) { + std::vector<SBEValue> randValues; + const int intNDV = static_cast<int>(nElems) / 4; + const size_t strNDV = nElems / 5; + std::vector<std::string> stringSet; + stringSet.reserve(strNDV); + + std::mt19937_64 gen{seed}; + std::uniform_int_distribution<int> uniformDist{1, intNDV}; + + for (size_t i = 0; i < std::round(nElems * intRatio); ++i) { + const auto [tag, val] = makeInt64Value(uniformDist(gen)); + randValues.emplace_back(tag, val); + } + + // Generate a set of strings so that each string can be chosen multiple times in the test + // data set. + for (size_t i = 0; i < strNDV; ++i) { + const auto randStr = genRandomString(8, gen, seed); + stringSet.push_back(randStr); + } + + std::uniform_int_distribution<size_t> idxDistr{0, stringSet.size() - 1}; + for (size_t i = 0; i < std::round(nElems * strRatio); ++i) { + size_t idx = idxDistr(gen); + const auto randStr = stringSet[idx]; + const auto [tag, val] = value::makeNewString(randStr); + const auto [copyTag, copyVal] = value::copyValue(tag, val); + randValues.emplace_back(copyTag, copyVal); + } + + return randValues; +} + +std::vector<SBEValue> genRandomValueArrayWithArrays(const std::vector<SBEValue>& input) { + std::vector<SBEValue> result; + auto [arrayTag, arrayVal] = value::makeNewArray(); + + for (size_t i = 0; i < input.size(); i++) { + const auto v = input[i].get(); + const auto [tagCopy, valCopy] = value::copyValue(v.first, v.second); + + if (i % 10 < 5) { + // 50% of values remain scalar. + result.emplace_back(tagCopy, valCopy); + } else { + // 50% of the values are grouped into arrays of size 10. + value::Array* arr = value::getArrayView(arrayVal); + arr->push_back(tagCopy, valCopy); + if (arr->size() == 10) { + result.emplace_back(arrayTag, arrayVal); + std::tie(arrayTag, arrayVal) = value::makeNewArray(); + } + } + } + + return result; +} + +} // namespace mongo::ce diff --git a/src/mongo/db/query/ce/rand_utils.h b/src/mongo/db/query/ce/rand_utils.h new file mode 100644 index 00000000000..f7cc41c58b4 --- /dev/null +++ b/src/mongo/db/query/ce/rand_utils.h @@ -0,0 +1,167 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#pragma once + +#include <random> +#include <vector> + +#include "value_utils.h" + +namespace mongo::ce { + +class SBEValue; + +// A simple histogram describing the distribution of values of each data type. +using DataTypeDistribution = std::map<value::TypeTags, double>; + +/** + Describes the distribution of a dataset according to type and weight. Other ctor parameters + are used to describe the various data types which can be emitted and correspond to the fields + named similarly + */ +class DatasetDescriptor { +public: + DatasetDescriptor(const DataTypeDistribution& dataTypeDistribution, + size_t intNDV, + int minInt, + int maxInt, + size_t strNDV, + size_t minStrLen, + size_t maxStrLen, + std::shared_ptr<DatasetDescriptor> nestedDataDescriptor = nullptr, + double reuseScalarsRatio = 0, + size_t arrNDV = 0, + size_t minArrLen = 0, + size_t maxArrLen = 0); + + // Generate a random dataset of 'nElems' according to the data distribution characteristics in + // this object. + std::vector<SBEValue> genRandomDataset(size_t nElems, DatasetDescriptor* parentDesc = nullptr); + +private: + // Select a random value data type. + value::TypeTags getRandDataType() { + double key = _uniformRandProbability(_gen); + return (*_dataTypeDistribution.upper_bound(key)).second; + } + + // Generate a random string with size 'len'. + std::string genRandomString(size_t len); + + // Generate a random array with length determined uniformly between minArrLen and maxArrLen + std::vector<SBEValue> genRandomArray(); + + // Generate a set of random arrays that are chosen from when generating array data. + void fillRandomArraySet(); + +private: + using InternalDataTypeDistribution = std::map<double, value::TypeTags>; + /* + * General distribution charecteristics. + */ + + // Pseudo-random generator. + std::mt19937_64 _gen; + // Random probabilities. Used to: + // - Select Value data types as random indexes in '_dataTypeDistribution'. + // - Select the source of values - either existing scalars or new. + std::uniform_real_distribution<double> _uniformRandProbability{0.0, 1.0}; + // Distribution of different SBE data types. There will be %percent values of each type. + InternalDataTypeDistribution _dataTypeDistribution; + double _reuseScalarsRatio; + + /* + * Integer data parameters. + */ + + // Number of distinct integer values. + const size_t _intNDV; + // A set of integers to choose from while generating random integers. + std::vector<int> _intSet; + // Generator of random integers with uniform distribution. + std::uniform_int_distribution<int> _uniformIntDist; + // Generator of random indexes into the set of integers '_intSet'. + std::uniform_int_distribution<size_t> _uniformIntIdxDist; + + /* + * String data parameters. + */ + + // All strings draw characters from this alphabet. + static const std::string _alphabet; + // A set of random strings to choose from. In theory there can be duplicates, but this is very + // unlikely. We don't care much if there are a few duplicates anyway. + std::vector<std::string> _stringSet; + // Generator of random indexes into the set of characters '_alphabet'. + std::uniform_int_distribution<size_t> _uniformCharIdxDist{0, _alphabet.size() - 1}; + // Generator of random indexes into the set of strings '_stringSet'. + std::uniform_int_distribution<size_t> _uniformStrIdxDist; + + /* + * Array data parameters. + */ + + // Number of distinct arrays. + // TODO: currently not used. The idea is to use it in the same way as arrays - pre-generate + // '_arrNDV' arrays, then select randomly from this initial set. + size_t _arrNDV; + // Set of arrays to pick from when generating random data. + std::vector<std::vector<SBEValue>> _arraySet; + // Generator of random array sizes. + std::uniform_int_distribution<size_t> _uniformArrSizeDist; + // Descriptor of the dataset within each array. + std::shared_ptr<DatasetDescriptor> _nestedDataDescriptor; + // Generator of random indexes into the set of arrays '_arraySet'. + std::uniform_int_distribution<size_t> _uniformArrIdxDist; +}; // namespace mongo::ce + +/** + Generate a random string of length len. + * The alphabet is fixed as [0-9][a-z][A-Z] + * Characters are chosed uniformly from the alphabet + */ +auto genRandomString(size_t len, std::mt19937_64& gen, size_t seed); + +/** + Generate a uniformly random set of elements consisting of string and ints in the + requested ratio + */ +std::vector<SBEValue> genRandomValueArray(size_t nElems, + double intRatio, + double strRatio, + size_t seed); +/** + Generate a set up values consisting of half scalars, and half arrays of length 10 + + Values contained in the result will be drawn from the input vector + */ +std::vector<SBEValue> genRandomValueArrayWithArrays(const std::vector<SBEValue>& input); + +} // namespace mongo::ce diff --git a/src/mongo/db/query/ce/rand_utils_new.cpp b/src/mongo/db/query/ce/rand_utils_new.cpp new file mode 100644 index 00000000000..2dab195d7f5 --- /dev/null +++ b/src/mongo/db/query/ce/rand_utils_new.cpp @@ -0,0 +1,250 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#include <algorithm> +#include <cstddef> +#include <string> +#include <unordered_map> +#include <vector> + +#include "mongo/db/query/ce/rand_utils_new.h" + +#include "mongo/db/exec/sbe/values/value.h" +#include "mongo/util/assert_util.h" + +namespace mongo::ce { + +const std::string StrDistribution::_alphabet = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + +void DataTypeDistrNew::generate(std::vector<SBEValue>& randValues, std::mt19937_64& gen) { + if (_nullsRatio > 0 && _nullSelector(gen) < _nullsRatio) { + auto [tag, val] = makeNullValue(); + randValues.emplace_back(tag, val); + } else { + size_t idx = (*_idxDist)(gen); + const auto val = _valSet.at(idx); + auto [copyTag, copyVal] = copyValue(val.getTag(), val.getValue()); + randValues.emplace_back(copyTag, copyVal); + } +} + +void DataTypeDistrNew::generate(value::Array* randValueArray, std::mt19937_64& gen) { + if (_nullsRatio > 0 && _nullSelector(gen) < _nullsRatio) { + auto [tag, val] = makeNullValue(); + randValueArray->push_back(tag, val); + } else { + size_t idx = (*_idxDist)(gen); + const auto val = _valSet.at(idx); + auto [copyTag, copyVal] = copyValue(val.getTag(), val.getValue()); + randValueArray->push_back(copyTag, copyVal); + } +} + +IntDistribution::IntDistribution(MixedDistributionDescriptor distrDescriptor, + double weight, + size_t ndv, + int minInt, + int maxInt, + double nullsRatio) + : DataTypeDistrNew(distrDescriptor, + value::TypeTags::NumberInt64, + weight, + std::min(ndv, static_cast<size_t>(std::abs(maxInt - minInt))), + nullsRatio), + _minInt(minInt), + _maxInt(maxInt) { + uassert(6660507, "Maximum integer number must be >= the minimum one.", (maxInt >= minInt)); +} + +void IntDistribution::init(DatasetDescriptorNew* parentDesc, std::mt19937_64& gen) { + mongo::stdx::unordered_set<int> tmpIntSet; + std::uniform_int_distribution<int> uniformIntDist{_minInt, _maxInt}; + + tmpIntSet.reserve(_ndv); + if (_ndv == static_cast<size_t>(std::abs(_maxInt - _minInt))) { + // This is a dense set of all ints in the range. + for (int i = _minInt; i <= _maxInt; ++i) { + tmpIntSet.insert(i); + } + } else { + size_t randCount = 0; + while (tmpIntSet.size() < _ndv && randCount < 10 * _ndv) { + int randInt = uniformIntDist(gen); + ++randCount; + tmpIntSet.insert(randInt); + } + } + uassert(6660508, "Too few integers generated.", (double)tmpIntSet.size() / (double)_ndv > 0.99); + _valSet.reserve(tmpIntSet.size()); + for (const auto randInt : tmpIntSet) { + const auto [tag, val] = makeInt64Value(randInt); + _valSet.emplace_back(tag, val); + } + + _idxDist = MixedDistribution::make(_mixedDistrDescriptor, 0, _valSet.size() - 1); +} + +StrDistribution::StrDistribution(MixedDistributionDescriptor distrDescriptor, + double weight, + size_t ndv, + size_t minStrLen, + size_t maxStrLen, + double nullsRatio) + : DataTypeDistrNew(distrDescriptor, value::TypeTags::StringBig, weight, ndv, nullsRatio), + _minStrLen(minStrLen), + _maxStrLen(maxStrLen) { + uassert(6660509, "Maximum string size must be >= the minimum one.", (maxStrLen >= minStrLen)); +} + +void StrDistribution::init(DatasetDescriptorNew* parentDesc, std::mt19937_64& gen) { + // Generate a set of random strings with random sizes between _minStrLen and _maxStrLen. + _valSet.reserve(_ndv); + std::uniform_int_distribution<size_t> uniformStrSizeDistr{_minStrLen, _maxStrLen}; + for (size_t i = 0; i < _ndv; ++i) { + size_t len = uniformStrSizeDistr(gen); + const auto randStr = genRandomString(len, gen); + const auto [tag, val] = value::makeNewString(randStr); + _valSet.emplace_back(tag, val); + } + + _idxDist = MixedDistribution::make(_mixedDistrDescriptor, 0, _valSet.size() - 1); +} + +std::string StrDistribution::genRandomString(size_t len, std::mt19937_64& gen) { + std::string randStr; + randStr.reserve(len); + for (size_t i = 0; i < len; ++i) { + size_t idx = _uniformCharIdxDist(gen); + const char ch = _alphabet[idx]; + randStr += ch; + } + + return randStr; +} + +ArrDistribution::ArrDistribution(MixedDistributionDescriptor distrDescriptor, + double weight, + size_t ndv, + size_t minArrLen, + size_t maxArrLen, + std::unique_ptr<DatasetDescriptorNew> arrayDataDescriptor, + double reuseScalarsRatio, + double nullsRatio) + : DataTypeDistrNew(distrDescriptor, value::TypeTags::Array, weight, ndv, nullsRatio), + _uniformArrSizeDist{minArrLen, maxArrLen}, + _arrayDataDescriptor(std::move(arrayDataDescriptor)), + _reuseScalarsRatio(reuseScalarsRatio) { + uassert(6660510, + "Array specs must be 0 if there is no array data descriptor.", + _arrayDataDescriptor || (ndv == 0 && minArrLen == 0 && maxArrLen == 0)); + uassert(6660511, + "Nested arrays requires sensible array lengths.", + !_arrayDataDescriptor || maxArrLen >= minArrLen); + uassert(6660512, + "reuseScalarsRatio must be in [0, 1].", + reuseScalarsRatio >= 0 && reuseScalarsRatio <= 1.0); +} + +void ArrDistribution::init(DatasetDescriptorNew* parentDesc, std::mt19937_64& gen) { + uassert(6660513, "There must always be a parent data descriptor.", parentDesc); + + // Extract the per-type probabilities from the parent descriptor, but set the array probability + // to 0 to avoid self-recursion. + std::vector<double> parentProbabilities; + for (const auto& dtd : parentDesc->_dataTypeDistributions) { + double prob = (dtd->tag() == value::TypeTags::Array) ? 0 : dtd->weight(); + parentProbabilities.push_back(prob); + } + std::discrete_distribution<size_t> parentDataTypeSelector; + parentDataTypeSelector.param(std::discrete_distribution<size_t>::param_type( + parentProbabilities.begin(), parentProbabilities.end())); + + // Generate _ndv distinct arrays, and store them in _valSet. + for (size_t i = 0; i < _ndv; ++i) { + auto [arrayTag, arrayVal] = value::makeNewArray(); + value::Array* arr = value::getArrayView(arrayVal); + size_t randArraySize = _uniformArrSizeDist(gen); + arr->reserve(randArraySize); + // Generate the data for one random array. + for (size_t j = 0; j < randArraySize; ++j) { + DataTypeDistrNew* dtd = nullptr; + size_t idx; + double reuseParentProb = _uniformRandProbability(gen); + if (reuseParentProb < _reuseScalarsRatio) { + // Pick a random data type descriptor from the parent. + idx = parentDataTypeSelector(gen); + dtd = parentDesc->_dataTypeDistributions.at(idx).get(); + } else { + idx = _arrayDataDescriptor->_dataTypeSelector(gen); + dtd = _arrayDataDescriptor->_dataTypeDistributions.at(idx).get(); + } + dtd->generate(arr, gen); + } + _valSet.emplace_back(arrayTag, arrayVal); + } + + _idxDist = MixedDistribution::make(_mixedDistrDescriptor, 0, _valSet.size() - 1); +} + +DatasetDescriptorNew::DatasetDescriptorNew(TypeDistrVector dataTypeDistributions, + std::mt19937_64& gen) + : _dataTypeDistributions(std::move(dataTypeDistributions)), _gen{gen} { + + // The probability of each type to be chosen. Extracted into a vector in order to setup a + // discrete_distribution. + std::vector<double> probabilities; + probabilities.reserve(_dataTypeDistributions.size()); + for (auto& dtd : _dataTypeDistributions) { + dtd->init(this, gen); + probabilities.push_back(dtd->weight()); + } + _dataTypeSelector.param( + std::discrete_distribution<size_t>::param_type(probabilities.begin(), probabilities.end())); +} + +DataTypeDistrNew* DatasetDescriptorNew::getRandDataTypeDist() { + size_t idx = _dataTypeSelector(_gen); + return _dataTypeDistributions[idx].get(); +} + +std::vector<SBEValue> DatasetDescriptorNew::genRandomDataset(size_t nElems) { + std::vector<SBEValue> randValues; + randValues.reserve(nElems); + + for (size_t i = 0; i < nElems; ++i) { + DataTypeDistrNew* dtd = getRandDataTypeDist(); + dtd->generate(randValues, _gen); + } + + return randValues; +} + + +} // namespace mongo::ce diff --git a/src/mongo/db/query/ce/rand_utils_new.h b/src/mongo/db/query/ce/rand_utils_new.h new file mode 100644 index 00000000000..0420b990dce --- /dev/null +++ b/src/mongo/db/query/ce/rand_utils_new.h @@ -0,0 +1,354 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#pragma once + +#include <random> +#include <vector> + +#include "value_utils.h" + +namespace mongo::ce { + +class SBEValue; +class DatasetDescriptorNew; + +/** + * A base class for wrappers of STL random distributions that produce size_t values within a range. + * This class enables polymorphic usage of random distributions, for instance to implement a mix of + * distributions. + */ +class RandomDistribution { +public: + RandomDistribution() = default; + RandomDistribution(const RandomDistribution&) = default; + RandomDistribution(RandomDistribution&&) = default; + RandomDistribution& operator=(const RandomDistribution&) = default; + RandomDistribution& operator=(RandomDistribution&&) = default; + virtual ~RandomDistribution() = default; + + virtual size_t operator()(std::mt19937_64& gen) = 0; +}; + +/** + A uniform random distribution of size_t within a range + */ +class UniformDistr : public RandomDistribution { +public: + UniformDistr(size_t min, size_t max) : _distr{min, max}, _min(min), _max(max) {} + + size_t operator()(std::mt19937_64& gen) override { + size_t result = _distr(gen); + uassert(6660540, "Random index out of range", result >= _min && result <= _max); + return result; + } + +private: + std::uniform_int_distribution<size_t> _distr; + size_t _min; + size_t _max; +}; + +/** + * Wrapper of normal distribution that is guaranteed to produces size_t values within a certain + * range. The STL class normal_distribution takes a median and standard deviation. This class + * computes a suitable median and standard deviation from the required [min,max] boundaries. + */ +class NormalDistr : public RandomDistribution { +public: + NormalDistr(size_t min, size_t max) + : _distr{(double)(min + max) / 2.0, (double)(max - min) / 4.0}, + _backup{min, max}, + _min((double)min), + _max((double)max) {} + + size_t operator()(std::mt19937_64& gen) override { + size_t result = std::round(_distr(gen)); + size_t trials = 0; + // If the result is outside the range (an event with low probability), try 10 more times to + // get a number in the range. + while (!(result >= _min && result <= _max) && trials < 10) { + double randNum = _distr(gen); + if (randNum < _min) { + result = std::ceil(randNum); + } else if (randNum > _max) { + result = std::floor(randNum); + } else { + result = std::round(randNum); + } + ++trials; + } + if (result < _min && result > _max) { + // We couldn't generate a number in [min,max] within 10 attempts. Generate a uniform + // number. + result = _backup(gen); + } + uassert(6660541, "Random index out of range", result >= _min && result <= _max); + return result; + } + +private: + std::normal_distribution<double> _distr; + std::uniform_int_distribution<size_t> _backup; + double _min; + double _max; +}; + +enum class DistrType { kUniform, kNormal }; + +using MixedDistributionDescriptor = std::vector<std::pair<DistrType, double /*weight*/>>; + +/** + * Generator for mixed distribution, where mixing is on the type of distribution, in the + * probabilities specified in distrProbabilites + */ +class MixedDistribution { +public: + MixedDistribution(std::vector<std::unique_ptr<RandomDistribution>> distrMix, + std::vector<double>& distrProbabilities) + : _distrMix(std::move(distrMix)) { + _distDist.param(std::discrete_distribution<size_t>::param_type(distrProbabilities.begin(), + distrProbabilities.end())); + } + + static std::unique_ptr<MixedDistribution> make(MixedDistributionDescriptor& descriptor, + size_t min, + size_t max) { + std::vector<double> distrProbabilities; + std::vector<std::unique_ptr<RandomDistribution>> distrMix; + + for (const auto& [distrType, weight] : descriptor) { + distrProbabilities.push_back(weight); + switch (distrType) { + case DistrType::kUniform: + distrMix.emplace_back(std::make_unique<UniformDistr>(min, max)); + break; + case DistrType::kNormal: + distrMix.emplace_back(std::make_unique<NormalDistr>(min, max)); + break; + default: + MONGO_UNREACHABLE; + } + } + + return std::make_unique<MixedDistribution>(std::move(distrMix), distrProbabilities); + } + + size_t operator()(std::mt19937_64& gen) { + size_t distIdx = _distDist(gen); + size_t result = (*_distrMix.at(distIdx))(gen); + return result; + } + +private: + // Mix of different distributions. There can be instances of the same type of distribution, + // because they can still be defined differently. + std::vector<std::unique_ptr<RandomDistribution>> _distrMix; + // Distribution of distributions - select the current distribution with a certain probability. + std::discrete_distribution<size_t> _distDist; +}; + +/** + * Descriptor of a typed data distribution + */ +class DataTypeDistrNew { +public: + DataTypeDistrNew(MixedDistributionDescriptor distrDescriptor, + value::TypeTags tag, + double weight, + size_t ndv, + double nullsRatio = 0.0) + : _mixedDistrDescriptor(distrDescriptor), + _tag(tag), + _weight(weight), + _ndv(ndv), + _nullsRatio(nullsRatio) { + uassert(6660542, "NDV must be > 0.", ndv > 0); + uassert(6660543, "nullsRatio must be in [0, 1].", nullsRatio >= 0 && nullsRatio <= 1); + } + + virtual ~DataTypeDistrNew() = default; + + /** + * Generate all unique values that generation chooses from, and store them in '_valSet'. + * Different data types provide different implementations. + * @todo: The 'parentDesc' parameter is used only by array generation. Consider a different way + * of passing it only to that type. + */ + virtual void init(DatasetDescriptorNew* parentDesc, std::mt19937_64& gen) = 0; + + /** + * Generate a single random value, and store it in 'randValues' vector. + */ + void generate(std::vector<SBEValue>& randValues, std::mt19937_64& gen); + + /** + * Generate a single random value, and store it in 'randValueArray' array. + */ + void generate(value::Array* randValueArray, std::mt19937_64& gen); + + /** + * Custom equality comparison for storage in sets. There can be only datatype in a set. + */ + bool operator==(const DataTypeDistrNew& d) const { + return this->_tag == d._tag; + } + + value::TypeTags tag() const { + return _tag; + } + + double weight() const { + return _weight; + } + +protected: + MixedDistributionDescriptor _mixedDistrDescriptor; + value::TypeTags _tag; + // Weight that determines the probability of a value of this type. + const double _weight; + const size_t _ndv; + // A set of (randomly generated) values to choose from when generating random datasets. + std::vector<SBEValue> _valSet; + // Generator of random indexes into a set of values. + // std::uniform_int_distribution<size_t> _idxDist; + std::unique_ptr<MixedDistribution> _idxDist; + // Percent of null values in the dataset. + double _nullsRatio; + std::uniform_real_distribution<double> _nullSelector{0, 1}; + + friend class DatasetDescriptorNew; +}; + +using TypeDistrVector = std::vector<std::unique_ptr<DataTypeDistrNew>>; + +/** + * Integer data distribution. + */ +class IntDistribution : public DataTypeDistrNew { +public: + IntDistribution(MixedDistributionDescriptor distrDescriptor, + double weight, + size_t ndv, + int minInt, + int maxInt, + double nullsRatio = 0); + + /* + * Generate a set of random integers, and store them in _valSet. + */ + void init(DatasetDescriptorNew* parentDesc, std::mt19937_64& gen) override; + +protected: + int _minInt; + int _maxInt; +}; + +/** + * String data distribution. + */ +class StrDistribution : public DataTypeDistrNew { +public: + StrDistribution(MixedDistributionDescriptor distrDescriptor, + double weight, + size_t ndv, + size_t minStrLen, + size_t maxStrLen, + double nullsRatio = 0); + + /* + * Generate a set of random strings, and store them in _valSet. + */ + void init(DatasetDescriptorNew* parentDesc, std::mt19937_64& gen) override; + +protected: + std::string genRandomString(size_t len, std::mt19937_64& gen); + + size_t _minStrLen; + size_t _maxStrLen; + // All strings draw characters from this alphabet. + static const std::string _alphabet; + // Generator of random indexes into the set of characters '_alphabet'. + std::uniform_int_distribution<size_t> _uniformCharIdxDist{0, _alphabet.size() - 1}; +}; + +/** + * SBE array data distribution. + */ +class ArrDistribution : public DataTypeDistrNew { +public: + ArrDistribution(MixedDistributionDescriptor distrDescriptor, + double weight, + size_t ndv, + size_t minArrLen, + size_t maxArrLen, + std::unique_ptr<DatasetDescriptorNew> arrayDataDescriptor, + double reuseScalarsRatio = 0, + double nullsRatio = 0); + +private: + void init(DatasetDescriptorNew* parentDesc, std::mt19937_64& gen) override; + + // Generator of random array sizes. + std::uniform_int_distribution<size_t> _uniformArrSizeDist; + // Descriptor of the dataset within each array. + std::unique_ptr<DatasetDescriptorNew> _arrayDataDescriptor; + // Randomly select a parent or a child distribution when generating random + std::uniform_real_distribution<double> _uniformRandProbability{0.0, 1.0}; + double _reuseScalarsRatio; +}; + +/** + Given a list of tyoed data distibutions, this class is used to generate a vector of values + according to the distribution weights. +*/ +class DatasetDescriptorNew { +public: + DatasetDescriptorNew(TypeDistrVector dataTypeDistributions, std::mt19937_64& gen); + + // Generate a random dataset of 'nElems' according to the data distribution characteristics in + // this object. + std::vector<SBEValue> genRandomDataset(size_t nElems); + +private: + // Select a random value data type. + DataTypeDistrNew* getRandDataTypeDist(); + + // Distribution of different SBE data types. There will be %percent values of each type. + // TODO: is it a better idea to store shared_ptr or raw pointers to enable reuse? + TypeDistrVector _dataTypeDistributions; + // Pseudo-random generator. + std::mt19937_64& _gen; + // Select a random data type distribution. + std::discrete_distribution<size_t> _dataTypeSelector; + + friend class ArrDistribution; +}; + +} // namespace mongo::ce diff --git a/src/mongo/db/query/ce/value_utils.cpp b/src/mongo/db/query/ce/value_utils.cpp new file mode 100644 index 00000000000..d170eb5d6ae --- /dev/null +++ b/src/mongo/db/query/ce/value_utils.cpp @@ -0,0 +1,167 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#include "mongo/db/query/ce/value_utils.h" + +#include "mongo/db/query/ce/max_diff.h" +#include "mongo/db/query/ce/scalar_histogram.h" + +namespace mongo::ce { + +using namespace sbe; + +SBEValue::SBEValue(value::TypeTags tag, value::Value val) : _tag(tag), _val(val) {} + +SBEValue::SBEValue(std::pair<value::TypeTags, value::Value> v) : SBEValue(v.first, v.second) {} + +SBEValue::SBEValue(const SBEValue& other) { + auto [tag, val] = copyValue(other._tag, other._val); + _tag = tag; + _val = val; +} + +SBEValue::SBEValue(SBEValue&& other) { + _tag = other._tag; + _val = other._val; + + other._tag = value::TypeTags::Nothing; + other._val = 0; +} + +SBEValue::~SBEValue() { + value::releaseValue(_tag, _val); +} + +SBEValue& SBEValue::operator=(const SBEValue& other) { + value::releaseValue(_tag, _val); + + auto [tag, val] = copyValue(other._tag, other._val); + _tag = tag; + _val = val; + return *this; +} + +SBEValue& SBEValue::operator=(SBEValue&& other) { + value::releaseValue(_tag, _val); + + _tag = other._tag; + _val = other._val; + + other._tag = value::TypeTags::Nothing; + other._val = 0; + + return *this; +} + +std::pair<value::TypeTags, value::Value> SBEValue::get() const { + return std::make_pair(_tag, _val); +} + +value::TypeTags SBEValue::getTag() const { + return _tag; +} + +value::Value SBEValue::getValue() const { + return _val; +} + +const std::pair<value::TypeTags, value::Value> makeInt64Value(int v) { + return std::make_pair(value::TypeTags::NumberInt64, value::bitcastFrom<int64_t>(v)); +}; + +const std::pair<value::TypeTags, value::Value> makeNullValue() { + return std::make_pair(value::TypeTags::Null, 0); +}; + +bool sameTypeClass(value::TypeTags tag1, value::TypeTags tag2) { + if (tag1 == tag2) { + return true; + } + + static constexpr const char* kTempFieldName = "temp"; + + BSONObjBuilder minb1; + minb1.appendMinForType(kTempFieldName, value::tagToType(tag1)); + const BSONObj min1 = minb1.obj(); + + BSONObjBuilder minb2; + minb2.appendMinForType(kTempFieldName, value::tagToType(tag2)); + const BSONObj min2 = minb2.obj(); + + return min1.woCompare(min2) == 0; +} + +bool sameTypeBracket(value::TypeTags tag1, value::TypeTags tag2) { + if (tag1 == tag2) { + return true; + } + return ((value::isNumber(tag1) && value::isNumber(tag2)) || + (value::isString(tag1) && value::isString(tag2))); +} + +int32_t compareValues(value::TypeTags tag1, + + value::Value val1, + value::TypeTags tag2, + value::Value val2) { + const auto [compareTag, compareVal] = value::compareValue(tag1, val1, tag2, val2); + uassert(6660547, "Invalid comparison result", compareTag == value::TypeTags::NumberInt32); + return value::bitcastTo<int32_t>(compareVal); +} + +void sortValueVector(std::vector<SBEValue>& sortVector) { + const auto cmp = [](const SBEValue& a, const SBEValue& b) { + return compareValues(a.getTag(), a.getValue(), b.getTag(), b.getValue()) < 0; + }; + std::sort(sortVector.begin(), sortVector.end(), cmp); +} + +double valueToDouble(value::TypeTags tag, value::Value val) { + double result = 0; + if (value::isNumber(tag)) { + result = value::numericCast<double>(tag, val); + } else if (value::isString(tag)) { + const StringData sd = value::getStringView(tag, val); + + // Convert a prefix of the string to a double. + const size_t maxPrecision = std::min(sd.size(), sizeof(double)); + for (size_t i = 0; i < maxPrecision; ++i) { + const char ch = sd[i]; + const double charToDbl = ch / std::pow(2, i * 8); + result += charToDbl; + } + } else { + uassert(6844500, "Unexpected value type", false); + } + + return result; +} + + +} // namespace mongo::ce diff --git a/src/mongo/db/query/ce/value_utils.h b/src/mongo/db/query/ce/value_utils.h new file mode 100644 index 00000000000..a9d664b0b4c --- /dev/null +++ b/src/mongo/db/query/ce/value_utils.h @@ -0,0 +1,109 @@ +/** + * Copyright (C) 2022-present MongoDB, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the Server Side Public License, version 1, + * as published by MongoDB, Inc. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * Server Side Public License for more details. + * + * You should have received a copy of the Server Side Public License + * along with this program. If not, see + * <http://www.mongodb.com/licensing/server-side-public-license>. + * + * As a special exception, the copyright holders give permission to link the + * code of portions of this program with the OpenSSL library under certain + * conditions as described in each individual source file and distribute + * linked combinations including the program with the OpenSSL library. You + * must comply with the Server Side Public License in all respects for + * all of the code used other than as permitted herein. If you modify file(s) + * with this exception, you may extend this exception to your version of the + * file(s), but you are not obligated to do so. If you do not wish to do so, + * delete this exception statement from your version. If you delete this + * exception statement from all source files in the program, then also delete + * it in the license file. + */ + +#pragma once + +#include "mongo/db/exec/sbe/values/value.h" + +namespace mongo::ce { + +using namespace sbe; + +/** + Container object for SBE value/tag pairs. Supplied values are owned by this object + and are released on destruction +*/ +class SBEValue { +public: + SBEValue(value::TypeTags tag, value::Value val); + SBEValue(std::pair<value::TypeTags, value::Value> v); + ~SBEValue(); + + SBEValue(const SBEValue& other); + SBEValue(SBEValue&& other); + + SBEValue& operator=(const SBEValue& other); + SBEValue& operator=(SBEValue&& other); + + std::pair<value::TypeTags, value::Value> get() const; + value::TypeTags getTag() const; + value::Value getValue() const; + +private: + value::TypeTags _tag; + value::Value _val; +}; + +/** + Generate an SBE Value pair that represents the supplied int with + type Int64 +*/ +const std::pair<value::TypeTags, value::Value> makeInt64Value(int v); + +/** + Generate an SBE Value pair representing a BSON null value +*/ +const std::pair<value::TypeTags, value::Value> makeNullValue(); + +/** + Do the supplied type tags represent the same BSON type? +*/ +bool sameTypeClass(value::TypeTags tag1, value::TypeTags tag2); + +/** + Do the supplied type tags represent the same BSON type? + TODO: This may be the same as sameTypeClass. @timourk? +*/ +bool sameTypeBracket(value::TypeTags tag1, value::TypeTags tag2); + +/** + Compare a pair of SBE values. + + The return will be + <0 if val1 < val2 in BSON order + 0 if val1 == val2 in BSON order + >0 if val1 > val2 in BSON order +*/ +int32_t compareValues(value::TypeTags tag1, + value::Value val1, + value::TypeTags tag2, + value::Value val2); + +/** + Sort a vector of values in place in BSON order +*/ +void sortValueVector(std::vector<SBEValue>& sortVector); + +/** + Convert a value of any supported type into a double according to some metric. This + metric will be consistent with ordering in the type. +*/ +double valueToDouble(value::TypeTags tag, value::Value val); + +} // namespace mongo::ce |
