/
pipeline_d.cpp
2237 lines (2007 loc) · 108 KB
/
pipeline_d.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (C) 2018-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/pipeline/pipeline_d.h"
#include <algorithm>
#include <bitset>
#include <boost/cstdint.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/none.hpp>
#include <boost/optional/optional.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/smart_ptr/intrusive_ptr.hpp>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <iterator>
#include <list>
#include <string>
#include <tuple>
#include <type_traits>
#include <vector>
#include "mongo/base/error_codes.h"
#include "mongo/base/exact_cast.h"
#include "mongo/base/status.h"
#include "mongo/bson/bsonelement.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/bson/bsontypes.h"
#include "mongo/db/basic_types.h"
#include "mongo/db/catalog/index_catalog.h"
#include "mongo/db/concurrency/lock_manager_defs.h"
#include "mongo/db/concurrency/locker.h"
#include "mongo/db/exec/cached_plan.h"
#include "mongo/db/exec/collection_scan.h"
#include "mongo/db/exec/collection_scan_common.h"
#include "mongo/db/exec/document_value/document.h"
#include "mongo/db/exec/document_value/value.h"
#include "mongo/db/exec/index_scan.h"
#include "mongo/db/exec/multi_iterator.h"
#include "mongo/db/exec/multi_plan.h"
#include "mongo/db/exec/plan_stats.h"
#include "mongo/db/exec/sample_from_timeseries_bucket.h"
#include "mongo/db/exec/shard_filter.h"
#include "mongo/db/exec/shard_filterer.h"
#include "mongo/db/exec/shard_filterer_impl.h"
#include "mongo/db/exec/trial_stage.h"
#include "mongo/db/exec/unpack_timeseries_bucket.h"
#include "mongo/db/exec/working_set.h"
#include "mongo/db/feature_flag.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/index_names.h"
#include "mongo/db/matcher/expression_algo.h"
#include "mongo/db/matcher/expression_expr.h"
#include "mongo/db/matcher/extensions_callback_real.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/ops/write_ops_gen.h"
#include "mongo/db/pipeline/dependencies.h"
#include "mongo/db/pipeline/document_source.h"
#include "mongo/db/pipeline/document_source_cursor.h"
#include "mongo/db/pipeline/document_source_geo_near.h"
#include "mongo/db/pipeline/document_source_geo_near_cursor.h"
#include "mongo/db/pipeline/document_source_group.h"
#include "mongo/db/pipeline/document_source_group_base.h"
#include "mongo/db/pipeline/document_source_internal_projection.h"
#include "mongo/db/pipeline/document_source_internal_replace_root.h"
#include "mongo/db/pipeline/document_source_internal_unpack_bucket.h"
#include "mongo/db/pipeline/document_source_lookup.h"
#include "mongo/db/pipeline/document_source_match.h"
#include "mongo/db/pipeline/document_source_replace_root.h"
#include "mongo/db/pipeline/document_source_sample.h"
#include "mongo/db/pipeline/document_source_sample_from_random_cursor.h"
#include "mongo/db/pipeline/document_source_set_window_fields.h"
#include "mongo/db/pipeline/document_source_single_document_transformation.h"
#include "mongo/db/pipeline/document_source_skip.h"
#include "mongo/db/pipeline/document_source_sort.h"
#include "mongo/db/pipeline/expression.h"
#include "mongo/db/pipeline/expression_context.h"
#include "mongo/db/pipeline/inner_pipeline_stage_impl.h"
#include "mongo/db/pipeline/inner_pipeline_stage_interface.h"
#include "mongo/db/pipeline/pipeline.h"
#include "mongo/db/pipeline/search_helper.h"
#include "mongo/db/pipeline/skip_and_limit.h"
#include "mongo/db/pipeline/stage_constraints.h"
#include "mongo/db/pipeline/transformer_interface.h"
#include "mongo/db/query/canonical_query.h"
#include "mongo/db/query/collation/collator_interface.h"
#include "mongo/db/query/find_command.h"
#include "mongo/db/query/get_executor.h"
#include "mongo/db/query/index_bounds.h"
#include "mongo/db/query/parsed_distinct.h"
#include "mongo/db/query/plan_executor_factory.h"
#include "mongo/db/query/plan_executor_impl.h"
#include "mongo/db/query/plan_yield_policy.h"
#include "mongo/db/query/plan_yield_policy_remote_cursor.h"
#include "mongo/db/query/projection.h"
#include "mongo/db/query/projection_parser.h"
#include "mongo/db/query/projection_policies.h"
#include "mongo/db/query/query_decorations.h"
#include "mongo/db/query/query_feature_flags_gen.h"
#include "mongo/db/query/query_knobs_gen.h"
#include "mongo/db/query/query_planner_params.h"
#include "mongo/db/query/query_request_helper.h"
#include "mongo/db/query/query_settings.h"
#include "mongo/db/query/query_utils.h"
#include "mongo/db/query/record_id_bound.h"
#include "mongo/db/query/sort_pattern.h"
#include "mongo/db/query/stage_types.h"
#include "mongo/db/query/tailable_mode_gen.h"
#include "mongo/db/query/timeseries/bucket_spec.h"
#include "mongo/db/query/util/make_data_structure.h"
#include "mongo/db/record_id.h"
#include "mongo/db/s/collection_sharding_state.h"
#include "mongo/db/s/scoped_collection_metadata.h"
#include "mongo/db/server_options.h"
#include "mongo/db/server_parameter.h"
#include "mongo/db/server_parameter_with_storage.h"
#include "mongo/db/storage/record_store.h"
#include "mongo/db/storage/sorted_data_interface.h"
#include "mongo/db/storage/test_harness_helper.h"
#include "mongo/db/timeseries/timeseries_constants.h"
#include "mongo/db/timeseries/timeseries_gen.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/platform/compiler.h"
#include "mongo/rpc/metadata/client_metadata.h"
#include "mongo/s/query/document_source_merge_cursors.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/intrusive_counter.h"
#include "mongo/util/str.h"
#include "mongo/util/time_support.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kQuery
namespace mongo {
using boost::intrusive_ptr;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using write_ops::InsertCommandRequest;
namespace {
/**
* Helper for findSbeCompatibleStagesForPushdown() that checks whether 'stage' is a $project or
* $addFields that can be pushed down to SBE as a 'DocumentSourceInternalProjection' stage. If so,
* this returns a pointer to a constructed object of the latter type, else it returns nullptr.
*/
boost::intrusive_ptr<DocumentSource> sbeCompatibleProjectionFromSingleDocumentTransformation(
const DocumentSourceSingleDocumentTransformation& transformStage,
SbeCompatibility minRequiredCompatibility) {
InternalProjectionPolicyEnum policies;
switch (transformStage.getType()) {
case TransformerInterface::TransformerType::kExclusionProjection:
case TransformerInterface::TransformerType::kInclusionProjection:
policies = InternalProjectionPolicyEnum::kAggregate;
break;
case TransformerInterface::TransformerType::kComputedProjection:
policies = InternalProjectionPolicyEnum::kAddFields;
break;
default:
return nullptr;
}
const boost::intrusive_ptr<ExpressionContext>& expCtx = transformStage.getContext();
SbeCompatibility originalSbeCompatibility =
std::exchange(expCtx->sbeCompatibility, SbeCompatibility::fullyCompatible);
ON_BLOCK_EXIT([&] { expCtx->sbeCompatibility = originalSbeCompatibility; });
boost::intrusive_ptr<DocumentSource> projectionStage =
make_intrusive<DocumentSourceInternalProjection>(
expCtx,
transformStage.getTransformer().serializeTransformation(boost::none).toBson(),
policies);
if (expCtx->sbeCompatibility < minRequiredCompatibility) {
return nullptr;
}
return projectionStage;
}
/**
* Helper for findSbeCompatibleStagesForPushdown() that creates a
* 'DocumentSourceInternalReplaceRoot' from 'stage' if 'stage' is a '$replaceRoot' that can be
* pushed down to SBE or returns nullptr otherwise.
*/
boost::intrusive_ptr<DocumentSource> sbeCompatibleReplaceRootStage(
DocumentSourceSingleDocumentTransformation* replaceRootStage,
SbeCompatibility minRequiredCompatibility) {
if (replaceRootStage->getType() != TransformerInterface::TransformerType::kReplaceRoot) {
return nullptr;
}
const auto& replaceRootTransformation =
dynamic_cast<const ReplaceRootTransformation&>(replaceRootStage->getTransformer());
if (replaceRootTransformation.sbeCompatibility() < minRequiredCompatibility) {
return nullptr;
}
return make_intrusive<DocumentSourceInternalReplaceRoot>(
replaceRootStage->getContext(), replaceRootTransformation.getExpression());
}
// A bit field with a bool flag for each aggregation pipeline stage that can be translated to SBE.
// The flags can be used to indicate which translations are enabled and/or supported in a particular
// context.
struct CompatiblePipelineStages {
bool group : 1;
bool lookup : 1;
// The $project and $addField stages are considered the same for the purposes of SBE
// translation.
bool transform : 1;
bool match : 1;
bool unwind : 1;
bool sort : 1;
bool limitSkip : 1;
bool search : 1;
bool window : 1;
bool unpackBucket : 1;
};
// Determine if 'stage' is eligible for SBE, and if it is add it to the 'stagesForPushdown' list as
// a 'InnerPipelineStageInterface' and return true. Return false if 'stage' is ineligible, either
// because it is disallowed by 'allowedStages' or because it requires functionality that cannot be
// translated to SBE.
bool pushDownPipelineStageIfCompatible(
const OperationContext* opCtx,
const boost::intrusive_ptr<DocumentSource>& stage,
SbeCompatibility minRequiredCompatibility,
const CompatiblePipelineStages& allowedStages,
bool isLastSource,
std::vector<std::unique_ptr<InnerPipelineStageInterface>>& stagesForPushdown) {
if (auto groupStage = dynamic_cast<DocumentSourceGroup*>(stage.get())) {
if (!allowedStages.group || groupStage->doingMerge() ||
groupStage->sbeCompatibility() < minRequiredCompatibility) {
return false;
}
stagesForPushdown.emplace_back(
std::make_unique<InnerPipelineStageImpl>(groupStage, isLastSource));
return true;
} else if (auto lookupStage = dynamic_cast<DocumentSourceLookUp*>(stage.get())) {
if (!allowedStages.lookup || lookupStage->sbeCompatibility() < minRequiredCompatibility) {
return false;
}
stagesForPushdown.emplace_back(
std::make_unique<InnerPipelineStageImpl>(lookupStage, isLastSource));
return true;
} else if (auto transformStage =
dynamic_cast<DocumentSourceSingleDocumentTransformation*>(stage.get())) {
if (!allowedStages.transform) {
return false;
}
if (auto replaceRoot =
sbeCompatibleReplaceRootStage(transformStage, minRequiredCompatibility)) {
stagesForPushdown.emplace_back(
std::make_unique<InnerPipelineStageImpl>(replaceRoot, isLastSource));
return true;
} else if (auto projectionStage = sbeCompatibleProjectionFromSingleDocumentTransformation(
*transformStage, minRequiredCompatibility)) {
stagesForPushdown.emplace_back(
std::make_unique<InnerPipelineStageImpl>(projectionStage, isLastSource));
return true;
}
return false;
} else if (auto matchStage = dynamic_cast<DocumentSourceMatch*>(stage.get())) {
if (!allowedStages.match || matchStage->sbeCompatibility() < minRequiredCompatibility) {
return false;
}
stagesForPushdown.emplace_back(
std::make_unique<InnerPipelineStageImpl>(matchStage, isLastSource));
return true;
} else if (auto sortStage = dynamic_cast<DocumentSourceSort*>(stage.get())) {
if (!allowedStages.sort || !isSortSbeCompatible(sortStage->getSortKeyPattern())) {
return false;
}
stagesForPushdown.emplace_back(
std::make_unique<InnerPipelineStageImpl>(sortStage, isLastSource));
return true;
} else if (dynamic_cast<DocumentSourceLimit*>(stage.get()) ||
dynamic_cast<DocumentSourceSkip*>(stage.get())) {
if (!allowedStages.limitSkip) {
return false;
}
stagesForPushdown.push_back(
std::make_unique<InnerPipelineStageImpl>(stage.get(), isLastSource));
return true;
} else if (const auto& searchHelpers = getSearchHelpers(opCtx->getServiceContext());
searchHelpers->isSearchStage(stage.get()) ||
searchHelpers->isSearchMetaStage(stage.get())) {
if (!allowedStages.search) {
return false;
}
stagesForPushdown.emplace_back(
std::make_unique<InnerPipelineStageImpl>(stage, isLastSource));
return true;
} else if (auto windowStage =
dynamic_cast<DocumentSourceInternalSetWindowFields*>(stage.get())) {
if (!allowedStages.window || windowStage->sbeCompatibility() < minRequiredCompatibility) {
return false;
}
stagesForPushdown.emplace_back(
std::make_unique<InnerPipelineStageImpl>(windowStage, isLastSource));
return true;
} else if (auto unpackBucketStage =
dynamic_cast<DocumentSourceInternalUnpackBucket*>(stage.get())) {
if (!allowedStages.unpackBucket) {
return false;
}
stagesForPushdown.emplace_back(
std::make_unique<InnerPipelineStageImpl>(unpackBucketStage, isLastSource));
return true;
} else if (auto unwindStage = dynamic_cast<DocumentSourceUnwind*>(stage.get())) {
if (!allowedStages.unwind || unwindStage->sbeCompatibility() < minRequiredCompatibility) {
return false;
}
stagesForPushdown.emplace_back(
std::make_unique<InnerPipelineStageImpl>(unwindStage, isLastSource));
return true;
}
return false;
}
/**
* After copying as many pipeline stages as possible into the 'stagesForPushdown' pipeline, this
* second pass takes off any stages that may not benefit from execution in SBE.
*/
void reconsiderStagesForPushdown(
std::vector<std::unique_ptr<InnerPipelineStageInterface>>& stagesForPushdown) {
// Always push down the entire pipeline when possible.
if (stagesForPushdown.empty() || stagesForPushdown.back()->isLastSource()) {
return;
}
// When splitting a pipeline between SBE and Classic DocumentSource stages, there is often a
// performance penalty for executing an $addFields in SBE only to immediately translate its
// output to MutableDocument form for the Classic DocumentSource execution phase. Instead, we
// keep the $addFields as a DocumentSource.
do {
auto projectionStage = dynamic_cast<DocumentSourceInternalProjection*>(
stagesForPushdown.back()->documentSource());
if (!projectionStage ||
projectionStage->projection().type() != projection_ast::ProjectType::kAddition) {
return;
}
stagesForPushdown.pop_back();
} while (!stagesForPushdown.empty());
}
// Limit the number of aggregation pipeline stages that can be "pushed down" to the SBE stage
// builders. Compiling too many pipeline stages during stage building would overflow the call stack.
// The limit is higher for optimized builds, because optimization reduces the size of stack frames.
#ifdef MONGO_CONFIG_OPTIMIZED_BUILD
constexpr size_t kSbeMaxPipelineStages = 400;
#else
constexpr size_t kSbeMaxPipelineStages = 100;
#endif
/**
* Finds a prefix of stages from the given pipeline to prepare for pushdown into the inner query
* layer so that it can be executed using SBE.
*
* $group stages ('DocumentSourceGroup') are extracted from the pipeline when all of:
* - 'internalQueryFrameworkControl' is not set to "forceClassicEngine".
* - 'internalQuerySlotBasedExecutionDisableGroupPushdown' query knob is 'false'.
* - DocumentSourceGroup has 'doingMerge=false'.
*
* $lookup stages ('DocumentSourceLookUp') are extracted when all of:
* - 'internalQueryFrameworkControl' is not set to "forceClassicEngine".
* - 'internalQuerySlotBasedExecutionDisableLookupPushdown' query knob is 'false'.
* - The $lookup uses only the 'localField'/'foreignField' syntax (no pipelines).
* - The foreign collection is neither sharded nor a view.
*
* $project and $addFields stages (collectively 'DocumentSourceInternalProjection') are extracted
* when all of:
* - 'internalQueryFrameworkControl' is not set to "forceClassicEngine".
* - featureFlagSbeFull is enabled (TODO SERVER-72549 remove this comment line: SBE Pushdown)
*
* Search is extracted from the pipeline when the following conditions are met:
* - When the 'internalQueryFrameworkControl' is not set to "forceClassicEngine".
* - When 'featureFlagSearchInSbe' is true.
*
* $_internalUnpackBucket stages ('DocumentSourceInternalUnpackBucket') are extracted when all of:
* - When the 'internalQueryFrameworkControl' is not set to "forceClassicEngine".
* - When 'featureFlagTimeSeriesInSbe' is true.
* - When ExpressionContext::sbePipelineCompatibility is set to
* 'SbeCompatibility::fullyCompatible'.
*/
std::vector<std::unique_ptr<InnerPipelineStageInterface>> findSbeCompatibleStagesForPushdown(
const MultipleCollectionAccessor& collections,
const CanonicalQuery* cq,
bool needsMerge,
const Pipeline* pipeline) {
// We will eventually use the extracted group stages to populate 'CanonicalQuery::pipeline'
// which requires stages to be wrapped in an interface.
std::vector<std::unique_ptr<InnerPipelineStageInterface>> stagesForPushdown;
// This handles the case of unionWith against an unknown collection.
if (!collections.getMainCollection()) {
return {};
}
// No pushdown if we're using the classic engine.
if (cq->getForceClassicEngine()) {
return {};
}
const auto& sources = pipeline->getSources();
bool isMainCollectionSharded = false;
if (const auto& mainColl = collections.getMainCollection()) {
isMainCollectionSharded = mainColl.isSharded_DEPRECATED();
}
// SERVER-78998: Refactor these checks so that they do not load their values multiple times
// during the same query.
// (Ignore FCV check): featureFlagSbeFull does not change the semantics of queries, so it can
// safely be enabled on some nodes and disabled on other nodes during upgrade/downgrade.
SbeCompatibility minRequiredCompatibility =
feature_flags::gFeatureFlagSbeFull.isEnabledAndIgnoreFCVUnsafe()
? SbeCompatibility::flagGuarded
: SbeCompatibility::fullyCompatible;
auto& queryKnob = QueryKnobConfiguration::decoration(cq->getExpCtxRaw()->opCtx);
CompatiblePipelineStages allowedStages = {
.group = !queryKnob.getSbeDisableGroupPushdownForOp(),
// If lookup pushdown isn't enabled or the main collection is sharded or any of the
// secondary namespaces are sharded or are a view, then no $lookup stage will be eligible
// for pushdown.
//
// When acquiring locks for multiple collections, it is the case that we can only determine
// whether any secondary collection is a view or is sharded, not which ones are a view or
// are sharded and which ones aren't. As such, if any secondary collection is a view or is
// sharded, no $lookup will be eligible for pushdown.
.lookup = !queryKnob.getSbeDisableLookupPushdownForOp() && !isMainCollectionSharded &&
!collections.isAnySecondaryNamespaceAViewOrSharded(),
// TODO (SERVER-72549): SBE execution of "transform stages" ($project and $addFields),
// $match, $sort, $limit, and $skip requires 'featureFlagSbeFull' to be enabled.
.transform = SbeCompatibility::flagGuarded >= minRequiredCompatibility,
.match = SbeCompatibility::flagGuarded >= minRequiredCompatibility,
// TODO (SERVER-80226): SBE execution of 'unwind' stages requires 'featureFlagSbeFull' to be
// enabled.
.unwind = SbeCompatibility::flagGuarded >= minRequiredCompatibility,
// Note: even if its sort pattern is SBE compatible, we cannot push down a $sort stage when
// the pipeline is the shard part of a sorted-merge query on a sharded collection. It is
// possible that the merge operation will need a $sortKey field from the sort, and SBE plans
// do not yet support metadata fields.
.sort = (SbeCompatibility::flagGuarded >= minRequiredCompatibility) && !needsMerge,
.limitSkip = SbeCompatibility::flagGuarded >= minRequiredCompatibility,
// TODO (SERVER-77229): SBE execution of $search requires 'featureFlagSearchInSbe' to be
// enabled.
// (Ignore FCV check): As with 'featureFlagSbeFull' (above), the effects of
// 'featureFlagSearchInSbe' are local to this node, making it safe to ignore the FCV.
.search = feature_flags::gFeatureFlagSearchInSbe.isEnabledAndIgnoreFCVUnsafe(),
.window = !(SbeCompatibility::fullyCompatible < minRequiredCompatibility),
// TODO (SERVER-80243): Remove 'featureFlagTimeSeriesInSbe' check.
.unpackBucket = feature_flags::gFeatureFlagTimeSeriesInSbe.isEnabled(
serverGlobalParams.featureCompatibility) &&
cq->getExpCtx()->sbePipelineCompatibility == SbeCompatibility::fullyCompatible,
};
for (auto itr = sources.begin(); itr != sources.end(); ++itr) {
// Push down at most kMaxPipelineStages stages for execution in SBE.
if (stagesForPushdown.size() >= kSbeMaxPipelineStages) {
break;
}
const bool isLastSource = itr->get() == sources.back().get();
if (!pushDownPipelineStageIfCompatible(pipeline->getContext()->opCtx,
*itr,
minRequiredCompatibility,
allowedStages,
isLastSource,
stagesForPushdown)) {
// Stop pushing stages down once we hit an incompatible stage.
break;
}
}
// TODO (SERVER-72549): Once $addFields stages can be pushed down without 'featureFlagSbeFull'
// being enabled, enabling 'featureFlagFull` will disable this step so that $addFields will
// _always_ be pushed down when possible.
reconsiderStagesForPushdown(stagesForPushdown);
return stagesForPushdown;
}
/**
* Removes the first 'stagesToRemove' stages from the pipeline. This function is meant to be paired
* with a call to findSbeCompatibleStagesForPushdown() - the caller must first get the stages to
* push down, then remove them.
*/
void trimPipelineStages(Pipeline* pipeline, size_t stagesToRemove) {
auto& sources = pipeline->getSources();
tassert(7087104,
"stagesToRemove must be <= number of pipeline sources",
stagesToRemove <= sources.size());
for (size_t i = 0; i < stagesToRemove; ++i) {
sources.erase(sources.begin());
}
}
std::unique_ptr<FindCommandRequest> createFindCommand(
const intrusive_ptr<ExpressionContext>& expCtx,
const NamespaceString& nss,
BSONObj queryObj,
BSONObj projectionObj,
BSONObj sortObj,
SkipThenLimit skipThenLimit,
const AggregateCommandRequest* aggRequest) {
auto findCommand = std::make_unique<FindCommandRequest>(nss);
query_request_helper::setTailableMode(expCtx->tailableMode, findCommand.get());
findCommand->setFilter(queryObj.getOwned());
findCommand->setProjection(projectionObj.getOwned());
findCommand->setSort(sortObj.getOwned());
if (auto skip = skipThenLimit.getSkip()) {
findCommand->setSkip(static_cast<std::int64_t>(*skip));
}
if (auto limit = skipThenLimit.getLimit()) {
findCommand->setLimit(static_cast<std::int64_t>(*limit));
}
if (aggRequest) {
findCommand->setAllowDiskUse(aggRequest->getAllowDiskUse());
findCommand->setHint(aggRequest->getHint().value_or(BSONObj()).getOwned());
findCommand->setRequestResumeToken(aggRequest->getRequestResumeToken());
if (aggRequest->getResumeAfter()) {
findCommand->setResumeAfter(*aggRequest->getResumeAfter());
}
}
// The collation on the ExpressionContext has been resolved to either the user-specified
// collation or the collection default. This BSON should never be empty even if the resolved
// collator is simple.
findCommand->setCollation(expCtx->getCollatorBSON().getOwned());
return findCommand;
}
StatusWith<std::unique_ptr<PlanExecutor, PlanExecutor::Deleter>> attemptToGetExecutor(
const intrusive_ptr<ExpressionContext>& expCtx,
const MultipleCollectionAccessor& collections,
const NamespaceString& nss,
std::unique_ptr<FindCommandRequest> findCommand,
const QueryMetadataBitSet& metadataRequested,
const GroupFromFirstDocumentTransformation* groupForDistinctScan,
const QueryPlannerParams& plannerOpts,
const MatchExpressionParser::AllowedFeatureSet& matcherFeatures,
Pipeline* pipeline,
bool isCountLike) {
// Reset the 'sbeCompatible' flag before canonicalizing the 'findCommand' to potentially
// allow SBE to execute the portion of the query that's pushed down, even if the portion of
// the query that is not pushed down contains expressions not supported by SBE.
expCtx->sbeCompatibility = SbeCompatibility::fullyCompatible;
auto cq = CanonicalQuery::make(
{.expCtx = expCtx,
.parsedFind =
ParsedFindCommandParams{
.findCommand = std::move(findCommand),
.extensionsCallback = ExtensionsCallbackReal(expCtx->opCtx, &nss),
.allowedFeatures = matcherFeatures,
.projectionPolicies = ProjectionPolicies::aggregateProjectionPolicies()},
.explain = static_cast<bool>(expCtx->explain),
.isCountLike = isCountLike,
.isSearchQuery = PipelineD::isSearchPresentAndEligibleForSbe(pipeline)});
if (!cq.isOK()) {
// Return an error instead of uasserting, since there are cases where the combination of
// sort and projection will result in a bad query, but when we try with a different
// combination it will be ok. e.g. a sort by {$meta: 'textScore'}, without any projection
// will fail, but will succeed when the corresponding '$meta' projection is passed in
// another attempt.
return {cq.getStatus()};
}
// Mark the metadata that's requested by the pipeline on the CQ.
cq.getValue()->requestAdditionalMetadata(metadataRequested);
if (groupForDistinctScan) {
// When the pipeline includes a $group that groups by a single field
// (groupIdForDistinctScan), we use getExecutorDistinct() to attempt to get an executor that
// uses a DISTINCT_SCAN to scan exactly one document for each group. When that's not
// possible, we return nullptr, and the caller is responsible for trying again without
// passing a 'groupIdForDistinctScan' value.
ParsedDistinct parsedDistinct(std::move(cq.getValue()), groupForDistinctScan->groupId());
// If the GroupFromFirst transformation was generated for the $last case, we will need to
// flip the direction of any generated DISTINCT_SCAN to preserve the semantics of the query.
const bool flipDistinctScanDirection = groupForDistinctScan->expectedInput() ==
GroupFromFirstDocumentTransformation::ExpectedInput::kLastDocument;
// Note that we request a "strict" distinct plan because:
// 1) We do not want to have to de-duplicate the results of the plan.
//
// 2) We not want a plan that will return separate values for each array element. For
// example, if we have a document {a: [1,2]} and group by "a" a DISTINCT_SCAN on an "a"
// index would produce one result for '1' and another for '2', which would be incorrect.
auto distinctExecutor =
getExecutorDistinct(&collections.getMainCollection(),
plannerOpts.options | QueryPlannerParams::STRICT_DISTINCT_ONLY,
&parsedDistinct,
flipDistinctScanDirection);
if (!distinctExecutor.isOK()) {
return distinctExecutor.getStatus().withContext(
"Unable to use distinct scan to optimize $group stage");
} else if (!distinctExecutor.getValue()) {
return {ErrorCodes::NoQueryExecutionPlans,
"Unable to use distinct scan to optimize $group stage"};
} else {
return distinctExecutor;
}
}
// Queries that can use SBE may push down compatible pipeline stages. 'getExecutorFind' will
// call this lambda in two phases: 1) determine compatible stages and attach them to the
// canonical query, and 2) finalize the push down and trim the pushed-down stages from the
// original pipeline.
auto extractAndAttachPipelineStages = [&collections, &pipeline, needsMerge{expCtx->needsMerge}](
auto* canonicalQuery, bool attachOnly) {
if (attachOnly) {
canonicalQuery->setCqPipeline(findSbeCompatibleStagesForPushdown(
collections, canonicalQuery, needsMerge, pipeline));
} else {
trimPipelineStages(pipeline, canonicalQuery->cqPipeline().size());
}
};
return getExecutorFind(expCtx->opCtx,
collections,
std::move(cq.getValue()),
std::move(extractAndAttachPipelineStages),
true /* permitYield */,
plannerOpts);
}
/**
* Examines the indexes in 'collection' and returns the field name of a geo-indexed field suitable
* for use in $geoNear. 2d indexes are given priority over 2dsphere indexes.
*
* The 'collection' is required to exist. Throws if no usable 2d or 2dsphere index could be found.
*/
StringData extractGeoNearFieldFromIndexes(OperationContext* opCtx,
const CollectionPtr& collection) {
invariant(collection);
std::vector<const IndexDescriptor*> idxs;
collection->getIndexCatalog()->findIndexByType(opCtx, IndexNames::GEO_2D, idxs);
uassert(ErrorCodes::IndexNotFound,
str::stream() << "There is more than one 2d index on "
<< collection->ns().toStringForErrorMsg()
<< "; unsure which to use for $geoNear",
idxs.size() <= 1U);
if (idxs.size() == 1U) {
for (auto&& elem : idxs.front()->keyPattern()) {
if (elem.type() == BSONType::String && elem.valueStringData() == IndexNames::GEO_2D) {
return elem.fieldNameStringData();
}
}
MONGO_UNREACHABLE;
}
// If there are no 2d indexes, look for a 2dsphere index.
idxs.clear();
collection->getIndexCatalog()->findIndexByType(opCtx, IndexNames::GEO_2DSPHERE, idxs);
uassert(ErrorCodes::IndexNotFound,
"$geoNear requires a 2d or 2dsphere index, but none were found",
!idxs.empty());
uassert(ErrorCodes::IndexNotFound,
str::stream() << "There is more than one 2dsphere index on "
<< collection->ns().toStringForErrorMsg()
<< "; unsure which to use for $geoNear",
idxs.size() <= 1U);
invariant(idxs.size() == 1U);
for (auto&& elem : idxs.front()->keyPattern()) {
if (elem.type() == BSONType::String && elem.valueStringData() == IndexNames::GEO_2DSPHERE) {
return elem.fieldNameStringData();
}
}
MONGO_UNREACHABLE;
}
/**
* This attempts to either extract a $sample stage at the front of the pipeline or a
* $_internalUnpackBucket stage at the front of the pipeline immediately followed by a $sample
* stage. In the former case a 'nullptr' is returned for the second element of the pair <$sample,
* $_internalUnpackBucket>, and if the latter case is encountered both elements of the pair will be
* a populated. If the pipeline doesn't contain a $_internalUnpackBucket at the front of the
* pipeline immediately followed by a $sample stage, then the first element in the pair will be a
* 'nullptr'.
*/
std::pair<DocumentSourceSample*, DocumentSourceInternalUnpackBucket*> extractSampleUnpackBucket(
const Pipeline::SourceContainer& sources) {
DocumentSourceSample* sampleStage = nullptr;
DocumentSourceInternalUnpackBucket* unpackStage = nullptr;
auto sourcesIt = sources.begin();
if (sourcesIt != sources.end()) {
sampleStage = dynamic_cast<DocumentSourceSample*>(sourcesIt->get());
if (sampleStage) {
return std::pair{sampleStage, unpackStage};
}
unpackStage = dynamic_cast<DocumentSourceInternalUnpackBucket*>(sourcesIt->get());
++sourcesIt;
if (unpackStage && sourcesIt != sources.end()) {
sampleStage = dynamic_cast<DocumentSourceSample*>(sourcesIt->get());
return std::pair{sampleStage, unpackStage};
}
}
return std::pair{sampleStage, unpackStage};
}
bool areSortFieldsModifiedByEventProjection(const SortPattern& sortPattern,
const DocumentSource::GetModPathsReturn& modPaths) {
return std::any_of(sortPattern.begin(), sortPattern.end(), [&](const auto& sortPatternPart) {
const auto& fieldPath = sortPatternPart.fieldPath;
return !fieldPath || modPaths.canModify(*fieldPath);
});
}
bool areSortFieldsModifiedByBucketProjection(const SortPattern& sortPattern,
const DocumentSource::GetModPathsReturn& modPaths) {
// The time field maps to control.min.[time], control.max.[time], or
// _id, and $_internalUnpackBucket assumes that all of those fields are
// preserved. (We never push down a stage that would overwrite them.)
// Each field [meta].a.b.c maps to 'meta.a.b.c'.
auto rename = [&](const FieldPath& eventField) -> FieldPath {
if (eventField.getPathLength() == 1)
return timeseries::kBucketMetaFieldName;
return FieldPath{timeseries::kBucketMetaFieldName}.concat(eventField.tail());
};
return std::any_of(sortPattern.begin(),
// Skip the last field, which is time: only check the meta fields
std::prev(sortPattern.end()),
[&](const auto& sortPatternPart) {
auto bucketFieldPath = rename(*sortPatternPart.fieldPath);
return modPaths.canModify(bucketFieldPath);
});
}
bool areSortFieldsModifiedByProjection(bool seenUnpack,
const SortPattern& sortPattern,
const DocumentSource::GetModPathsReturn& modPaths) {
if (seenUnpack) {
// This stage operates on events: check the event-level field names.
return areSortFieldsModifiedByEventProjection(sortPattern, modPaths);
} else {
// This stage operates on buckets: check the bucket-level field names.
return areSortFieldsModifiedByBucketProjection(sortPattern, modPaths);
}
}
// There can be exactly one unpack stage in a pipeline but multiple sort stages. We'll find the
// _first_ sort.
struct SortAndUnpackInPipeline {
DocumentSourceInternalUnpackBucket* unpack = nullptr;
DocumentSourceSort* sort = nullptr;
int unpackIdx = -1;
int sortIdx = -1;
};
SortAndUnpackInPipeline findUnpackAndSort(const Pipeline::SourceContainer& sources) {
SortAndUnpackInPipeline su;
int idx = 0;
auto itr = sources.begin();
while (itr != sources.end()) {
if (!su.unpack) {
su.unpack = dynamic_cast<DocumentSourceInternalUnpackBucket*>(itr->get());
su.unpackIdx = idx;
}
if (!su.sort) {
su.sort = dynamic_cast<DocumentSourceSort*>(itr->get());
su.sortIdx = idx;
}
if (su.unpack && su.sort) {
break;
}
++itr;
++idx;
}
return su;
}
} // namespace
StatusWith<unique_ptr<PlanExecutor, PlanExecutor::Deleter>> PipelineD::createRandomCursorExecutor(
const CollectionPtr& coll,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
Pipeline* pipeline,
long long sampleSize,
long long numRecords,
boost::optional<timeseries::BucketUnpacker> bucketUnpacker) {
OperationContext* opCtx = expCtx->opCtx;
// Verify that we are already under a collection lock or in a lock-free read. We avoid taking
// locks ourselves in this function because double-locking forces any PlanExecutor we create to
// adopt a NO_YIELD policy.
invariant(opCtx->isLockFreeReadsOp() ||
opCtx->lockState()->isCollectionLockedForMode(coll->ns(), MODE_IS));
auto* clusterParameters = ServerParameterSet::getClusterParameterSet();
auto* randomCursorSampleRatioParam =
clusterParameters
->get<ClusterParameterWithStorage<InternalQueryCutoffForSampleFromRandomCursorStorage>>(
"internalQueryCutoffForSampleFromRandomCursor");
auto maxSampleRatioClusterParameter =
randomCursorSampleRatioParam->getValue(expCtx->ns.tenantId());
const double kMaxSampleRatioForRandCursor = maxSampleRatioClusterParameter.getSampleCutoff();
if (!expCtx->ns.isTimeseriesBucketsCollection()) {
if (sampleSize > numRecords * kMaxSampleRatioForRandCursor || numRecords <= 100) {
return nullptr;
}
} else {
// Suppose that a time-series bucket collection is observed to contain 200 buckets, and the
// 'gTimeseriesBucketMaxCount' parameter is set to 1000. If all buckets are full, then the
// maximum possible measurment count would be 200 * 1000 = 200,000. While the
// 'SampleFromTimeseriesBucket' plan is more efficient when the sample size is small
// relative to the total number of measurements in the time-series collection, for larger
// sample sizes the top-k sort based sample is faster. Experiments have approximated that
// the tipping point is roughly when the requested sample size is greater than 1% of the
// maximum possible number of measurements in the collection (i.e. numBuckets *
// maxMeasurementsPerBucket).
static const double kCoefficient = 0.01;
if (sampleSize > kCoefficient * numRecords * gTimeseriesBucketMaxCount) {
return nullptr;
}
}
// Attempt to get a random cursor from the RecordStore.
auto rsRandCursor = coll->getRecordStore()->getRandomCursor(opCtx);
if (!rsRandCursor) {
// The storage engine has no random cursor support.
return nullptr;
}
// Build a MultiIteratorStage and pass it the random-sampling RecordCursor.
auto ws = std::make_unique<WorkingSet>();
std::unique_ptr<PlanStage> root =
std::make_unique<MultiIteratorStage>(expCtx.get(), ws.get(), &coll);
static_cast<MultiIteratorStage*>(root.get())->addIterator(std::move(rsRandCursor));
TrialStage* trialStage = nullptr;
const auto [isSharded, optOwnershipFilter] = [&]() {
auto scopedCss =
CollectionShardingState::assertCollectionLockedAndAcquire(opCtx, coll->ns());
const bool isSharded = scopedCss->getCollectionDescription(opCtx).isSharded();
boost::optional<ScopedCollectionFilter> optFilter = isSharded
? boost::optional<ScopedCollectionFilter>(scopedCss->getOwnershipFilter(
opCtx, CollectionShardingState::OrphanCleanupPolicy::kDisallowOrphanCleanup))
: boost::none;
return std::pair(isSharded, std::move(optFilter));
}();
// Because 'numRecords' includes orphan documents, our initial decision to optimize the $sample
// cursor may have been mistaken. For sharded collections, build a TRIAL plan that will switch
// to a collection scan if the ratio of orphaned to owned documents encountered over the first
// 100 works() is such that we would have chosen not to optimize.
static const size_t kMaxPresampleSize = 100;
if (expCtx->ns.isTimeseriesBucketsCollection()) {
// We can't take ARHASH optimization path for a direct $sample on the system.buckets
// collection because data is in compressed form. If we did have a direct $sample on the
// system.buckets collection, then the 'bucketUnpacker' would not be set up properly. We
// also should bail out early if a $sample is made against a time series collection that is
// empty. If we don't the 'minAdvancedToWorkRatio' can be nan/-nan depending on the
// architecture.
if (!(bucketUnpacker && numRecords)) {
return nullptr;
}
// Use a 'TrialStage' to run a trial between 'SampleFromTimeseriesBucket' and
// 'UnpackTimeseriesBucket' with $sample left in the pipeline in-place. If the buckets are
// not sufficiently full, or the 'SampleFromTimeseriesBucket' plan draws too many
// duplicates, then we will fall back to the 'TrialStage' backup plan. This backup plan uses
// the top-k sort sampling approach.
//
// Suppose the 'gTimeseriesBucketMaxCount' is 1000, but each bucket only contains 500
// documents on average. The observed trial advanced/work ratio approximates the average
// bucket fullness, noted here as "abf". In this example, abf = 500 / 1000 = 0.5.
// Experiments have shown that the optimized 'SampleFromTimeseriesBucket' algorithm performs
// better than backup plan when
//
// sampleSize < 0.02 * abf * numRecords * gTimeseriesBucketMaxCount
//
// This inequality can be rewritten as
//
// abf > sampleSize / (0.02 * numRecords * gTimeseriesBucketMaxCount)
//
// Therefore, if the advanced/work ratio exceeds this threshold, we will use the
// 'SampleFromTimeseriesBucket' plan. Note that as the sample size requested by the user
// becomes larger with respect to the number of buckets, we require a higher advanced/work
// ratio in order to justify using 'SampleFromTimeseriesBucket'.
//
// Additionally, we require the 'TrialStage' to approximate the abf as at least 0.25. When
// buckets are mostly empty, the 'SampleFromTimeseriesBucket' will be inefficient due to a
// lot of sampling "misses".
static const auto kCoefficient = 0.02;
static const auto kMinBucketFullness = 0.25;
const auto minAdvancedToWorkRatio = std::max(
std::min(sampleSize / (kCoefficient * numRecords * gTimeseriesBucketMaxCount), 1.0),
kMinBucketFullness);
boost::optional<std::unique_ptr<ShardFilterer>> maybeShardFilter;
if (isSharded) {
// In the sharded case, we need to use a ShardFilterer within the ARHASH plan to
// eliminate orphans from the working set, since the stage owns the cursor.
invariant(optOwnershipFilter);
maybeShardFilter = std::make_unique<ShardFiltererImpl>(*optOwnershipFilter);
}
auto arhashPlan = std::make_unique<SampleFromTimeseriesBucket>(
expCtx.get(),
ws.get(),
std::move(root),
bucketUnpacker->copy(),
std::move(maybeShardFilter),
// By using a quantity slightly higher than 'kMaxPresampleSize', we ensure that the
// 'SampleFromTimeseriesBucket' stage won't fail due to too many consecutive sampling
// attempts during the 'TrialStage's trial period.
kMaxPresampleSize + 5,
sampleSize,
gTimeseriesBucketMaxCount);
std::unique_ptr<PlanStage> collScanPlan = std::make_unique<CollectionScan>(
expCtx.get(), &coll, CollectionScanParams{}, ws.get(), nullptr);
if (isSharded) {
// In the sharded case, we need to add a shard-filterer stage to the backup plan to
// eliminate orphans. The trial plan is thus SHARDING_FILTER-COLLSCAN.
invariant(optOwnershipFilter);
collScanPlan = std::make_unique<ShardFilterStage>(
expCtx.get(), *optOwnershipFilter, ws.get(), std::move(collScanPlan));
}
auto topkSortPlan = std::make_unique<UnpackTimeseriesBucket>(
expCtx.get(), ws.get(), std::move(collScanPlan), bucketUnpacker->copy());
// In a sharded collection we need to preserve the $sample source in order to provide the
// AsyncResultsMerger with $sortKeys it can use to merge samples from multiple shards.
// However, this means we need to perform a sort on the results of ARHASH. This work is not
// counted by the TrialStage, so we impose an arbitrary upper limit on the sample size
// before defaulting to a Top-K sort, in order to bound the cost of sorting the sample
// returned by ARHASH.