-
Type:
Bug
-
Resolution: Unresolved
-
Priority:
Major - P3
-
None
-
Affects Version/s: None
-
Component/s: None
-
None
-
Query Execution
-
ALL
-
None
-
None
-
None
-
None
-
None
-
None
-
None
In $bucketAuto's $mergeObjects, the value for each field should come from the document that is last in the input, tracked by its input position. When a value arrives, we compare its position with the largest position recorded for that field and only overwrite the output if it is greater. However, the recorded position is not updated when we overwrite the value. So the stored position stays at the first one seen for that field, and later values are compared against it instead of against the latest winner. Because documents are processed in groupBy order, a document with a smaller position than the current winner, but larger than the first one seen, could overwrite the output. The merged result then depends on the groupBy order and not on the input order.
Suggested change
diff --git a/src/mongo/db/pipeline/accumulator_for_bucket_auto.cpp b/src/mongo/db/pipeline/accumulator_for_bucket_auto.cppindex 1ddf8396c8e4..1c6590256d8b 100644--- a/src/mongo/db/pipeline/accumulator_for_bucket_auto.cpp+++ b/src/mongo/db/pipeline/accumulator_for_bucket_auto.cpp@@ -479,10 +479,16 @@ void AccumulatorMergeObjectsForBucketAuto::processInternal(const Value& compound largestPositionIter->second.value() < inputPosition) { // Remember this new position, and track memory usage. const auto memUsage = sizeof(inputPosition) + input.getApproximateSize(); - _fieldPositions.emplace( - inputFieldName, - SimpleMemoryUsageTokenWith<long long>{ - SimpleMemoryUsageToken{memUsage, &_memUsageTracker}, inputPosition}); + + if (largestPositionIter == _fieldPositions.cend()) { + _fieldPositions.emplace( + inputFieldName, + SimpleMemoryUsageTokenWith<long long>{ + SimpleMemoryUsageToken{memUsage, &_memUsageTracker}, inputPosition}); + } else { + largestPositionIter->second = SimpleMemoryUsageTokenWith<long long>{ + SimpleMemoryUsageToken{memUsage, &_memUsageTracker}, inputPosition}; + } // Update the output. _output.setField(inputFieldName, std::move(inputFieldValue));