summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCheahuychou Mao <mao.cheahuychou@gmail.com>2022-09-19 23:55:21 +0000
committerEvergreen Agent <no-reply@evergreen.mongodb.com>2022-09-20 19:14:39 +0000
commit722d0d3ba9eb5579998b75f35613224f2c32efe5 (patch)
treee0891a20347551112e8beccb41fc8e791f0258e6
parent0baa1bacf682849154e1df565f0bd63ee203c8ca (diff)
downloadmongo-722d0d3ba9eb5579998b75f35613224f2c32efe5.tar.gz
SERVER-68753 Make analyzeShardKey command calculate metrics about the monotonicity
-rw-r--r--jstests/sharding/analyze_shard_key/analyze_shard_key_basic.js32
-rw-r--r--jstests/sharding/analyze_shard_key/cardinality_and_frequency_basic.js2
-rw-r--r--jstests/sharding/analyze_shard_key/libs/analyze_shard_key_util.js31
-rw-r--r--jstests/sharding/analyze_shard_key/libs/monotonicity_common.js285
-rw-r--r--jstests/sharding/analyze_shard_key/monotonicity_hashed_sharding_compound.js75
-rw-r--r--jstests/sharding/analyze_shard_key/monotonicity_hashed_sharding_non_compound.js70
-rw-r--r--jstests/sharding/analyze_shard_key/monotonicity_range_sharding_compound.js82
-rw-r--r--jstests/sharding/analyze_shard_key/monotonicity_range_sharding_non_compound.js70
-rw-r--r--src/mongo/base/error_codes.yml2
-rw-r--r--src/mongo/db/s/analyze_shard_key_cmd_util.cpp87
-rw-r--r--src/mongo/s/SConscript1
-rw-r--r--src/mongo/s/analyze_shard_key_cmd.idl13
-rw-r--r--src/mongo/s/analyze_shard_key_server_parameters.idl47
-rw-r--r--src/mongo/s/commands/cluster_analyze_shard_key_cmd.cpp98
14 files changed, 845 insertions, 50 deletions
diff --git a/jstests/sharding/analyze_shard_key/analyze_shard_key_basic.js b/jstests/sharding/analyze_shard_key/analyze_shard_key_basic.js
index 45b7339225c..5fd43533a4c 100644
--- a/jstests/sharding/analyze_shard_key/analyze_shard_key_basic.js
+++ b/jstests/sharding/analyze_shard_key/analyze_shard_key_basic.js
@@ -42,17 +42,16 @@ function testExistingUnshardedCollection(writeConn, testCases) {
if (testCase.isSupported) {
// This is an unsharded collection so in a sharded cluster it only exists on the
// primary shard.
- if (testCase.isNonShardsvrMongod || testCase.isPrimaryShardMongod ||
- testCase.isMongos) {
- assert.commandFailedWithCode(res0, ErrorCodes.InvalidOptions);
- // When there isn't an index available, the calculation of the metrics about the
- // characteristics of the shard key is skipped by design. As a result, there is no
- // "non-empty collection" check.
- assert.commandWorked(res1);
- } else {
- assert.commandFailedWithCode(res0, ErrorCodes.NamespaceNotFound);
- assert.commandFailedWithCode(res1, ErrorCodes.NamespaceNotFound);
- }
+ let expectedErrCode = (() => {
+ if (testCase.isMongos || testCase.isNonShardsvrMongod) {
+ return ErrorCodes.InvalidOptions;
+ } else if (testCase.isPrimaryShardMongod) {
+ return ErrorCodes.CollectionIsEmptyLocally;
+ }
+ return ErrorCodes.NamespaceNotFound;
+ })();
+ assert.commandFailedWithCode(res0, expectedErrCode);
+ assert.commandFailedWithCode(res1, expectedErrCode);
} else {
assert.commandFailedWithCode(res0, ErrorCodes.IllegalOperation);
assert.commandFailedWithCode(res1, ErrorCodes.IllegalOperation);
@@ -112,12 +111,11 @@ function testExistingShardedCollection(st, testCases) {
const res0 = testCase.conn.adminCommand({analyzeShardKey: ns, key: candidateKey0});
const res1 = testCase.conn.adminCommand({analyzeShardKey: ns, key: candidateKey1});
if (testCase.isSupported) {
- assert.commandFailedWithCode(res, ErrorCodes.InvalidOptions);
- assert.commandFailedWithCode(res0, ErrorCodes.InvalidOptions);
- // When there isn't an index available, the calculation of the metrics about the
- // characteristics of the shard key is skipped by design. As a result, there is no
- // "non-empty collection" check.
- assert.commandWorked(res1);
+ const expectedErrCode =
+ testCase.isMongos ? ErrorCodes.InvalidOptions : ErrorCodes.CollectionIsEmptyLocally;
+ assert.commandFailedWithCode(res, expectedErrCode);
+ assert.commandFailedWithCode(res0, expectedErrCode);
+ assert.commandFailedWithCode(res1, expectedErrCode);
} else {
assert.commandFailedWithCode(res, ErrorCodes.IllegalOperation);
assert.commandFailedWithCode(res0, ErrorCodes.IllegalOperation);
diff --git a/jstests/sharding/analyze_shard_key/cardinality_and_frequency_basic.js b/jstests/sharding/analyze_shard_key/cardinality_and_frequency_basic.js
index 10142d63280..846f2ff70c1 100644
--- a/jstests/sharding/analyze_shard_key/cardinality_and_frequency_basic.js
+++ b/jstests/sharding/analyze_shard_key/cardinality_and_frequency_basic.js
@@ -113,6 +113,7 @@ function assertNoMetrics(res) {
assert(!res.hasOwnProperty("isUnique"), res);
assert(!res.hasOwnProperty("cardinality"), res);
assert(!res.hasOwnProperty("frequency"), res);
+ assert(!res.hasOwnProperty("monotonicity"), res);
}
function assertMetrics(res, {numDocs, isUnique, cardinality, frequency}) {
@@ -120,6 +121,7 @@ function assertMetrics(res, {numDocs, isUnique, cardinality, frequency}) {
assert.eq(res.isUnique, isUnique, res);
assert.eq(res.cardinality, cardinality, res);
assert.eq(bsonWoCompare(res.frequency, frequency), 0, res);
+ assert(res.hasOwnProperty("monotonicity"), res);
}
/**
diff --git a/jstests/sharding/analyze_shard_key/libs/analyze_shard_key_util.js b/jstests/sharding/analyze_shard_key/libs/analyze_shard_key_util.js
index 5a44e29c199..2a90b10e27d 100644
--- a/jstests/sharding/analyze_shard_key/libs/analyze_shard_key_util.js
+++ b/jstests/sharding/analyze_shard_key/libs/analyze_shard_key_util.js
@@ -59,6 +59,34 @@ var AnalyzeShardKeyUtil = (function() {
}
/**
+ * Returns a random integer between the given range (inclusive).
+ */
+ function getRandInteger(min, max) {
+ return Math.floor(Math.random() * (max - min + 1)) + min;
+ }
+
+ /**
+ * Returns a random element in the given array.
+ */
+ function getRandomElement(arr) {
+ return arr[getRandInteger(0, arr.length - 1)];
+ }
+
+ /**
+ * Returns the field name "<prefix>", "<prefix>.x" or "<prefix>.x.y" with roughly equal
+ * probability.
+ */
+ function getRandomFieldName(prefix) {
+ const prob = Math.random();
+ if (prob < 0.3) {
+ return prefix;
+ } else if (prob < 0.6) {
+ return prefix + ".x";
+ }
+ return prefix + ".x.y";
+ }
+
+ /**
* Enables profiling of the given database on all the given mongods.
*/
function enableProfiler(mongodConns, dbName) {
@@ -81,6 +109,9 @@ var AnalyzeShardKeyUtil = (function() {
isIdKeyPattern,
getCombinedFieldNames,
setDottedField,
+ getRandInteger,
+ getRandomElement,
+ getRandomFieldName,
enableProfiler,
disableProfiler
};
diff --git a/jstests/sharding/analyze_shard_key/libs/monotonicity_common.js b/jstests/sharding/analyze_shard_key/libs/monotonicity_common.js
new file mode 100644
index 00000000000..f1b6ba51c47
--- /dev/null
+++ b/jstests/sharding/analyze_shard_key/libs/monotonicity_common.js
@@ -0,0 +1,285 @@
+/**
+ * Defines helpers for testing that the analyzeShardKey command returns correct monotonicity
+ * metrics.
+ */
+
+load("jstests/sharding/analyze_shard_key/libs/analyze_shard_key_util.js");
+
+const kOrderTypes = [
+ {
+ name: "constant",
+ monotonicity: "not monotonic",
+ supportedFieldTypes: ["integer", "string", "date", "objectid", "uuid"]
+ },
+ {
+ name: "fluctuating",
+ monotonicity: "not monotonic",
+ supportedFieldTypes: ["integer", "string", "date", "uuid"]
+ },
+ {
+ name: "increasing",
+ monotonicity: "monotonic",
+ supportedFieldTypes: ["integer", "string", "date", "objectid"]
+ },
+
+ {
+ name: "decreasing",
+ monotonicity: "monotonic",
+ supportedFieldTypes: ["integer", "string", "date"]
+ }
+];
+
+/**
+ * Appends the field of the specified name and type to the given documents such that the field value
+ * is identical across the documents.
+ */
+function appendConstantField(docs, fieldName, fieldType) {
+ const value = (() => {
+ switch (fieldType) {
+ case "integer":
+ return 1;
+ case "string":
+ return "A1";
+ case "date":
+ return new Date();
+ case "objectid":
+ return new ObjectId();
+ case "uuid":
+ return new UUID();
+ default:
+ break;
+ }
+ throw "Unexpected field type";
+ })();
+ for (let i = 0; i < docs.length; i++) {
+ AnalyzeShardKeyUtil.setDottedField(docs[i], fieldName, value);
+ }
+}
+
+/**
+ * Appends the field of the specified name and type to the given documents such that the field value
+ * is random (i.e. fluctuating).
+ */
+function appendFluctuatingField(docs, fieldName, fieldType) {
+ const maxIntValue = docs.length;
+ const numDigits = maxIntValue.toString().length;
+
+ for (let i = 0; i < docs.length; i++) {
+ const value = (() => {
+ const intValue = AnalyzeShardKeyUtil.getRandInteger(0, maxIntValue);
+ switch (fieldType) {
+ case "integer":
+ return intValue;
+ case "string":
+ return "A" + intValue.toString().padStart(numDigits, "0");
+ case "date":
+ let dateValue = new Date(1970, 0, 1);
+ dateValue.setSeconds(intValue);
+ return dateValue;
+ case "objectid":
+ throw "Cannot have a fluctuating ObjectId";
+ case "uuid":
+ return new UUID();
+ default:
+ break;
+ }
+ throw "Unexpected field type";
+ })();
+ AnalyzeShardKeyUtil.setDottedField(docs[i], fieldName, value);
+ }
+}
+
+/**
+ * The helper for 'appendIncreasingField()' and 'appendDecreasingField()'. Appends the value
+ * returned by 'getNextValueFunc()' to the given documents in order, each value is appended to at
+ * most 'maxFrequency' documents.
+ */
+function appendDuplicatedField(docs, fieldName, getNextValueFunc, maxFrequency) {
+ let docIndex = 0;
+ while (docIndex < docs.length) {
+ const value = getNextValueFunc();
+ const frequency =
+ Math.min(docs.length - docIndex, AnalyzeShardKeyUtil.getRandInteger(1, maxFrequency));
+ for (let i = 0; i < frequency; i++) {
+ AnalyzeShardKeyUtil.setDottedField(docs[docIndex], fieldName, value);
+ docIndex++;
+ }
+ }
+}
+
+/**
+ * Appends the field of the specified name and type to the given documents such that the field value
+ * is increasing and each is duplicated at most 'maxFrequency' times.
+ */
+function appendIncreasingField(docs, fieldName, fieldType, maxFrequency) {
+ const maxIntValue = docs.length;
+ const numDigits = maxIntValue.toString().length;
+ let intValue = 0;
+
+ const getNextValueFunc = () => {
+ intValue++;
+ switch (fieldType) {
+ case "integer":
+ return intValue;
+ case "string":
+ return "A" + intValue.toString().padStart(numDigits, "0");
+ case "date":
+ let dateValue = new Date(1970, 0, 1);
+ dateValue.setSeconds(intValue);
+ return dateValue;
+ case "objectid":
+ return new ObjectId();
+ case "uuid":
+ throw "Cannot have a increasing UUID";
+ default:
+ break;
+ }
+ throw "Unexpected field type";
+ };
+
+ appendDuplicatedField(docs, fieldName, getNextValueFunc, maxFrequency);
+}
+
+/**
+ * Appends the field of the specified name and type to the given documents such that the field value
+ * is decreasing and each is duplicated at most 'maxFrequency' times.
+ */
+function appendDecreasingField(docs, fieldName, fieldType, maxFrequency) {
+ const maxIntValue = docs.length;
+ const numDigits = maxIntValue.toString().length;
+ let intValue = maxIntValue;
+
+ const getNextValueFunc = () => {
+ intValue--;
+ switch (fieldType) {
+ case "integer":
+ return intValue;
+ case "string":
+ return "A" + intValue.toString().padStart(numDigits, "0");
+ case "date":
+ let dateValue = new Date(1970, 0, 1);
+ dateValue.setSeconds(intValue);
+ return dateValue;
+ case "objectid":
+ throw "Cannot have a decreasing ObjectId";
+ case "uuid":
+ throw "Cannot have a decreasing UUID";
+ default:
+ break;
+ }
+ throw "Unexpected field type";
+ };
+
+ appendDuplicatedField(docs, fieldName, getNextValueFunc, maxFrequency);
+}
+
+/**
+ * Returns 'numDocs' documents created based on the given 'fieldOpts'.
+ */
+function makeDocuments(numDocs, fieldOpts) {
+ const docs = [];
+ for (let i = 0; i < numDocs; i++) {
+ docs.push({});
+ }
+ for (let {name, type, order, maxFrequency} of fieldOpts) {
+ switch (order) {
+ case "constant":
+ appendConstantField(docs, name, type);
+ break;
+ case "increasing":
+ appendIncreasingField(docs, name, type, maxFrequency);
+ break;
+ case "decreasing":
+ appendDecreasingField(docs, name, type, maxFrequency);
+ break;
+ case "fluctuating":
+ appendFluctuatingField(docs, name, type);
+ break;
+ default:
+ throw "Unexpected field order";
+ }
+ }
+ return docs;
+}
+
+const minNumDocs = 2500;
+const maxNumDocs = 5000;
+
+function testMonotonicity(conn, dbName, collName, currentShardKey, testCases) {
+ const ns = dbName + "." + collName;
+ const db = conn.getDB(dbName);
+ const coll = db.getCollection(collName);
+
+ testCases.forEach(testCase => {
+ const numDocs = AnalyzeShardKeyUtil.getRandInteger(minNumDocs, maxNumDocs);
+ for (let i = 0; i < testCase.fieldOpts.length; i++) {
+ const order = testCase.fieldOpts[i].order;
+ if (order == "increasing" || order == "decreasing") {
+ // Make the field have at least 15 unique values in the collection.
+ testCase.fieldOpts[i].maxFrequency =
+ AnalyzeShardKeyUtil.getRandInteger(1, numDocs / 15);
+ }
+ }
+ const fieldOpts = [...testCase.fieldOpts];
+ if (currentShardKey) {
+ for (let fieldName in currentShardKey) {
+ fieldOpts.push({name: fieldName, type: "integer", order: "fluctuating"});
+ }
+ }
+
+ jsTest.log(`Testing metrics for ${
+ tojson({dbName, collName, currentShardKey, numDocs, testCase})}`);
+
+ assert.commandWorked(coll.createIndex(testCase.indexKey));
+ const docs = makeDocuments(numDocs, fieldOpts);
+ assert.commandWorked(db.runCommand({insert: collName, documents: docs, ordered: true}));
+
+ const res =
+ assert.commandWorked(conn.adminCommand({analyzeShardKey: ns, key: testCase.shardKey}));
+
+ const listCollectionRes =
+ assert.commandWorked(db.runCommand({listCollections: 1, filter: {name: collName}}));
+ const isClusteredColl =
+ listCollectionRes.cursor.firstBatch[0].options.hasOwnProperty("clusteredIndex");
+ assert.eq(res.monotonicity, isClusteredColl ? "unknown" : testCase.expected, res);
+
+ assert.commandWorked(coll.remove({}));
+ assert.commandWorked(coll.dropIndex(testCase.indexKey));
+ for (let i = 0; i < testCase.fieldOpts.length; i++) {
+ delete testCase.fieldOpts[i].maxFrequency;
+ }
+ });
+}
+
+function testAnalyzeShardKeysUnshardedCollection(conn, testCases) {
+ const dbName = "testDbCandidateUnsharded";
+ const collName = "testColl";
+ const db = conn.getDB(dbName);
+
+ jsTest.log(`Testing analyzing a shard key for a unsharded collection: ${
+ tojsononeline({dbName, collName})}`);
+
+ testMonotonicity(conn, dbName, collName, null /* currentShardKey */, testCases);
+ assert.commandWorked(db.dropDatabase());
+}
+
+function testAnalyzeShardKeysShardedCollection(st, testCases) {
+ const dbName = "testDbCandidateSharded";
+ const collName = "testColl";
+ const ns = dbName + "." + collName;
+ const currentShardKey = {skey: 1};
+ const currentShardKeySplitPoint = {skey: 0};
+ const db = st.s.getDB(dbName);
+
+ jsTest.log(`Testing analyzing a shard key for a unsharded collection: ${
+ tojsononeline({dbName, collName})}`);
+
+ assert.commandWorked(st.s.adminCommand({enableSharding: dbName}));
+ st.ensurePrimaryShard(dbName, st.shard0.name);
+ assert.commandWorked(st.s.adminCommand({shardCollection: ns, key: currentShardKey}));
+ assert.commandWorked(st.s.adminCommand({split: ns, middle: currentShardKeySplitPoint}));
+ assert.commandWorked(st.s.adminCommand(
+ {moveChunk: ns, find: currentShardKeySplitPoint, to: st.shard1.shardName}));
+ testMonotonicity(st.s, dbName, collName, currentShardKey, testCases);
+ assert.commandWorked(db.dropDatabase());
+}
diff --git a/jstests/sharding/analyze_shard_key/monotonicity_hashed_sharding_compound.js b/jstests/sharding/analyze_shard_key/monotonicity_hashed_sharding_compound.js
new file mode 100644
index 00000000000..42f3b22fb7e
--- /dev/null
+++ b/jstests/sharding/analyze_shard_key/monotonicity_hashed_sharding_compound.js
@@ -0,0 +1,75 @@
+/**
+ * Tests that the analyzeShardKey command returns monotonicity metrics for compound shard keys that
+ * use hashed sharding.
+ *
+ * @tags: [requires_fcv_62, featureFlagAnalyzeShardKey, resource_intensive]
+ */
+(function() {
+"use strict";
+
+load("jstests/sharding/analyze_shard_key/libs/monotonicity_common.js");
+
+// Construct test cases for testing the monotonicity of compound shard keys that use hashed
+// sharding. For each test case:
+// - 'shardKey' is the shard key being analyzed.
+// - 'indexKey' is the supporting index for the shard key.
+// - 'fieldOpts' specifies the name, type and order for each field inside the documents in the
+// collection. The order refers to whether the value is constant, fluctuating, increasing or
+// decreasing.
+// - 'expected' is the expected monotonicity. Since the shard key is compound, its monotonicity is
+// determined by the monotonicity of the first non-constant shard key field. If the field is
+// hashed, then it is not monotonic since hashing guarantees randomness.
+const testCases = [];
+
+for (let orderType0 of kOrderTypes) {
+ const fieldName0 = AnalyzeShardKeyUtil.getRandomFieldName("a");
+ const fieldType0 = AnalyzeShardKeyUtil.getRandomElement(orderType0.supportedFieldTypes);
+
+ for (let orderType1 of kOrderTypes) {
+ const fieldName1 = AnalyzeShardKeyUtil.getRandomFieldName("b");
+ const fieldType1 = AnalyzeShardKeyUtil.getRandomElement(orderType1.supportedFieldTypes);
+
+ // Test compound shard key with a hashed prefix.
+ testCases.push({
+ shardKey: {[fieldName0]: "hashed", [fieldName1]: 1},
+ indexKey: {[fieldName0]: "hashed", [fieldName1]: 1},
+ fieldOpts: [
+ {name: fieldName0, type: fieldType0, order: orderType0.name},
+ {name: fieldName1, type: fieldType1, order: orderType1.name}
+ ],
+ expected: orderType0.name == "constant" ? orderType1.monotonicity : "not monotonic"
+ });
+
+ // Test compound shard key without a hashed prefix.
+ testCases.push({
+ shardKey: {[fieldName0]: 1, [fieldName1]: "hashed"},
+ indexKey: {[fieldName0]: 1, [fieldName1]: "hashed"},
+ fieldOpts: [
+ {name: fieldName0, type: fieldType0, order: orderType0.name},
+ {name: fieldName1, type: fieldType1, order: orderType1.name}
+ ],
+ expected: orderType0.monotonicity
+ });
+ }
+}
+
+{
+ const st = new ShardingTest({shards: 2, rs: {nodes: 2}});
+
+ testAnalyzeShardKeysUnshardedCollection(st.s, testCases);
+ testAnalyzeShardKeysShardedCollection(st, testCases);
+
+ st.stop();
+}
+
+{
+ const rst = new ReplSetTest({nodes: 2});
+ rst.startSet();
+ rst.initiate();
+ const primary = rst.getPrimary();
+
+ testAnalyzeShardKeysUnshardedCollection(primary, testCases);
+
+ rst.stopSet();
+}
+})();
diff --git a/jstests/sharding/analyze_shard_key/monotonicity_hashed_sharding_non_compound.js b/jstests/sharding/analyze_shard_key/monotonicity_hashed_sharding_non_compound.js
new file mode 100644
index 00000000000..ae0bbfe4c27
--- /dev/null
+++ b/jstests/sharding/analyze_shard_key/monotonicity_hashed_sharding_non_compound.js
@@ -0,0 +1,70 @@
+/**
+ * Tests that the analyzeShardKey command returns monotonicity metrics for non-compound shard keys
+ * that use hashed sharding.
+ *
+ * @tags: [requires_fcv_62, featureFlagAnalyzeShardKey]
+ */
+(function() {
+"use strict";
+
+load("jstests/sharding/analyze_shard_key/libs/monotonicity_common.js");
+
+const testCases = [];
+
+// Construct test cases for testing the monotonicity of non-compound shard keys that use hashed
+// sharding. For each test case:
+// - 'shardKey' is the shard key being analyzed.
+// - 'indexKey' is the supporting index for the shard key.
+// - 'fieldOpts' specifies the name, type and order for each field inside the documents in the
+// collection. The order refers to whether the value is constant, fluctuating, increasing or
+// decreasing.
+// - 'expected' is the expected monotonicity.
+for (let orderType0 of kOrderTypes) {
+ const fieldName0 = AnalyzeShardKeyUtil.getRandomFieldName("a");
+ const fieldType0 = AnalyzeShardKeyUtil.getRandomElement(orderType0.supportedFieldTypes);
+
+ // Test non-compound hashed shard key.
+ testCases.push({
+ shardKey: {[fieldName0]: "hashed"},
+ indexKey: {[fieldName0]: "hashed"},
+ fieldOpts: [{name: fieldName0, type: fieldType0, order: orderType0.name}],
+ expected: "not monotonic"
+ });
+
+ for (let orderType1 of kOrderTypes) {
+ const fieldName1 = AnalyzeShardKeyUtil.getRandomFieldName("b");
+ const fieldType1 = AnalyzeShardKeyUtil.getRandomElement(orderType1.supportedFieldTypes);
+
+ // Test non-compound hashed shard key.
+ testCases.push({
+ shardKey: {[fieldName0]: "hashed"},
+ indexKey: {[fieldName0]: "hashed", [fieldName1]: 1},
+ fieldOpts: [
+ {name: fieldName0, type: fieldType0, order: orderType0.name},
+ {name: fieldName1, type: fieldType1, order: orderType1.name}
+ ],
+ expected: "not monotonic"
+ });
+ }
+}
+
+{
+ const st = new ShardingTest({shards: 2, rs: {nodes: 2}});
+
+ testAnalyzeShardKeysUnshardedCollection(st.s, testCases);
+ testAnalyzeShardKeysShardedCollection(st, testCases);
+
+ st.stop();
+}
+
+{
+ const rst = new ReplSetTest({nodes: 2});
+ rst.startSet();
+ rst.initiate();
+ const primary = rst.getPrimary();
+
+ testAnalyzeShardKeysUnshardedCollection(primary, testCases);
+
+ rst.stopSet();
+}
+})();
diff --git a/jstests/sharding/analyze_shard_key/monotonicity_range_sharding_compound.js b/jstests/sharding/analyze_shard_key/monotonicity_range_sharding_compound.js
new file mode 100644
index 00000000000..f16166da462
--- /dev/null
+++ b/jstests/sharding/analyze_shard_key/monotonicity_range_sharding_compound.js
@@ -0,0 +1,82 @@
+/**
+ * Tests that the analyzeShardKey command returns monotonicity metrics for compound shard keys that
+ * use range sharding.
+ *
+ * @tags: [requires_fcv_62, featureFlagAnalyzeShardKey, resource_intensive]
+ */
+(function() {
+"use strict";
+
+load("jstests/sharding/analyze_shard_key/libs/monotonicity_common.js");
+
+// Construct test cases for testing the monotonicity of compound shard keys that use range sharding.
+// For each test case:
+// - 'shardKey' is the shard key being analyzed.
+// - 'indexKey' is the supporting index for the shard key.
+// - 'fieldOpts' specifies the name, type and order for each field inside the documents in the
+// collection. The order refers to whether the value is constant, fluctuating, increasing or
+// decreasing.
+// - 'expected' is the expected monotonicity. Since the shard key is compound, its monotonicity is
+// determined by the monotonicity of the first non-constant shard key field.
+const testCases = [];
+
+for (let orderType0 of kOrderTypes) {
+ const fieldName0 = AnalyzeShardKeyUtil.getRandomFieldName("a");
+ const fieldType0 = AnalyzeShardKeyUtil.getRandomElement(orderType0.supportedFieldTypes);
+
+ for (let orderType1 of kOrderTypes) {
+ const fieldName1 = AnalyzeShardKeyUtil.getRandomFieldName("b");
+ const fieldType1 = AnalyzeShardKeyUtil.getRandomElement(orderType1.supportedFieldTypes);
+
+ // Test compound shard key with a shard key index.
+ testCases.push({
+ shardKey: {[fieldName0]: 1, [fieldName1]: 1},
+ indexKey: {[fieldName0]: 1, [fieldName1]: 1},
+ fieldOpts: [
+ {name: fieldName0, type: fieldType0, order: orderType0.name},
+ {name: fieldName1, type: fieldType1, order: orderType1.name}
+ ],
+ expected: orderType0.name == "constant" ? orderType1.monotonicity
+ : orderType0.monotonicity
+ });
+
+ for (let orderType2 of kOrderTypes) {
+ const fieldName2 = AnalyzeShardKeyUtil.getRandomFieldName("c");
+ const fieldType2 = AnalyzeShardKeyUtil.getRandomElement(orderType2.supportedFieldTypes);
+
+ // Test compound shard key with a compound shard key prefixed index.
+ testCases.push({
+ shardKey: {[fieldName0]: 1, [fieldName1]: 1},
+ indexKey: {[fieldName0]: 1, [fieldName1]: 1, [fieldName2]: 1},
+ fieldOpts: [
+ {name: fieldName0, type: fieldType0, order: orderType0.name},
+ {name: fieldName1, type: fieldType1, order: orderType1.name},
+ {name: fieldName2, type: fieldType2, order: orderType2.name}
+ ],
+ expected: orderType0.name == "constant" ? orderType1.monotonicity
+ : orderType0.monotonicity
+ });
+ }
+ }
+}
+
+{
+ const st = new ShardingTest({shards: 2, rs: {nodes: 2}});
+
+ testAnalyzeShardKeysUnshardedCollection(st.s, testCases);
+ testAnalyzeShardKeysShardedCollection(st, testCases);
+
+ st.stop();
+}
+
+{
+ const rst = new ReplSetTest({nodes: 2});
+ rst.startSet();
+ rst.initiate();
+ const primary = rst.getPrimary();
+
+ testAnalyzeShardKeysUnshardedCollection(primary, testCases);
+
+ rst.stopSet();
+}
+})();
diff --git a/jstests/sharding/analyze_shard_key/monotonicity_range_sharding_non_compound.js b/jstests/sharding/analyze_shard_key/monotonicity_range_sharding_non_compound.js
new file mode 100644
index 00000000000..526f920a68b
--- /dev/null
+++ b/jstests/sharding/analyze_shard_key/monotonicity_range_sharding_non_compound.js
@@ -0,0 +1,70 @@
+/**
+ * Tests that the analyzeShardKey command returns monotonicity metrics for non-compound shard keys
+ * that use range sharding.
+ *
+ * @tags: [requires_fcv_62, featureFlagAnalyzeShardKey]
+ */
+(function() {
+"use strict";
+
+load("jstests/sharding/analyze_shard_key/libs/monotonicity_common.js");
+
+const testCases = [];
+
+// Construct test cases for testing the monotonicity of non-compound shard keys that use range
+// sharding. For each test case:
+// - 'shardKey' is the shard key being analyzed.
+// - 'indexKey' is the supporting index for the shard key.
+// - 'fieldOpts' specifies the name, type and order for each field inside the documents in the
+// collection. The order refers to whether the value is constant, fluctuating, increasing or
+// decreasing.
+// - 'expected' is the expected monotonicity.
+for (let orderType0 of kOrderTypes) {
+ const fieldName0 = AnalyzeShardKeyUtil.getRandomFieldName("a");
+ const fieldType0 = AnalyzeShardKeyUtil.getRandomElement(orderType0.supportedFieldTypes);
+
+ // Test non-compound shard key with a shard key index.
+ testCases.push({
+ shardKey: {[fieldName0]: 1},
+ indexKey: {[fieldName0]: 1},
+ fieldOpts: [{name: fieldName0, type: fieldType0, order: orderType0.name}],
+ expected: orderType0.monotonicity
+ });
+
+ for (let orderType1 of kOrderTypes) {
+ const fieldName1 = AnalyzeShardKeyUtil.getRandomFieldName("b");
+ const fieldType1 = AnalyzeShardKeyUtil.getRandomElement(orderType1.supportedFieldTypes);
+
+ // Test non-compound shard key with a compound shard key prefixed index.
+ testCases.push({
+ shardKey: {[fieldName0]: 1},
+ indexKey: {[fieldName0]: 1, [fieldName1]: 1},
+ fieldOpts: [
+ {name: fieldName0, type: fieldType0, order: orderType0.name},
+ {name: fieldName1, type: fieldType1, order: orderType1.name}
+ ],
+ expected: orderType0.monotonicity
+ });
+ }
+}
+
+{
+ const st = new ShardingTest({shards: 2, rs: {nodes: 2}});
+
+ testAnalyzeShardKeysUnshardedCollection(st.s, testCases);
+ testAnalyzeShardKeysShardedCollection(st, testCases);
+
+ st.stop();
+}
+
+{
+ const rst = new ReplSetTest({nodes: 2});
+ rst.startSet();
+ rst.initiate();
+ const primary = rst.getPrimary();
+
+ testAnalyzeShardKeysUnshardedCollection(primary, testCases);
+
+ rst.stopSet();
+}
+})();
diff --git a/src/mongo/base/error_codes.yml b/src/mongo/base/error_codes.yml
index 4234bdfe85b..c2e8fcd1a5d 100644
--- a/src/mongo/base/error_codes.yml
+++ b/src/mongo/base/error_codes.yml
@@ -494,6 +494,8 @@ error_codes:
- {code: 382, name: RemoteCommandExecutionError, extra: RemoteCommandExecutionErrorInfo, categories: [InternalOnly]}
+ - {code: 383, name: CollectionIsEmptyLocally, categories: [InternalOnly]}
+
# Error codes 4000-8999 are reserved.
# Non-sequential error codes for compatibility only)
diff --git a/src/mongo/db/s/analyze_shard_key_cmd_util.cpp b/src/mongo/db/s/analyze_shard_key_cmd_util.cpp
index 4ed56091ddc..766e78cb228 100644
--- a/src/mongo/db/s/analyze_shard_key_cmd_util.cpp
+++ b/src/mongo/db/s/analyze_shard_key_cmd_util.cpp
@@ -29,13 +29,18 @@
#include "mongo/platform/basic.h"
+#include <boost/math/statistics/bivariate_statistics.hpp>
+
+#include "mongo/db/bson/dotted_path_support.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/pipeline/aggregate_command_gen.h"
+#include "mongo/db/query/internal_plans.h"
#include "mongo/db/s/analyze_shard_key_cmd_util.h"
#include "mongo/db/s/shard_key_index_util.h"
#include "mongo/logv2/log.h"
#include "mongo/rpc/factory.h"
+#include "mongo/s/analyze_shard_key_server_parameters_gen.h"
#include "mongo/s/grid.h"
#include "mongo/s/query/cluster_aggregate.h"
#include "mongo/s/service_entry_point_mongos.h"
@@ -319,6 +324,81 @@ CardinalityFrequencyMetricsBundle calculateCardinalityAndFrequency(OperationCont
return bundle;
}
+/**
+ * Returns the monotonicity metrics for the given shard key, i.e. whether the value of the given
+ * shard key is monotonically changing in insertion order. If the collection is clustered or the
+ * shard key does not have a supporting index, returns 'unknown'.
+ */
+MonotonicityTypeEnum calculateMonotonicity(OperationContext* opCtx,
+ const CollectionPtr& collection,
+ const BSONObj& shardKey) {
+ if (collection->isClustered()) {
+ return MonotonicityTypeEnum::kUnknown;
+ }
+
+ if (KeyPattern::isHashedKeyPattern(shardKey) && shardKey.nFields() == 1) {
+ return MonotonicityTypeEnum::kNotMonotonic;
+ }
+
+ auto index = findShardKeyPrefixedIndex(opCtx,
+ collection,
+ collection->getIndexCatalog(),
+ shardKey,
+ /*requireSingleKey=*/true);
+
+ if (!index) {
+ return MonotonicityTypeEnum::kUnknown;
+ }
+ // Non-clustered indexes always have an associated IndexDescriptor.
+ invariant(index->descriptor());
+
+ std::vector<int64_t> recordIds;
+ BSONObj prevKey;
+
+ KeyPattern indexKeyPattern(index->keyPattern());
+ auto exec = InternalPlanner::indexScan(opCtx,
+ &collection,
+ index->descriptor(),
+ indexKeyPattern.globalMin(),
+ indexKeyPattern.globalMax(),
+ BoundInclusion::kExcludeBothStartAndEndKeys,
+ PlanYieldPolicy::YieldPolicy::INTERRUPT_ONLY);
+ try {
+ RecordId recordId;
+ BSONObj recordVal;
+ while (PlanExecutor::ADVANCED == exec->getNext(&recordVal, &recordId)) {
+ auto currentKey = dotted_path_support::extractElementsBasedOnTemplate(
+ recordVal.replaceFieldNames(shardKey), shardKey);
+ if (SimpleBSONObjComparator::kInstance.evaluate(prevKey == currentKey)) {
+ continue;
+ }
+ prevKey = currentKey;
+ recordIds.push_back(recordId.getLong());
+ }
+ } catch (DBException& ex) {
+ LOGV2_WARNING(6875301, "Internal error while reading", "ns"_attr = collection->ns());
+ ex.addContext("Executor error while reading during 'analyzeShardKey' command");
+ throw;
+ }
+
+ invariant(recordIds.size() > 0);
+
+ auto coefficient = [&] {
+ auto& y = recordIds;
+ std::vector<int64_t> x(y.size());
+ std::iota(x.begin(), x.end(), 1);
+ return boost::math::statistics::correlation_coefficient<std::vector<int64_t>>(x, y);
+ }();
+ auto coefficientThreshold = gMonotonicityCorrelationCoefficientThreshold.load();
+ LOGV2(6875302,
+ "Calculating monotonicity",
+ "coefficient"_attr = coefficient,
+ "coefficientThreshold"_attr = coefficientThreshold);
+
+ return abs(coefficient) >= coefficientThreshold ? MonotonicityTypeEnum::kMonotonic
+ : MonotonicityTypeEnum::kNotMonotonic;
+}
+
} // namespace
KeyCharacteristicsMetrics calculateKeyCharacteristicsMetrics(OperationContext* opCtx,
@@ -335,6 +415,12 @@ KeyCharacteristicsMetrics calculateKeyCharacteristicsMetrics(OperationContext* o
str::stream() << "Cannot analyze a shard key for a non-existing collection",
collection);
+ uassert(serverGlobalParams.clusterRole == ClusterRole::ShardServer
+ ? ErrorCodes::CollectionIsEmptyLocally
+ : ErrorCodes::InvalidOptions,
+ "Cannot analyze a shard key for an empty collection",
+ collection->numRecords(opCtx) > 0);
+
auto indexSpec = findCompatiblePrefixedIndex(
opCtx, *collection, collection->getIndexCatalog(), shardKeyBson);
@@ -345,6 +431,7 @@ KeyCharacteristicsMetrics calculateKeyCharacteristicsMetrics(OperationContext* o
indexKeyBson = indexSpec->keyPattern.getOwned();
metrics.setIsUnique(shardKeyBson.nFields() == indexKeyBson.nFields() ? indexSpec->isUnique
: false);
+ metrics.setMonotonicity(calculateMonotonicity(opCtx, *collection, shardKeyBson));
}
auto bundle = calculateCardinalityAndFrequency(
diff --git a/src/mongo/s/SConscript b/src/mongo/s/SConscript
index 6997dfdbc58..c99dd308612 100644
--- a/src/mongo/s/SConscript
+++ b/src/mongo/s/SConscript
@@ -137,6 +137,7 @@ env.Library(
source=[
'analyze_shard_key_cmd.idl',
'analyze_shard_key_feature_flag.idl',
+ 'analyze_shard_key_server_parameters.idl',
'cannot_implicitly_create_collection_info.cpp',
'catalog/mongo_version_range.cpp',
'catalog/type_changelog.cpp',
diff --git a/src/mongo/s/analyze_shard_key_cmd.idl b/src/mongo/s/analyze_shard_key_cmd.idl
index 1c437d262a4..650e00d6738 100644
--- a/src/mongo/s/analyze_shard_key_cmd.idl
+++ b/src/mongo/s/analyze_shard_key_cmd.idl
@@ -33,6 +33,15 @@ imports:
- "mongo/db/basic_types.idl"
- "mongo/db/keypattern.idl"
+enums:
+ MonotonicityType:
+ description: "The monotonicity type of a shard key."
+ type: string
+ values:
+ kMonotonic: "monotonic"
+ kNotMonotonic: "not monotonic"
+ kUnknown: "unknown"
+
structs:
percentileMetrics:
description: "The percentile metrics for a set of non-negative integers."
@@ -76,6 +85,10 @@ structs:
description: "The percentile metrics for the number of documents for each distinct shard key
value."
optional: true
+ monotonicity:
+ type: MonotonicityType
+ description: "The monotonicity of the shard key values in insertion order."
+ optional: true
analyzeShardKeyResponse:
description: "The response for the 'analyzeShardKey' command."
diff --git a/src/mongo/s/analyze_shard_key_server_parameters.idl b/src/mongo/s/analyze_shard_key_server_parameters.idl
new file mode 100644
index 00000000000..22da669e452
--- /dev/null
+++ b/src/mongo/s/analyze_shard_key_server_parameters.idl
@@ -0,0 +1,47 @@
+# 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.
+#
+
+# Server parameters for the 'analyzeShardKey' command.
+
+global:
+ cpp_namespace: "mongo::analyze_shard_key"
+
+imports:
+ - "mongo/db/basic_types.idl"
+
+server_parameters:
+ monotonicityCorrelationCoefficientThreshold:
+ description: The correlation coefficient threshold used to determine if a shard key is
+ monotonically changing.
+ set_at: [startup, runtime]
+ cpp_vartype: AtomicWord<double>
+ cpp_varname: gMonotonicityCorrelationCoefficientThreshold
+ default: 0.7
+ validator:
+ gt: 0
+ lte: 1
diff --git a/src/mongo/s/commands/cluster_analyze_shard_key_cmd.cpp b/src/mongo/s/commands/cluster_analyze_shard_key_cmd.cpp
index 371f336516c..22acef5ea7f 100644
--- a/src/mongo/s/commands/cluster_analyze_shard_key_cmd.cpp
+++ b/src/mongo/s/commands/cluster_analyze_shard_key_cmd.cpp
@@ -44,15 +44,21 @@ namespace mongo {
namespace {
-ShardId getRandomOwningShardId(const ChunkManager& cm, const CachedDatabaseInfo& dbInfo) {
+/**
+ * Returns a new command object with shard version and/or database version appended to it based on
+ * the given routing info.
+ */
+BSONObj makeVersionedCmdObj(const ChunkManager& cm,
+ const BSONObj& unversionedCmdObj,
+ ShardId shardId) {
if (cm.isSharded()) {
- std::set<ShardId> shardIds;
- cm.getAllShardIds(&shardIds);
- auto it = shardIds.begin();
- std::advance(it, std::rand() % shardIds.size());
- return *it;
+ auto placementVersion = cm.getVersion(shardId);
+ return appendShardVersion(
+ unversionedCmdObj,
+ ShardVersion(placementVersion, CollectionIndexes(placementVersion, boost::none)));
}
- return dbInfo->getPrimary();
+ auto versionedCmdObj = appendShardVersion(unversionedCmdObj, ShardVersion::UNSHARDED());
+ return appendDbVersionIfPresent(versionedCmdObj, cm.dbVersion());
}
class AnalyzeShardKeyCmd : public TypedCommand<AnalyzeShardKeyCmd> {
@@ -68,37 +74,63 @@ public:
const auto& nss = ns();
const auto& catalogCache = Grid::get(opCtx)->catalogCache();
const auto cm = uassertStatusOK(catalogCache->getCollectionRoutingInfo(opCtx, nss));
- const auto dbInfo = uassertStatusOK(catalogCache->getDatabase(opCtx, nss.db()));
- auto shardId = getRandomOwningShardId(cm, dbInfo);
- uassert(ErrorCodes::IllegalOperation,
- "Cannot analyze a shard key for a collection on the config server",
- shardId != ShardId::kConfigServerId);
- const auto shard =
- uassertStatusOK(Grid::get(opCtx)->shardRegistry()->getShard(opCtx, shardId));
-
- auto cmdObj = CommandHelpers::filterCommandRequestForPassthrough(request().toBSON({}));
+ std::set<ShardId> candidateShardIds;
if (cm.isSharded()) {
- cmdObj = appendShardVersion(
- cmdObj,
- ShardVersion(cm.getVersion(shardId),
- CollectionIndexes(cm.getVersion(shardId), boost::none)));
+ cm.getAllShardIds(&candidateShardIds);
} else {
- cmdObj = appendShardVersion(cmdObj, ShardVersion::UNSHARDED());
- cmdObj = appendDbVersionIfPresent(cmdObj, dbInfo->getVersion());
+ candidateShardIds.insert(cm.dbPrimary());
}
- auto swResponse = shard->runCommandWithFixedRetryAttempts(
- opCtx,
- ReadPreferenceSetting{ReadPreference::SecondaryPreferred},
- NamespaceString::kAdminDb.toString(),
- cmdObj,
- Shard::RetryPolicy::kIdempotent);
- uassertStatusOK(Shard::CommandResponse::getEffectiveStatus(swResponse));
-
- auto response = AnalyzeShardKeyResponse::parse(
- IDLParserContext("clusterAnalyzeShardKey"), swResponse.getValue().response);
- return response;
+ const auto unversionedCmdObj =
+ CommandHelpers::filterCommandRequestForPassthrough(request().toBSON({}));
+ while (true) {
+ // Select a random shard.
+ invariant(!candidateShardIds.empty());
+ auto it = candidateShardIds.begin();
+ std::advance(it, std::rand() % candidateShardIds.size());
+ auto shardId = *it;
+ candidateShardIds.erase(shardId);
+
+ uassert(ErrorCodes::IllegalOperation,
+ "Cannot analyze a shard key for a collection on the config server",
+ shardId != ShardId::kConfigServerId);
+
+ // Build a versioned command for the selected shard.
+ auto versionedCmdObj = makeVersionedCmdObj(cm, unversionedCmdObj, shardId);
+
+ // Execute the command against the shard.
+ auto shard =
+ uassertStatusOK(Grid::get(opCtx)->shardRegistry()->getShard(opCtx, shardId));
+ auto swResponse = shard->runCommandWithFixedRetryAttempts(
+ opCtx,
+ ReadPreferenceSetting{ReadPreference::SecondaryPreferred},
+ NamespaceString::kAdminDb.toString(),
+ versionedCmdObj,
+ Shard::RetryPolicy::kIdempotent);
+ auto status = Shard::CommandResponse::getEffectiveStatus(swResponse);
+
+ if (status == ErrorCodes::CollectionIsEmptyLocally) {
+ uassert(ErrorCodes::InvalidOptions,
+ "Cannot analyze a shard key for an empty collection",
+ !candidateShardIds.empty());
+
+ LOGV2(6875300,
+ "Failed to analyze shard key on the selected shard since it did not "
+ "have any documents for the collection locally. Retrying on a different "
+ "shard.",
+ "nss"_attr = nss,
+ "key"_attr = request().getKey(),
+ "shardId"_attr = shardId,
+ "error"_attr = status);
+ continue;
+ }
+
+ uassertStatusOK(status);
+ auto response = AnalyzeShardKeyResponse::parse(
+ IDLParserContext("clusterAnalyzeShardKey"), swResponse.getValue().response);
+ return response;
+ }
}
private: