Running a simple query like
may not actually return the results in the requested order when SBE is used, large documents are present and multi-planning occurs.
The reason for this is the behavior we have at the command level for dealing with full batches. After we've pulled a document from a PlanExecutor, if it will not fit in the batch being sent to the user, we "stash" it, essentially giving it back to the PlanExecutor so that it can be consumed later.
Sadly, this stash is implemented with a queue, which means that when a document is "stashed" it is returned in FIFO order.
With SBE, this stash is pre-populated with the results gathered during multi planning. So, if a query has a non empty stash, and one of the documents does not fit into the batch, the document will be put at the end of the queue, and the ordering provided by the query plan is lost.
In the classic engine, a queue is also used for the stash, but, because the stash is never pre-populated, the it always has a size of 0 or 1. In this case, the FIFO behavior is the same as LIFO. There is a separate stash within the MULTI_PLAN stage for each candidate that is only read from. So, this bug is specific to SBE, though the logic for this in the classic engine should also be cleaned up.
Instead of using a queue for the stash, we should use a double ended list, and we should push to the front of the list when stashing a document that won't fit in the next batch.
The easiest way to expose this behavior is to query on a collection with documents that are large, since it's likely that no more than one will fit in a batch.