/
get_executor.cpp
3139 lines (2762 loc) · 139 KB
/
get_executor.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/query/get_executor.h"
#include <absl/container/flat_hash_set.h>
#include <absl/container/node_hash_map.h>
#include <boost/container/flat_set.hpp>
#include <boost/container/small_vector.hpp>
#include <boost/container/vector.hpp>
#include <boost/cstdint.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/none.hpp>
#include <boost/optional.hpp>
#include <boost/optional/optional.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/smart_ptr/intrusive_ptr.hpp>
// IWYU pragma: no_include "ext/alloc_traits.h"
#include <cstdint>
#include <iterator>
#include <limits>
#include <mutex>
#include <set>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include "mongo/base/error_codes.h"
#include "mongo/base/status.h"
#include "mongo/bson/bsonelement.h"
#include "mongo/db/api_parameters.h"
#include "mongo/db/basic_types.h"
#include "mongo/db/catalog/clustered_collection_options_gen.h"
#include "mongo/db/catalog/index_catalog.h"
#include "mongo/db/client.h"
#include "mongo/db/concurrency/locker.h"
#include "mongo/db/curop.h"
#include "mongo/db/database_name.h"
#include "mongo/db/exec/batched_delete_stage.h"
#include "mongo/db/exec/cached_plan.h"
#include "mongo/db/exec/count.h"
#include "mongo/db/exec/delete_stage.h"
#include "mongo/db/exec/document_value/document_metadata_fields.h"
#include "mongo/db/exec/eof.h"
#include "mongo/db/exec/idhack.h"
#include "mongo/db/exec/index_path_projection.h"
#include "mongo/db/exec/multi_plan.h"
#include "mongo/db/exec/plan_cache_util.h"
#include "mongo/db/exec/plan_stage.h"
#include "mongo/db/exec/projection.h"
#include "mongo/db/exec/projection_executor_utils.h"
#include "mongo/db/exec/record_store_fast_count.h"
#include "mongo/db/exec/return_key.h"
#include "mongo/db/exec/sbe/stages/stages.h"
#include "mongo/db/exec/shard_filter.h"
#include "mongo/db/exec/sort_key_generator.h"
#include "mongo/db/exec/spool.h"
#include "mongo/db/exec/subplan.h"
#include "mongo/db/exec/timeseries/bucket_unpacker.h"
#include "mongo/db/exec/timeseries_modify.h"
#include "mongo/db/exec/timeseries_upsert.h"
#include "mongo/db/exec/update_stage.h"
#include "mongo/db/exec/upsert_stage.h"
#include "mongo/db/exec/working_set.h"
#include "mongo/db/feature_flag.h"
#include "mongo/db/field_ref.h"
#include "mongo/db/index/columns_access_method.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/index/multikey_metadata_access_stats.h"
#include "mongo/db/index/wildcard_access_method.h"
#include "mongo/db/index_names.h"
#include "mongo/db/matcher/expression.h"
#include "mongo/db/matcher/expression_parser.h"
#include "mongo/db/matcher/extensions_callback.h"
#include "mongo/db/matcher/extensions_callback_noop.h"
#include "mongo/db/matcher/extensions_callback_real.h"
#include "mongo/db/ops/delete_request_gen.h"
#include "mongo/db/ops/update_request.h"
#include "mongo/db/pipeline/document_source.h"
#include "mongo/db/pipeline/document_source_group.h"
#include "mongo/db/pipeline/field_path.h"
#include "mongo/db/pipeline/inner_pipeline_stage_interface.h"
#include "mongo/db/query/canonical_query.h"
#include "mongo/db/query/classic_plan_cache.h"
#include "mongo/db/query/collation/collator_factory_interface.h"
#include "mongo/db/query/collation/collator_interface.h"
#include "mongo/db/query/collection_query_info.h"
#include "mongo/db/query/cqf_command_utils.h"
#include "mongo/db/query/cqf_get_executor.h"
#include "mongo/db/query/find_command.h"
#include "mongo/db/query/index_bounds.h"
#include "mongo/db/query/index_bounds_builder.h"
#include "mongo/db/query/internal_plans.h"
#include "mongo/db/query/interval.h"
#include "mongo/db/query/interval_evaluation_tree.h"
#include "mongo/db/query/optimizer/defs.h"
#include "mongo/db/query/optimizer/explain_interface.h"
#include "mongo/db/query/plan_cache.h"
#include "mongo/db/query/plan_cache_key_factory.h"
#include "mongo/db/query/plan_executor_factory.h"
#include "mongo/db/query/plan_explainer.h"
#include "mongo/db/query/plan_explainer_factory.h"
#include "mongo/db/query/plan_yield_policy_sbe.h"
#include "mongo/db/query/planner_analysis.h"
#include "mongo/db/query/planner_ixselect.h"
#include "mongo/db/query/planner_wildcard_helpers.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_feature_flags_gen.h"
#include "mongo/db/query/query_knobs_gen.h"
#include "mongo/db/query/query_planner.h"
#include "mongo/db/query/query_planner_common.h"
#include "mongo/db/query/query_planner_params.h"
#include "mongo/db/query/query_settings.h"
#include "mongo/db/query/query_settings_decoration.h"
#include "mongo/db/query/query_utils.h"
#include "mongo/db/query/sbe_cached_solution_planner.h"
#include "mongo/db/query/sbe_multi_planner.h"
#include "mongo/db/query/sbe_plan_cache.h"
#include "mongo/db/query/sbe_runtime_planner.h"
#include "mongo/db/query/sbe_stage_builder.h"
#include "mongo/db/query/sbe_sub_planner.h"
#include "mongo/db/query/stage_builder_util.h"
#include "mongo/db/query/stage_types.h"
#include "mongo/db/query/util/make_data_structure.h"
#include "mongo/db/query/wildcard_multikey_paths.h"
#include "mongo/db/query/yield_policy_callbacks_impl.h"
#include "mongo/db/repl/replication_coordinator.h"
#include "mongo/db/s/operation_sharding_state.h"
#include "mongo/db/server_options.h"
#include "mongo/db/server_parameter.h"
#include "mongo/db/service_context.h"
#include "mongo/db/stats/counters.h"
#include "mongo/db/storage/record_store.h"
#include "mongo/db/storage/recovery_unit.h"
#include "mongo/db/storage/storage_options.h"
#include "mongo/db/timeseries/timeseries_gen.h"
#include "mongo/db/timeseries/timeseries_update_delete_util.h"
#include "mongo/db/update/update_driver.h"
#include "mongo/db/yieldable.h"
#include "mongo/logv2/log.h"
#include "mongo/logv2/log_attr.h"
#include "mongo/logv2/log_component.h"
#include "mongo/logv2/redaction.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/s/shard_key_pattern.h"
#include "mongo/s/shard_key_pattern_query_util.h"
#include "mongo/stdx/unordered_set.h"
#include "mongo/stdx/variant.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/decorable.h"
#include "mongo/util/duration.h"
#include "mongo/util/intrusive_counter.h"
#include "mongo/util/processinfo.h"
#include "mongo/util/scopeguard.h"
#include "mongo/util/str.h"
#include "mongo/util/synchronized_value.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kQuery
namespace mongo {
boost::intrusive_ptr<ExpressionContext> makeExpressionContextForGetExecutor(
OperationContext* opCtx, const BSONObj& requestCollation, const NamespaceString& nss) {
invariant(opCtx);
auto expCtx = make_intrusive<ExpressionContext>(opCtx, nullptr, nss);
if (!requestCollation.isEmpty()) {
auto statusWithCollator = CollatorFactoryInterface::get(expCtx->opCtx->getServiceContext())
->makeFromBSON(requestCollation);
expCtx->setCollator(uassertStatusOK(std::move(statusWithCollator)));
}
return expCtx;
}
// static
void filterAllowedIndexEntries(const AllowedIndicesFilter& allowedIndicesFilter,
std::vector<IndexEntry>* indexEntries) {
invariant(indexEntries);
// Filter index entries
// Check BSON objects in AllowedIndices::_indexKeyPatterns against IndexEntry::keyPattern.
// Removes IndexEntrys that do not match _indexKeyPatterns.
std::vector<IndexEntry> temp;
for (std::vector<IndexEntry>::const_iterator i = indexEntries->begin();
i != indexEntries->end();
++i) {
const IndexEntry& indexEntry = *i;
if (allowedIndicesFilter.allows(indexEntry)) {
// Copy index entry into temp vector if found in query settings.
temp.push_back(indexEntry);
}
}
// Update results.
temp.swap(*indexEntries);
}
namespace {
namespace wcp = ::mongo::wildcard_planning;
// The body is below in the "count hack" section but getExecutor calls it.
bool turnIxscanIntoCount(QuerySolution* soln);
} // namespace
bool isAnyComponentOfPathMultikey(const BSONObj& indexKeyPattern,
bool isMultikey,
const MultikeyPaths& indexMultikeyInfo,
StringData path) {
if (!isMultikey) {
return false;
}
size_t keyPatternFieldIndex = 0;
bool found = false;
if (indexMultikeyInfo.empty()) {
// There is no path-level multikey information available, so we must assume 'path' is
// multikey.
return true;
}
for (auto&& elt : indexKeyPattern) {
if (elt.fieldNameStringData() == path) {
found = true;
break;
}
keyPatternFieldIndex++;
}
invariant(found);
invariant(indexMultikeyInfo.size() > keyPatternFieldIndex);
return !indexMultikeyInfo[keyPatternFieldIndex].empty();
}
IndexEntry indexEntryFromIndexCatalogEntry(OperationContext* opCtx,
const CollectionPtr& collection,
const IndexCatalogEntry& ice,
const CanonicalQuery* canonicalQuery) {
auto desc = ice.descriptor();
invariant(desc);
if (desc->isIdIndex()) {
// _id indexes are guaranteed to be non-multikey. Determining whether the index is multikey
// has a small cost associated with it, so we skip that here to make _id lookups faster.
return {desc->keyPattern(),
desc->getIndexType(),
desc->version(),
false, /* isMultikey */
{}, /* MultikeyPaths */
{}, /* multikey Pathset */
desc->isSparse(),
desc->unique(),
IndexEntry::Identifier{desc->indexName()},
ice.getFilterExpression(),
desc->infoObj(),
ice.getCollator(),
nullptr /* wildcard projection */};
}
auto accessMethod = ice.accessMethod();
invariant(accessMethod);
const bool isMultikey = ice.isMultikey(opCtx, collection);
const WildcardProjection* wildcardProjection = nullptr;
std::set<FieldRef> multikeyPathSet;
if (desc->getIndexType() == IndexType::INDEX_WILDCARD) {
wildcardProjection =
static_cast<const WildcardAccessMethod*>(accessMethod)->getWildcardProjection();
if (isMultikey) {
MultikeyMetadataAccessStats mkAccessStats;
if (canonicalQuery) {
RelevantFieldIndexMap fieldIndexProps;
QueryPlannerIXSelect::getFields(canonicalQuery->root(), &fieldIndexProps);
stdx::unordered_set<std::string> projectedFields;
for (auto&& [fieldName, _] : fieldIndexProps) {
if (projection_executor_utils::applyProjectionToOneField(
wildcardProjection->exec(), fieldName)) {
projectedFields.insert(fieldName);
}
}
multikeyPathSet =
getWildcardMultikeyPathSet(opCtx, &ice, projectedFields, &mkAccessStats);
} else {
multikeyPathSet = getWildcardMultikeyPathSet(opCtx, &ice, &mkAccessStats);
}
LOGV2_DEBUG(20920,
2,
"Multikey path metadata range index scan stats",
"index"_attr = desc->indexName(),
"numSeeks"_attr = mkAccessStats.keysExamined,
"keysExamined"_attr = mkAccessStats.keysExamined);
}
}
return {desc->keyPattern(),
desc->getIndexType(),
desc->version(),
isMultikey,
// The fixed-size vector of multikey paths stored in the index catalog.
ice.getMultikeyPaths(opCtx, collection),
// The set of multikey paths from special metadata keys stored in the index itself.
// Indexes that have these metadata keys do not store a fixed-size vector of multikey
// metadata in the index catalog. Depending on the index type, an index uses one of
// these mechanisms (or neither), but not both.
std::move(multikeyPathSet),
desc->isSparse(),
desc->unique(),
IndexEntry::Identifier{desc->indexName()},
ice.getFilterExpression(),
desc->infoObj(),
ice.getCollator(),
wildcardProjection};
}
ColumnIndexEntry columnIndexEntryFromIndexCatalogEntry(OperationContext* opCtx,
const CollectionPtr& collection,
const IndexCatalogEntry& ice) {
auto desc = ice.descriptor();
invariant(desc);
auto accessMethod = ice.accessMethod();
invariant(accessMethod);
auto cam = static_cast<const ColumnStoreAccessMethod*>(accessMethod);
const auto columnstoreProjection = cam->getColumnstoreProjection();
return {desc->keyPattern(),
desc->getIndexType(),
desc->version(),
desc->isSparse(),
desc->unique(),
ColumnIndexEntry::Identifier{desc->indexName()},
ice.getFilterExpression(),
ice.getCollator(),
columnstoreProjection};
}
/**
* If query supports index filters, filter params.indices according to any index filters that have
* been configured. In addition, sets that there were indeed index filters applied.
*/
void applyIndexFilters(const CollectionPtr& collection,
const CanonicalQuery& canonicalQuery,
QueryPlannerParams* plannerParams) {
const QuerySettings* querySettings =
QuerySettingsDecoration::get(collection->getSharedDecorations());
const auto key = canonicalQuery.encodeKeyForPlanCacheCommand();
// Filter index catalog if index filters are specified for query.
// Also, signal to planner that application hint should be ignored.
if (boost::optional<AllowedIndicesFilter> allowedIndicesFilter =
querySettings->getAllowedIndicesFilter(key)) {
filterAllowedIndexEntries(*allowedIndicesFilter, &plannerParams->indices);
plannerParams->indexFiltersApplied = true;
}
}
namespace {
void fillOutIndexEntries(OperationContext* opCtx,
bool apiStrict,
const CanonicalQuery* canonicalQuery,
const CollectionPtr& collection,
std::vector<IndexEntry>& entries,
std::vector<ColumnIndexEntry>& columnEntries) {
std::vector<const IndexCatalogEntry*> columnIndexes, plainIndexes;
auto ii = collection->getIndexCatalog()->getIndexIterator(
opCtx, IndexCatalog::InclusionPolicy::kReady);
while (ii->more()) {
const IndexCatalogEntry* ice = ii->next();
// Indexes excluded from API version 1 should _not_ be used for planning if apiStrict is
// set to true.
auto indexType = ice->descriptor()->getIndexType();
if (apiStrict &&
(indexType == IndexType::INDEX_HAYSTACK || indexType == IndexType::INDEX_TEXT ||
indexType == IndexType::INDEX_COLUMN || ice->descriptor()->isSparse()))
continue;
// Skip the addition of hidden indexes to prevent use in query planning.
if (ice->descriptor()->hidden())
continue;
if (indexType == IndexType::INDEX_COLUMN) {
columnIndexes.push_back(ice);
} else {
plainIndexes.push_back(ice);
}
}
columnEntries.reserve(columnIndexes.size());
for (auto ice : columnIndexes) {
columnEntries.emplace_back(columnIndexEntryFromIndexCatalogEntry(opCtx, collection, *ice));
}
entries.reserve(plainIndexes.size());
for (auto ice : plainIndexes) {
entries.emplace_back(
indexEntryFromIndexCatalogEntry(opCtx, collection, *ice, canonicalQuery));
}
}
} // namespace
CollectionStats fillOutCollectionStats(OperationContext* opCtx, const CollectionPtr& collection) {
auto recordStore = collection->getRecordStore();
CollectionStats stats;
stats.noOfRecords = recordStore->numRecords(opCtx),
stats.approximateDataSizeBytes = recordStore->dataSize(opCtx),
stats.storageSizeBytes = recordStore->storageSize(opCtx);
return stats;
}
void fillOutPlannerParams(OperationContext* opCtx,
const CollectionPtr& collection,
const CanonicalQuery* canonicalQuery,
QueryPlannerParams* plannerParams) {
invariant(canonicalQuery);
bool apiStrict = APIParameters::get(opCtx).getAPIStrict().value_or(false);
// _id queries can skip checking the catalog for indices since they will always use the _id
// index.
if (!isIdHackEligibleQuery(collection, *canonicalQuery)) {
// If it's not NULL, we may have indices. Access the catalog and fill out IndexEntry(s)
fillOutIndexEntries(opCtx,
apiStrict,
canonicalQuery,
collection,
plannerParams->indices,
plannerParams->columnStoreIndexes);
// If query supports index filters, filter params.indices by indices in query settings.
// Ignore index filters when it is possible to use the id-hack.
applyIndexFilters(collection, *canonicalQuery, plannerParams);
}
// We will not output collection scans unless there are no indexed solutions. NO_TABLE_SCAN
// overrides this behavior by not outputting a collscan even if there are no indexed
// solutions.
if (storageGlobalParams.noTableScan.load()) {
const auto& nss = canonicalQuery->nss();
// There are certain cases where we ignore this restriction:
bool ignore =
canonicalQuery->getQueryObj().isEmpty() || nss.isSystem() || nss.isOnInternalDb();
if (!ignore) {
plannerParams->options |= QueryPlannerParams::NO_TABLE_SCAN;
}
}
// If the caller wants a shard filter, make sure we're actually sharded.
if (plannerParams->options & QueryPlannerParams::INCLUDE_SHARD_FILTER) {
if (collection.isSharded()) {
const auto& shardKeyPattern = collection.getShardKeyPattern();
// If the shard key is specified exactly, the query is guaranteed to only target one
// shard. Shards cannot own orphans for the key ranges they own, so there is no need
// to include a shard filtering stage. By omitting the shard filter, it may be possible
// to get a more efficient plan (for example, a COUNT_SCAN may be used if the query is
// eligible).
const BSONObj extractedKey = extractShardKeyFromQuery(shardKeyPattern, *canonicalQuery);
if (extractedKey.isEmpty()) {
plannerParams->shardKey = shardKeyPattern.toBSON();
} else {
plannerParams->options &= ~QueryPlannerParams::INCLUDE_SHARD_FILTER;
}
} else {
// If there's no metadata don't bother w/the shard filter since we won't know what
// the key pattern is anyway...
plannerParams->options &= ~QueryPlannerParams::INCLUDE_SHARD_FILTER;
}
}
if (internalQueryPlannerEnableIndexIntersection.load()) {
plannerParams->options |= QueryPlannerParams::INDEX_INTERSECTION;
}
if (internalQueryEnumerationPreferLockstepOrEnumeration.load()) {
plannerParams->options |= QueryPlannerParams::ENUMERATE_OR_CHILDREN_LOCKSTEP;
}
if (internalQueryPlannerGenerateCoveredWholeIndexScans.load()) {
plannerParams->options |= QueryPlannerParams::GENERATE_COVERED_IXSCANS;
}
if (shouldWaitForOplogVisibility(
opCtx, collection, canonicalQuery->getFindCommandRequest().getTailable())) {
plannerParams->options |= QueryPlannerParams::OPLOG_SCAN_WAIT_FOR_VISIBLE;
}
if (collection->isClustered()) {
plannerParams->clusteredInfo = collection->getClusteredInfo();
plannerParams->clusteredCollectionCollator = collection->getDefaultCollator();
}
if (!plannerParams->columnStoreIndexes.empty()) {
// Fill out statistics needed for column scan query planning.
plannerParams->collectionStats = fillOutCollectionStats(opCtx, collection);
const auto kMB = 1024 * 1024;
plannerParams->availableMemoryBytes =
static_cast<long long>(ProcessInfo::getMemSizeMB()) * kMB;
}
}
std::map<NamespaceString, SecondaryCollectionInfo> fillOutSecondaryCollectionsInformation(
OperationContext* opCtx,
const MultipleCollectionAccessor& collections,
const CanonicalQuery* canonicalQuery) {
std::map<NamespaceString, SecondaryCollectionInfo> infoMap;
bool apiStrict = APIParameters::get(opCtx).getAPIStrict().value_or(false);
auto fillOutSecondaryInfo = [&](const NamespaceString& nss,
const CollectionPtr& secondaryColl) {
auto secondaryInfo = SecondaryCollectionInfo();
if (secondaryColl) {
fillOutIndexEntries(opCtx,
apiStrict,
canonicalQuery,
secondaryColl,
secondaryInfo.indexes,
secondaryInfo.columnIndexes);
secondaryInfo.stats = fillOutCollectionStats(opCtx, secondaryColl);
} else {
secondaryInfo.exists = false;
}
infoMap.emplace(nss, std::move(secondaryInfo));
};
for (auto& [collName, secondaryColl] : collections.getSecondaryCollections()) {
fillOutSecondaryInfo(collName, secondaryColl);
}
// In the event of a self $lookup, we must have an entry for the main collection in the map
// of secondary collections.
if (collections.hasMainCollection()) {
const auto& mainColl = collections.getMainCollection();
fillOutSecondaryInfo(mainColl->ns(), mainColl);
}
return infoMap;
}
void fillOutPlannerParams(OperationContext* opCtx,
const MultipleCollectionAccessor& collections,
const CanonicalQuery* canonicalQuery,
QueryPlannerParams* plannerParams) {
fillOutPlannerParams(opCtx, collections.getMainCollection(), canonicalQuery, plannerParams);
plannerParams->secondaryCollectionsInfo =
fillOutSecondaryCollectionsInformation(opCtx, collections, canonicalQuery);
}
bool shouldWaitForOplogVisibility(OperationContext* opCtx,
const CollectionPtr& collection,
bool tailable) {
// Only non-tailable cursors on the oplog are affected. Only forward cursors, not reverse
// cursors, are affected, but this is checked when the cursor is opened.
if (!collection->ns().isOplog() || tailable) {
return false;
}
// Only primaries should require readers to wait for oplog visibility. In any other replication
// state, readers read at the most visible oplog timestamp. The reason why readers on primaries
// need to wait is because multiple optimes can be allocated for operations before their entries
// are written to the storage engine. "Holes" will appear when an operation with a later optime
// commits before an operation with an earlier optime, and readers should wait so that all data
// is consistent.
//
// Secondaries can't wait for oplog visibility without the PBWM lock because it can introduce a
// hang while a batch application is in progress. The wait is done while holding a global lock,
// and the oplog visibility timestamp is updated at the end of every batch on a secondary,
// signalling the wait to complete. If a replication worker had a global lock and temporarily
// released it, a reader could acquire the lock to read the oplog. If the secondary reader were
// to wait for the oplog visibility timestamp to be updated, it would wait for a replication
// batch that would never complete because it couldn't reacquire its own lock, the global lock
// held by the waiting reader.
return repl::ReplicationCoordinator::get(opCtx)->canAcceptWritesForDatabase(
opCtx, DatabaseName::kAdmin);
}
namespace {
/**
* Struct to hold information about a query plan's cache info.
*/
struct PlanCacheInfo {
boost::optional<uint32_t> planCacheKey;
boost::optional<uint32_t> queryHash;
};
/**
* Fills in the given information on the CurOp::OpDebug object, if it has not already been filled in
* by an outer pipeline.
*/
void setOpDebugPlanCacheInfo(OperationContext* opCtx, const PlanCacheInfo& cacheInfo) {
OpDebug& opDebug = CurOp::get(opCtx)->debug();
if (!opDebug.queryHash && cacheInfo.queryHash) {
opDebug.queryHash = *cacheInfo.queryHash;
}
if (!opDebug.planCacheKey && cacheInfo.planCacheKey) {
opDebug.planCacheKey = *cacheInfo.planCacheKey;
}
}
/**
* A class to hold the result of preparation of the query to be executed using classic engine. This
* result stores and provides the following information:
* - A QuerySolutions for the query. May be null in certain circumstances, where the constructed
* execution tree does not have an associated query solution.
* - A root PlanStage of the constructed execution tree.
*/
class ClassicPrepareExecutionResult {
public:
void emplace(std::unique_ptr<PlanStage> root, std::unique_ptr<QuerySolution> solution) {
invariant(!_root);
invariant(!_solution);
_root = std::move(root);
_solution = std::move(solution);
}
std::string getPlanSummary() const {
invariant(_root);
auto explainer = plan_explainer_factory::make(_root.get());
return explainer->getPlanSummary();
}
std::tuple<std::unique_ptr<PlanStage>, std::unique_ptr<QuerySolution>> extractResultData() {
return std::make_tuple(std::move(_root), std::move(_solution));
}
void setRecoveredFromPlanCache(bool val) {
_fromPlanCache = val;
}
bool isRecoveredFromPlanCache() {
return _fromPlanCache;
}
PlanCacheInfo& planCacheInfo() {
return _cacheInfo;
}
private:
std::unique_ptr<PlanStage> _root;
std::unique_ptr<QuerySolution> _solution;
bool _fromPlanCache{false};
PlanCacheInfo _cacheInfo;
};
/**
* A class to hold the result of preparation of the query to be executed using SBE engine. This
* result stores and provides the following information:
* - A vector of QuerySolutions. Elements of the vector may be null, in certain circumstances
* where the constructed execution tree does not have an associated query solution.
* - A vector of PlanStages, representing the roots of the constructed execution trees (in the
* case when the query has multiple solutions, we may construct an execution tree for each
* solution and pick the best plan after multi-planning). Elements of this vector can never be
* null. The size of this vector must always be empty or match the size of 'querySolutions'
* vector. It will be empty in circumstances where we only construct query solutions and delay
* building execution trees, which is any time we are not using a cached plan.
* - A root node of the extension plan. The plan can be combined with a solution to create a
* larger plan after the winning solution is found. Can be null, meaning "no extension".
* - An optional decisionWorks value, which is populated when a solution was reconstructed from
* the PlanCache, and will hold the number of work cycles taken to decide on a winning plan
* when the plan was first cached. It used to decided whether cached solution runtime planning
* needs to be done or not.
* - A 'needSubplanning' flag indicating that the query contains rooted $or predicate and is
* eligible for runtime sub-planning.
*/
class SlotBasedPrepareExecutionResult {
public:
using QuerySolutionVector = std::vector<std::unique_ptr<QuerySolution>>;
using PlanStageVector =
std::vector<std::pair<std::unique_ptr<sbe::PlanStage>, stage_builder::PlanStageData>>;
void emplace(std::unique_ptr<QuerySolution> solution) {
// Only allow solutions to be added, execution trees will be generated later.
tassert(7087100,
"expected execution trees to be generated after query solutions",
_roots.empty());
_solutions.push_back(std::move(solution));
}
void emplace(std::pair<std::unique_ptr<sbe::PlanStage>, stage_builder::PlanStageData> root) {
_roots.push_back(std::move(root));
// Make sure we store an empty QuerySolution instead of a nullptr or nothing.
_solutions.push_back(std::make_unique<QuerySolution>());
}
std::string getPlanSummary() const {
// We can report plan summary only if this result contains a single solution.
tassert(7087101, "expected exactly one solution", _solutions.size() == 1);
tassert(7087102, "expected at most one execution tree", _roots.size() <= 1);
// We only need the query solution to build the explain summary.
auto explainer = plan_explainer_factory::make(
nullptr /* root */, nullptr /* data */, _solutions[0].get());
return explainer->getPlanSummary();
}
std::pair<PlanStageVector, QuerySolutionVector> extractResultData() {
return std::make_pair(std::move(_roots), std::move(_solutions));
}
const QuerySolutionVector& solutions() const {
return _solutions;
}
const PlanStageVector& roots() const {
return _roots;
}
boost::optional<size_t> decisionWorks() const {
return _decisionWorks;
}
bool needsSubplanning() const {
return _needSubplanning;
}
void setNeedsSubplanning(bool needsSubplanning) {
_needSubplanning = needsSubplanning;
}
void setDecisionWorks(boost::optional<size_t> decisionWorks) {
_decisionWorks = decisionWorks;
}
bool recoveredPinnedCacheEntry() const {
return _recoveredPinnedCacheEntry;
}
void setRecoveredPinnedCacheEntry(bool pinnedEntry) {
_recoveredPinnedCacheEntry = pinnedEntry;
}
void setRecoveredFromPlanCache(bool val) {
_fromPlanCache = val;
}
bool isRecoveredFromPlanCache() const {
return _fromPlanCache;
}
PlanCacheInfo& planCacheInfo() {
return _cacheInfo;
}
private:
QuerySolutionVector _solutions;
PlanStageVector _roots;
boost::optional<size_t> _decisionWorks;
bool _needSubplanning{false};
bool _recoveredPinnedCacheEntry{false};
bool _fromPlanCache{false};
PlanCacheInfo _cacheInfo;
};
/**
* A helper class to build and prepare a PlanStage tree for execution. This class contains common
* logic to build and prepare an execution tree for the provided canonical query, and also provides
* methods to build various specialized PlanStage trees when we either:
* * Do not build a QuerySolutionNode tree for the input query, and as such do not undergo the
* normal stage builder process.
* * We have a QuerySolutionNode tree (or multiple query solution trees), but must execute some
* custom logic in order to build the final execution tree.
*
* In most cases, the helper bypasses the final step of building the execution tree and returns only
* the query solution(s) if the 'DeferExecutionTreeGeneration' flag is true.
*/
template <typename KeyType,
typename PlanStageType,
typename ResultType,
bool DeferExecutionTreeGeneration>
class PrepareExecutionHelper {
public:
PrepareExecutionHelper(OperationContext* opCtx,
CanonicalQuery* cq,
PlanYieldPolicy* yieldPolicy,
const QueryPlannerParams& plannerOptions)
: _opCtx{opCtx},
_cq{cq},
_yieldPolicy{yieldPolicy},
_result{std::make_unique<ResultType>()} {
invariant(_cq);
_plannerParams = plannerOptions;
}
/**
* Returns a reference to the main collection that is targeted by this query.
*/
virtual const CollectionPtr& getMainCollection() const = 0;
StatusWith<std::unique_ptr<ResultType>> prepare() {
const auto& mainColl = getMainCollection();
ON_BLOCK_EXIT([&] { CurOp::get(_opCtx)->stopQueryPlanningTimer(); });
if (!mainColl) {
LOGV2_DEBUG(20921,
2,
"Collection does not exist. Using EOF plan",
logAttrs(_cq->nss()),
"canonicalQuery"_attr = redact(_cq->toStringShort()));
auto solution = std::make_unique<QuerySolution>();
solution->setRoot(std::make_unique<EofNode>());
auto result = releaseResult();
addSolutionToResult(result.get(), std::move(solution));
return std::move(result);
}
// Tailable: If the query requests tailable the collection must be capped.
if (_cq->getFindCommandRequest().getTailable() && !mainColl->isCapped()) {
return Status(ErrorCodes::BadValue,
str::stream() << "error processing query: " << _cq->toStringForErrorMsg()
<< " tailable cursor requested on non capped collection");
}
// If the canonical query does not have a user-specified collation and no one has given the
// CanonicalQuery a collation already, set it from the collection default.
if (_cq->getFindCommandRequest().getCollation().isEmpty() &&
_cq->getCollator() == nullptr && mainColl->getDefaultCollator()) {
_cq->setCollator(mainColl->getDefaultCollator()->clone());
}
// Before consulting the plan cache, check if we should short-circuit and construct a
// find-by-_id plan.
if (auto result = buildIdHackPlan()) {
return {std::move(result)};
}
auto planCacheKey = buildPlanCacheKey();
getResult()->planCacheInfo().queryHash = planCacheKey.queryHash();
getResult()->planCacheInfo().planCacheKey = planCacheKey.planCacheKeyHash();
if (auto result = buildCachedPlan(planCacheKey)) {
return {std::move(result)};
}
initializePlannerParamsIfNeeded();
if (SubplanStage::needsSubplanning(*_cq)) {
LOGV2_DEBUG(20924,
2,
"Running query as sub-queries",
"query"_attr = redact(_cq->toStringShort()));
return buildSubPlan();
}
auto statusWithMultiPlanSolns = QueryPlanner::plan(*_cq, _plannerParams);
if (!statusWithMultiPlanSolns.isOK()) {
return statusWithMultiPlanSolns.getStatus().withContext(
str::stream() << "error processing query: " << _cq->toStringForErrorMsg()
<< " planner returned error");
}
auto solutions = std::move(statusWithMultiPlanSolns.getValue());
// The planner should have returned an error status if there are no solutions.
invariant(solutions.size() > 0);
// See if one of our solutions is a fast count hack in disguise.
if (_cq->isCountLike()) {
for (size_t i = 0; i < solutions.size(); ++i) {
if (turnIxscanIntoCount(solutions[i].get())) {
auto result = releaseResult();
addSolutionToResult(result.get(), std::move(solutions[i]));
LOGV2_DEBUG(20925,
2,
"Using fast count",
"query"_attr = redact(_cq->toStringShort()),
"planSummary"_attr = result->getPlanSummary());
return std::move(result);
}
}
}
// Force multiplanning (and therefore caching) if forcePlanCache is set. We could manually
// update the plan cache instead without multiplanning but this is simpler.
if (1 == solutions.size() && !_cq->getExpCtxRaw()->forcePlanCache) {
// Only one possible plan. Build the stages from the solution.
auto result = releaseResult();
solutions[0]->indexFilterApplied = _plannerParams.indexFiltersApplied;
addSolutionToResult(result.get(), std::move(solutions[0]));
LOGV2_DEBUG(20926,
2,
"Only one plan is available",
"query"_attr = redact(_cq->toStringShort()),
"planSummary"_attr = result->getPlanSummary());
return std::move(result);
}
return buildMultiPlan(std::move(solutions));
}
protected:
static constexpr bool ShouldDeferExecutionTreeGeneration = DeferExecutionTreeGeneration;
/**
* Get the result object to be returned by this in-progress prepare() call.
*/
ResultType* getResult() {
tassert(7061700, "expected _result to not be null", _result);
return _result.get();
}
/**
* Release the result instance to be returned to the caller holding the result of the
* prepare() call.
*/
auto releaseResult() {
return std::move(_result);
}
/**
* Adds the query solution to the result object, additionally building the corresponding
* execution tree if 'DeferExecutionTreeGeneration' is turned on.
*/
void addSolutionToResult(ResultType* result, std::unique_ptr<QuerySolution> solution) {
if constexpr (!DeferExecutionTreeGeneration) {
auto root = buildExecutableTree(*solution);
result->emplace(std::move(root), std::move(solution));
} else {
result->emplace(std::move(solution));
}
}
/**
* Fills out planner parameters if not already filled.
*/
void initializePlannerParamsIfNeeded() {
if (_plannerParamsInitialized) {
return;
}
fillOutPlannerParams(_opCtx, getMainCollection(), _cq, &_plannerParams);
_plannerParamsInitialized = true;
}
/**
* Constructs a PlanStage tree from the given query 'solution'.
*/
virtual PlanStageType buildExecutableTree(const QuerySolution& solution) const = 0;
/**
* Attempts to build a special cased fast-path query plan for a find-by-_id query. Returns
* nullptr if this optimization does not apply.
*/
virtual std::unique_ptr<ResultType> buildIdHackPlan() = 0;
/**
* Constructs the plan cache key.
*/
virtual KeyType buildPlanCacheKey() const = 0;
/**
* Either constructs a PlanStage tree from a cached plan (if exists in the plan cache), or
* constructs a "id hack" PlanStage tree. Returns nullptr if no cached plan or id hack plan can
* be constructed.
*/
virtual std::unique_ptr<ResultType> buildCachedPlan(const KeyType& planCacheKey) = 0;
/**
* Constructs a special PlanStage tree for rooted $or queries. Each clause of the $or is planned
* individually, and then an overall query plan is created based on the winning plan from each
* clause.
*
* If sub-planning is implemented as a standalone component, rather than as part of the
* execution tree, this method can populate the result object with additional information
* required to perform the sub-planning.
*/
virtual std::unique_ptr<ResultType> buildSubPlan() = 0;
/**
* If the query have multiple solutions, this method either:
* * Constructs a special PlanStage tree to perform a multi-planning task and pick the best