[SERVER-61941] $sortArray comparator does not satisfy "Compare" requirement with -1 sort Created: 07/Dec/21  Updated: 29/Oct/23  Resolved: 08/Dec/21

Status: Closed
Project: Core Server
Component/s: None
Affects Version/s: None
Fix Version/s: 5.3.0, 5.2.0-rc1

Type: Bug Priority: Major - P3
Reporter: Kyle Suarez Assignee: Andrii Dobroshynski (Inactive)
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Backports
Depends
Related
Backwards Compatibility: Fully Compatible
Operating System: ALL
Backport Requested:
v5.2
Sprint: QE 2021-12-13
Participants:
Linked BF Score: 162

 Description   

To sort an STL container with std::sort(), the custom comparator used must satisfy the Compare named requirement. Specifically,

comp(a, b): Establishes strict weak ordering relation with the following properties:

  • For all a, comp(a,a)==false

When sorting by whole values descending (specifically, sortBy: -1), we do the following negation:

    if (useWholeValue) {
        const bool ascending = ValueComparator(collator).getLessThan()(lhs, rhs);
 
        const bool reversed = (sortPattern.firstElement().number() < 0);
 
        return (reversed ? !ascending : ascending);

Simply negating ascending is not correct, because when comparing two equal values, getLessThan() should return false for both.

This logic error triggers a fatal assertion on Windows debug builds, because the MSVC STL implementation checks for the validity of the comparator.



 Comments   
Comment by Kyle Suarez [ 09/Dec/21 ]

I am updating the fix version to "5.2.0-rc1":

xerograph:~/mongo-dev/mongo ♥ git describe ae1b90d86fa2fa5e3393bae921f25767aecd9800
r5.2.0-rc0-1-gae1b90d86f

FYI server-release that PM Bot is still tagging things with the fix version "5.2.0"; I'm not sure if that's intentional after we've branched for 5.2.

Comment by Githook User [ 09/Dec/21 ]

Author:

{'name': 'Andrii Dobroshynski', 'email': 'andrii.dobroshynski@mongodb.com', 'username': 'dobroshynski'}

Message: SERVER-61941 Make $sortArray comparator satisfy "Compare" requirement with -1 sort

(cherry picked from commit 6d0d66137f0217f6f9299e4af62daa0b507e9937)
Branch: v5.2
https://github.com/mongodb/mongo/commit/ae1b90d86fa2fa5e3393bae921f25767aecd9800

Comment by Githook User [ 08/Dec/21 ]

Author:

{'name': 'Andrii Dobroshynski', 'email': 'andrii.dobroshynski@mongodb.com', 'username': 'dobroshynski'}

Message: SERVER-61941 Make $sortArray comparator satisfy "Compare" requirement with -1 sort
Branch: master
https://github.com/mongodb/mongo/commit/6d0d66137f0217f6f9299e4af62daa0b507e9937

Generated at Thu Feb 08 05:53:43 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.