/
sbe_stage_builder.cpp
5872 lines (4981 loc) · 257 KB
/
sbe_stage_builder.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) 2019-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/sbe_stage_builder.h"
// IWYU pragma: no_include "ext/alloc_traits.h"
#include <absl/container/flat_hash_map.h>
#include <absl/container/flat_hash_set.h>
#include <absl/container/inlined_vector.h>
#include <absl/meta/type_traits.h>
#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 <limits>
#include <map>
#include <numeric>
#include <set>
#include <string_view>
#include <tuple>
#include <type_traits>
#include "mongo/base/checked_cast.h"
#include "mongo/base/error_codes.h"
#include "mongo/bson/bsonelement.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/bson/util/builder.h"
#include "mongo/bson/util/builder_fwd.h"
#include "mongo/db/basic_types.h"
#include "mongo/db/catalog/clustered_collection_util.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/index_catalog.h"
#include "mongo/db/catalog/index_catalog_entry.h"
#include "mongo/db/exec/document_value/document.h"
#include "mongo/db/exec/document_value/value.h"
#include "mongo/db/exec/docval_to_sbeval.h"
#include "mongo/db/exec/sbe/abt/abt_lower_defs.h"
#include "mongo/db/exec/sbe/makeobj_spec.h"
#include "mongo/db/exec/sbe/match_path.h"
#include "mongo/db/exec/sbe/sort_spec.h"
#include "mongo/db/exec/sbe/stages/agg_project.h"
#include "mongo/db/exec/sbe/stages/co_scan.h"
#include "mongo/db/exec/sbe/stages/column_scan.h"
#include "mongo/db/exec/sbe/stages/filter.h"
#include "mongo/db/exec/sbe/stages/hash_agg.h"
#include "mongo/db/exec/sbe/stages/hash_join.h"
#include "mongo/db/exec/sbe/stages/ix_scan.h"
#include "mongo/db/exec/sbe/stages/limit_skip.h"
#include "mongo/db/exec/sbe/stages/loop_join.h"
#include "mongo/db/exec/sbe/stages/makeobj.h"
#include "mongo/db/exec/sbe/stages/merge_join.h"
#include "mongo/db/exec/sbe/stages/project.h"
#include "mongo/db/exec/sbe/stages/search_cursor.h"
#include "mongo/db/exec/sbe/stages/sort.h"
#include "mongo/db/exec/sbe/stages/sorted_merge.h"
#include "mongo/db/exec/sbe/stages/union.h"
#include "mongo/db/exec/sbe/stages/unique.h"
#include "mongo/db/exec/sbe/stages/unwind.h"
#include "mongo/db/exec/sbe/values/arith_common.h"
#include "mongo/db/exec/sbe/values/bson.h"
#include "mongo/db/exec/sbe/values/value.h"
#include "mongo/db/exec/shard_filterer.h"
#include "mongo/db/exec/shard_filterer_impl.h"
#include "mongo/db/field_ref.h"
#include "mongo/db/fts/fts_matcher.h"
#include "mongo/db/fts/fts_query.h"
#include "mongo/db/fts/fts_query_impl.h"
#include "mongo/db/index/fts_access_method.h"
#include "mongo/db/index/index_access_method.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/index_names.h"
#include "mongo/db/matcher/expression_leaf.h"
#include "mongo/db/matcher/expression_tree.h"
#include "mongo/db/matcher/expression_type.h"
#include "mongo/db/matcher/match_expression_dependencies.h"
#include "mongo/db/matcher/matcher_type_set.h"
#include "mongo/db/pipeline/abt/field_map_builder.h"
#include "mongo/db/pipeline/accumulation_statement.h"
#include "mongo/db/pipeline/accumulator.h"
#include "mongo/db/pipeline/accumulator_multi.h"
#include "mongo/db/pipeline/dependencies.h"
#include "mongo/db/pipeline/expression.h"
#include "mongo/db/pipeline/expression_context.h"
#include "mongo/db/pipeline/expression_visitor.h"
#include "mongo/db/pipeline/expression_walker.h"
#include "mongo/db/pipeline/field_path.h"
#include "mongo/db/pipeline/window_function/window_function_first_last_n.h"
#include "mongo/db/pipeline/window_function/window_function_min_max.h"
#include "mongo/db/pipeline/window_function/window_function_shift.h"
#include "mongo/db/pipeline/window_function/window_function_top_bottom_n.h"
#include "mongo/db/query/bind_input_params.h"
#include "mongo/db/query/datetime/date_time_support.h"
#include "mongo/db/query/expression_walker.h"
#include "mongo/db/query/find_command.h"
#include "mongo/db/query/optimizer/defs.h"
#include "mongo/db/query/optimizer/syntax/syntax.h"
#include "mongo/db/query/projection.h"
#include "mongo/db/query/projection_parser.h"
#include "mongo/db/query/query_utils.h"
#include "mongo/db/query/sbe_stage_builder_abt_helpers.h"
#include "mongo/db/query/sbe_stage_builder_abt_holder_impl.h"
#include "mongo/db/query/sbe_stage_builder_accumulator.h"
#include "mongo/db/query/sbe_stage_builder_coll_scan.h"
#include "mongo/db/query/sbe_stage_builder_expression.h"
#include "mongo/db/query/sbe_stage_builder_filter.h"
#include "mongo/db/query/sbe_stage_builder_helpers.h"
#include "mongo/db/query/sbe_stage_builder_index_scan.h"
#include "mongo/db/query/sbe_stage_builder_projection.h"
#include "mongo/db/query/sbe_stage_builder_sbexpr_helpers.h"
#include "mongo/db/query/sbe_stage_builder_window_function.h"
#include "mongo/db/query/search/mongot_cursor.h"
#include "mongo/db/query/shard_filterer_factory_impl.h"
#include "mongo/db/query/sort_pattern.h"
#include "mongo/db/query/stage_types.h"
#include "mongo/db/query/util/make_data_structure.h"
#include "mongo/db/shard_role.h"
#include "mongo/db/storage/sorted_data_interface.h"
#include "mongo/logv2/log.h"
#include "mongo/s/shard_key_pattern.h"
#include "mongo/stdx/unordered_set.h"
#include "mongo/util/id_generator.h"
#include "mongo/util/intrusive_counter.h"
#include "mongo/util/string_map.h"
#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kQuery
namespace mongo::stage_builder {
namespace {
/**
* Generates an EOF plan. Note that even though this plan will return nothing, it will still define
* the slots specified by 'reqs'.
*/
std::pair<std::unique_ptr<sbe::PlanStage>, PlanStageSlots> generateEofPlan(
StageBuilderState& state, const PlanStageReqs& reqs, PlanNodeId nodeId) {
// If the parent is asking for a result, then set materialized result on 'forwardingReqs'.
PlanStageReqs forwardingReqs = reqs.copyForChild();
if (reqs.hasResult()) {
forwardingReqs.setResultObj();
}
// Create a new PlanStageSlots and map all the required names to the environment's Nothing slot.
PlanStageSlots outputs;
outputs.setMissingRequiredNamedSlotsToNothing(state, forwardingReqs);
auto stage = makeLimitCoScanTree(nodeId, 0);
return {std::move(stage), std::move(outputs)};
}
// Fill in the search slots based on initial cursor response from mongot.
void prepareSearchQueryParameters(PlanStageData* data, const CanonicalQuery& cq) {
if (cq.cqPipeline().empty() || !cq.isSearchQuery() || !cq.getExpCtxRaw()->uuid) {
return;
}
// Build a SearchNode in order to retrieve the search info.
auto sn = SearchNode::getSearchNode(cq.cqPipeline().front().get());
auto& env = data->env;
// Set values for QSN slots.
if (sn->limit) {
env->resetSlot(env->getSlot("searchLimit"_sd),
sbe::value::TypeTags::NumberInt64,
*sn->limit,
true /* owned */);
}
if (sn->sortSpec) {
auto sortSpec = std::make_unique<sbe::SortSpec>(*sn->sortSpec, cq.getExpCtx());
env->resetSlot(env->getSlot("searchSortSpec"_sd),
sbe::value::TypeTags::sortSpec,
sbe::value::bitcastFrom<sbe::SortSpec*>(sortSpec.release()),
true /* owned */);
}
if (auto remoteVars = sn->remoteCursorVars) {
auto name = Variables::getBuiltinVariableName(Variables::kSearchMetaId);
// Variables on the cursor must be an object.
auto varsObj = remoteVars->getField(name);
if (varsObj.ok()) {
auto [tag, val] = sbe::bson::convertFrom<false /* View */>(varsObj);
env->resetSlot(env->getSlot(name), tag, val, true /* owned */);
// Both the SBE and the classic portions of the query can reference the same value,
// and this is the only place to set the value if using SBE so we don't worry about
// inconsistency.
cq.getExpCtx()->variables.setReservedValue(
Variables::kSearchMetaId, mongo::Value(varsObj), true /* isConstant */);
if (varsObj.type() == BSONType::Object) {
auto metaValObj = varsObj.embeddedObject();
if (metaValObj.hasField("count")) {
auto& opDebug = CurOp::get(cq.getOpCtx())->debug();
opDebug.mongotCountVal = metaValObj.getField("count").wrap();
}
if (metaValObj.hasField(mongot_cursor::kSlowQueryLogFieldName)) {
auto& opDebug = CurOp::get(cq.getOpCtx())->debug();
opDebug.mongotSlowQueryLog =
metaValObj.getField(mongot_cursor::kSlowQueryLogFieldName)
.wrap(mongot_cursor::kSlowQueryLogFieldName);
}
}
}
}
}
} // namespace
sbe::value::SlotVector getSlotsOrderedByName(const PlanStageReqs& reqs,
const PlanStageSlots& outputs) {
auto requiredNamedSlots = outputs.getRequiredSlotsInOrder(reqs);
auto outputSlots = sbe::makeSV();
outputSlots.reserve(requiredNamedSlots.size());
for (const SbSlot& slot : requiredNamedSlots) {
outputSlots.emplace_back(slot.slotId);
}
return outputSlots;
}
sbe::value::SlotVector getSlotsToForward(StageBuilderState& state,
const PlanStageReqs& reqs,
const PlanStageSlots& outputs,
const sbe::value::SlotVector& exclude) {
auto requiredNamedSlots = outputs.getRequiredSlotsUnique(reqs);
auto slots = state.data->metadataSlots.getSlotVector();
if (exclude.empty()) {
for (const SbSlot& slot : requiredNamedSlots) {
if (!state.env->isSlotRegistered(slot.slotId)) {
slots.emplace_back(slot.slotId);
}
}
} else {
auto excludeSet = sbe::value::SlotSet{exclude.begin(), exclude.end()};
for (const SbSlot& slot : requiredNamedSlots) {
if (!state.env->isSlotRegistered(slot.slotId) && !excludeSet.count(slot.slotId)) {
slots.emplace_back(slot.slotId);
}
}
}
return slots;
}
/**
* Performs necessary initialization steps to execute an SBE tree 'root', including binding params
* from the current query 'cq' into the plan if it was cloned from the SBE plan cache.
* root - root node of the execution tree
* data - slot metadata (not actual parameter data!) that goes with the execution tree
* preparingFromCache - if true, 'root' and 'data' may have come from the SBE plan cache. This
* means current parameters from 'cq' need to be substituted into the execution plan.
*/
void prepareSlotBasedExecutableTree(OperationContext* opCtx,
sbe::PlanStage* root,
PlanStageData* data,
const CanonicalQuery& cq,
const MultipleCollectionAccessor& collections,
PlanYieldPolicySBE* yieldPolicy,
const bool preparingFromCache,
RemoteCursorMap* remoteCursors) {
tassert(6183502, "PlanStage cannot be null", root);
tassert(6142205, "PlanStageData cannot be null", data);
tassert(6142206, "yieldPolicy cannot be null", yieldPolicy);
root->attachToOperationContext(opCtx);
root->attachNewYieldPolicy(yieldPolicy);
// Call markShouldCollectTimingInfo() if appropriate.
auto expCtx = cq.getExpCtxRaw();
tassert(6142207, "No expression context", expCtx);
if (expCtx->explain || expCtx->mayDbProfile) {
root->markShouldCollectTimingInfo();
}
// Register this plan to yield according to the configured policy.
yieldPolicy->registerPlan(root);
auto& env = data->env;
env.ctx.remoteCursors = remoteCursors;
root->prepare(env.ctx);
// Populate/renew "shardFilterer" if there exists a "shardFilterer" slot. The slot value should
// be set to Nothing in the plan cache to avoid extending the lifetime of the ownership filter.
if (auto shardFiltererSlot = env->getSlotIfExists("shardFilterer"_sd)) {
populateShardFiltererSlot(opCtx, *env, *shardFiltererSlot, collections);
}
// Refresh "let" variables in the 'RuntimeEnvironment'.
auto ids = expCtx->variablesParseState.getDefinedVariableIDs();
auto& variables = expCtx->variables;
for (auto id : ids) {
// Variables defined in "ExpressionContext" may not always be translated into SBE slots.
if (auto it = data->staticData->variableIdToSlotMap.find(id);
it != data->staticData->variableIdToSlotMap.end()) {
auto slotId = it->second;
auto [tag, val] = sbe::value::makeValue(variables.getValue(id));
env->resetSlot(slotId, tag, val, true);
}
}
for (auto&& [id, name] : Variables::kIdToBuiltinVarName) {
// This can happen if the query that created the cache entry had no value for a system
// variable, whereas the current query has a value for the system variable but does not
// actually make use of it in the query plan.
if (id != Variables::kRootId && id != Variables::kRemoveId) {
if (auto slot = env->getSlotIfExists(name); slot && variables.hasValue(id)) {
auto [tag, val] = sbe::value::makeValue(variables.getValue(id));
env->resetSlot(*slot, tag, val, true);
}
}
}
// This block binds parameters into the main MatchExpression and any additional ones that have
// been pushed down via 'cq._cqPipeline'. The corresponding SBE plan cache key construction was
// done in encodeSBE() (canonical_query_encoder.cpp). The main MatchExpression was parameterized
// in CanonicalQuery::cqInit() and the pushed-down ones in QueryPlanner::extendWithAggPipeline()
// (query_planner.cpp).
input_params::bind(cq.getPrimaryMatchExpression(), *data, preparingFromCache);
for (auto& innerStage : cq.cqPipeline()) {
auto matchStage = dynamic_cast<DocumentSourceMatch*>(innerStage.get());
if (matchStage) {
input_params::bind(matchStage->getMatchExpression(), *data, preparingFromCache);
}
}
interval_evaluation_tree::IndexBoundsEvaluationCache indexBoundsEvaluationCache;
for (auto&& indexBoundsInfo : data->staticData->indexBoundsEvaluationInfos) {
input_params::bindIndexBounds(
cq, indexBoundsInfo, env.runtimeEnv, &indexBoundsEvaluationCache);
}
if (preparingFromCache && data->staticData->doClusteredCollectionScanSbe) {
input_params::bindClusteredCollectionBounds(cq, root, data, env.runtimeEnv);
}
if (preparingFromCache && cq.shouldParameterizeLimitSkip()) {
input_params::bindLimitSkipInputSlots(cq, data, env.runtimeEnv);
}
prepareSearchQueryParameters(data, cq);
} // prepareSlotBasedExecutableTree
std::pair<std::unique_ptr<sbe::PlanStage>, stage_builder::PlanStageData>
buildSearchMetadataExecutorSBE(OperationContext* opCtx,
const CanonicalQuery& cq,
size_t remoteCursorId,
RemoteCursorMap* remoteCursors,
PlanYieldPolicySBE* yieldPolicy) {
auto expCtx = cq.getExpCtxRaw();
Environment env(std::make_unique<sbe::RuntimeEnvironment>());
std::unique_ptr<PlanStageStaticData> data(std::make_unique<PlanStageStaticData>());
sbe::value::SlotIdGenerator slotIdGenerator;
data->resultSlot = slotIdGenerator.generate();
auto stage = sbe::SearchCursorStage::createForMetadata(expCtx->ns,
expCtx->uuid,
data->resultSlot,
remoteCursorId,
yieldPolicy,
PlanNodeId{} /* planNodeId */);
env.ctx.remoteCursors = remoteCursors;
stage->attachToOperationContext(opCtx);
stage->prepare(env.ctx);
data->cursorType = CursorTypeEnum::SearchMetaResult;
return std::make_pair(std::move(stage), PlanStageData(std::move(env), std::move(data)));
}
namespace {
void getAllNodesByTypeHelper(const QuerySolutionNode* root,
StageType type,
std::vector<const QuerySolutionNode*>& results) {
if (root->getType() == type) {
results.push_back(root);
}
for (auto&& child : root->children) {
getAllNodesByTypeHelper(child.get(), type, results);
}
}
std::vector<const QuerySolutionNode*> getAllNodesByType(const QuerySolutionNode* root,
StageType type) {
std::vector<const QuerySolutionNode*> results;
getAllNodesByTypeHelper(root, type, results);
return results;
}
std::unique_ptr<fts::FTSMatcher> makeFtsMatcher(OperationContext* opCtx,
const CollectionPtr& collection,
const std::string& indexName,
const fts::FTSQuery* ftsQuery) {
auto desc = collection->getIndexCatalog()->findIndexByName(opCtx, indexName);
tassert(5432209,
str::stream() << "index descriptor not found for index named '" << indexName
<< "' in collection '" << collection->ns().toStringForErrorMsg() << "'",
desc);
auto entry = collection->getIndexCatalog()->getEntry(desc);
tassert(5432210,
str::stream() << "index entry not found for index named '" << indexName
<< "' in collection '" << collection->ns().toStringForErrorMsg() << "'",
entry);
auto accessMethod = static_cast<const FTSAccessMethod*>(entry->accessMethod());
tassert(5432211,
str::stream() << "access method is not defined for index named '" << indexName
<< "' in collection '" << collection->ns().toStringForErrorMsg() << "'",
accessMethod);
// We assume here that node->ftsQuery is an FTSQueryImpl, not an FTSQueryNoop. In practice, this
// means that it is illegal to use the StageBuilder on a QuerySolution created by planning a
// query that contains "no-op" expressions.
auto query = dynamic_cast<const fts::FTSQueryImpl*>(ftsQuery);
tassert(5432220, "expected FTSQueryImpl", query);
return std::make_unique<fts::FTSMatcher>(*query, accessMethod->getSpec());
}
} // namespace
PlanStageSlots PlanStageSlots::makeMergedPlanStageSlots(StageBuilderState& state,
PlanNodeId nodeId,
const PlanStageReqs& reqs,
std::vector<PlanStageTree>& trees) {
tassert(8146604, "Expected 'trees' to be non-empty", !trees.empty());
PlanStageSlots outputs;
if (reqs.hasResultInfo()) {
// Merge the childeren's result infos.
mergeResultInfos(state, nodeId, trees);
}
if (reqs.hasResultObj()) {
// Assert each tree produces a materialized result.
for (auto& tree : trees) {
bool hasResultObject = tree.second.hasResultObj();
tassert(8378200, "Expected child tree to produce a result object", hasResultObject);
}
}
auto& firstTreeOutputs = trees[0].second;
for (const auto& slotName : firstTreeOutputs.getRequiredNamesInOrder(reqs)) {
outputs._data->slotNameToIdMap[slotName] = SbSlot{state.slotId()};
}
if (reqs.hasResultInfo()) {
// If 'reqs' requires ResultInfo, call setResultInfoBaseObj() to properly set a result base
// object on 'outputs' and then copy over the ResultInfo changes from the first child to the
// parent.
outputs.setResultInfoBaseObj(outputs.get(kResult));
outputs._data->resultInfoChanges.emplace(*trees[0].second._data->resultInfoChanges);
} else if (reqs.hasResultObj()) {
tassert(8428006, "Expected result object to be set", outputs.hasResultObj());
}
return outputs;
}
std::vector<PlanStageSlots::OwnedSlotName> PlanStageSlots::getRequiredNamesInOrder(
const PlanStageReqs& reqs) const {
// Get the required names from 'reqs' and store them into 'names'.
std::vector<OwnedSlotName> names(reqs._data->slotNameSet.begin(),
reqs._data->slotNameSet.end());
// Always treat as required, if it present, the slot holding the bitmap with the filtered items
// of block values.
if (has(kBlockSelectivityBitmap)) {
names.emplace_back(kBlockSelectivityBitmap);
}
// If this PlanStageSlots has ResultInfo and 'reqs.hasResult()' is true, then we need
// to get the list of changed fields and add them to 'names'.
if (reqs.hasResult() && hasResultInfo()) {
auto modified = _data->resultInfoChanges->getModifiedOrCreatedFieldSet();
for (auto&& fieldName : modified.getList()) {
names.emplace_back(OwnedSlotName(kField, fieldName));
}
}
// Sort and de-dup the list, and then return it.
std::sort(names.begin(), names.end());
auto newEnd = std::unique(names.begin(), names.end());
if (newEnd != names.end()) {
names.erase(newEnd, names.end());
}
return names;
}
SbSlotVector PlanStageSlots::getRequiredSlotsInOrder(const PlanStageReqs& reqs) const {
auto names = getRequiredNamesInOrder(reqs);
// Build the list of corresponding slots.
SbSlotVector result;
for (const auto& name : names) {
auto it = _data->slotNameToIdMap.find(name);
tassert(8146615,
str::stream() << "Could not find " << static_cast<int>(name.first) << ":'"
<< name.second << "' in the slot map, expected slot to exist",
it != _data->slotNameToIdMap.end());
result.emplace_back(it->second);
}
return result;
}
struct NameSbSlotPairLt {
using UnownedSlotName = PlanStageSlots::UnownedSlotName;
using PairType = std::pair<UnownedSlotName, SbSlot>;
bool operator()(const PairType& lhs, const PairType& rhs) const {
return lhs.first != rhs.first ? lhs.first < rhs.first
: SbSlot::Less()(lhs.second, rhs.second);
}
};
struct NameSbSlotPairEq {
using UnownedSlotName = PlanStageSlots::UnownedSlotName;
using PairType = std::pair<UnownedSlotName, SbSlot>;
bool operator()(const PairType& lhs, const PairType& rhs) const {
return lhs.first == rhs.first && SbSlot::EqualTo()(lhs.second, rhs.second);
}
};
SbSlotVector PlanStageSlots::getRequiredSlotsUnique(const PlanStageReqs& reqs) const {
auto names = getRequiredNamesInOrder(reqs);
SbSlotVector result;
// Build the list of corresponding slots.
for (const auto& name : names) {
auto it = _data->slotNameToIdMap.find(name);
tassert(8146616,
str::stream() << "Could not find " << static_cast<int>(name.first) << ":'"
<< name.second << "' in the slot map, expected slot to exist",
it != _data->slotNameToIdMap.end());
result.emplace_back(it->second);
}
// Sort and de-dup the list by SlotId.
std::sort(result.begin(), result.end(), SbSlot::Less());
auto newEnd = std::unique(result.begin(), result.end(), SbSlot::EqualTo());
if (newEnd != result.end()) {
result.erase(newEnd, result.end());
}
return result;
}
std::vector<std::pair<PlanStageSlots::UnownedSlotName, SbSlot>>
PlanStageSlots::getAllNameSlotPairsInOrder() const {
std::vector<std::pair<UnownedSlotName, SbSlot>> nameSlotPairs;
nameSlotPairs.reserve(_data->slotNameToIdMap.size());
for (auto& p : _data->slotNameToIdMap) {
nameSlotPairs.emplace_back(p.first, p.second);
}
std::sort(nameSlotPairs.begin(), nameSlotPairs.end(), NameSbSlotPairLt());
return nameSlotPairs;
}
SbSlotVector PlanStageSlots::getAllSlotsInOrder() const {
SbSlotVector result;
auto nameSlotPairs = getAllNameSlotPairsInOrder();
result.reserve(nameSlotPairs.size());
for (auto& p : nameSlotPairs) {
result.emplace_back(p.second);
}
return result;
}
void PlanStageSlots::setMissingRequiredNamedSlotsToNothing(StageBuilderState& state,
const PlanStageReqs& reqs) {
// If 'reqs' requires a result and we don't have a result, or if 'reqs' requires a materialized
// result and we don't have a materialized result, then we call setResultObj() to set
// a materialized result of Nothing on 'outputs'.
if ((reqs.hasResult() && !hasResult()) || (reqs.hasResultObj() && !hasResultObj())) {
auto nothingSlot = SbSlot{state.getNothingSlot()};
setResultObj(nothingSlot);
}
auto names = getRequiredNamesInOrder(reqs);
for (const auto& name : names) {
if (!has(name)) {
auto nothingSlot = SbSlot{state.getNothingSlot()};
set(name, nothingSlot);
}
}
}
void PlanStageSlots::clearNonRequiredSlots(const PlanStageReqs& reqs, bool saveResultObj) {
// If 'reqs' doesn't require a result object or ResultInfo, then clear the ResultInfo from
// this PlanStageSlots if it has one.
if (!reqs.hasResult() && _data->resultInfoChanges.has_value()) {
_data->resultInfoChanges.reset();
}
auto requiredNames = getRequiredNamesInOrder(reqs);
auto requiredNameSet = SlotNameSet(requiredNames.begin(), requiredNames.end());
// If 'saveResultObj' is true, then we add kResult to 'requiredNameSet' so that
// the kResult slot will not get cleared.
if (saveResultObj) {
requiredNameSet.emplace(kResult);
}
// Loop over the slot map and remove all slots that are not present in 'requiredNameSet'.
auto it = _data->slotNameToIdMap.begin();
while (it != _data->slotNameToIdMap.end()) {
auto& name = it->first;
if (requiredNameSet.contains(name)) {
++it;
} else {
_data->slotNameToIdMap.erase(it++);
}
}
}
void PlanStageSlots::mergeResultInfos(StageBuilderState& state,
PlanNodeId nodeId,
std::vector<PlanStageTree>& trees) {
// Compute the merged ProjectionEffects.
boost::optional<ProjectionEffects> mergedEffects;
for (auto&& tree : trees) {
auto& treeOutputs = tree.second;
// Assert that each tree produces either a materialized result object or a ResultInfo.
tassert(8378201,
"Expected child tree to produce a result object or a ResultInfo",
treeOutputs.hasResult());
// If 'tree' has a materialized result object, convert it into a ResultInfo (to make
// all the trees uniform).
if (treeOutputs.hasResult()) {
treeOutputs.setResultInfoBaseObj(treeOutputs.get(kResult));
}
const ProjectionEffects& treeEffects = treeOutputs.getResultInfoChanges();
if (!mergedEffects) {
mergedEffects.emplace(treeEffects);
} else {
*mergedEffects = mergedEffects->merge(treeEffects);
}
}
tassert(8378202,
"Expected default effect to be Keep or Drop",
mergedEffects->getDefaultEffect() == ProjectionEffects::kKeep ||
mergedEffects->getDefaultEffect() == ProjectionEffects::kDrop);
auto mergedModified = mergedEffects->getModifiedOrCreatedFieldSet();
// Inspect each 'tree' and populate any slots needed by 'mergedEffects' that are missing.
for (auto& tree : trees) {
auto& stage = tree.first;
auto& treeOutputs = tree.second;
sbe::SlotExprPairVector projects;
const ProjectionEffects& treeEffects = treeOutputs.getResultInfoChanges();
for (auto&& fieldName : mergedModified.getList()) {
if (!treeOutputs.has(UnownedSlotName(kField, fieldName))) {
if (treeEffects.isKeep(fieldName)) {
auto getFieldExpr =
makeFunction("getField"_sd,
makeVariable(treeOutputs.getResultInfoBaseObj()),
makeStrConstant(fieldName));
auto slot = state.slotId();
projects.emplace_back(std::pair(slot, std::move(getFieldExpr)));
treeOutputs.set(std::pair(kField, fieldName), slot);
} else {
tassert(8378203,
"Expected field to have Keep effect or Drop effect",
treeEffects.isDrop(fieldName));
auto nothingSlot = SbSlot{state.getNothingSlot()};
treeOutputs.set(std::pair(kField, fieldName), nothingSlot);
}
}
}
treeOutputs._data->resultInfoChanges.emplace(*mergedEffects);
stage = sbe::makeS<sbe::ProjectStage>(std::move(stage), std::move(projects), nodeId);
}
}
FieldSet PlanStageReqs::getNeededFieldSet() const {
if (hasResultObj()) {
return FieldSet::makeUniverseSet();
} else {
auto result = FieldSet::makeClosedSet(getFields());
if (_data->allowedSet) {
result.setUnion(*_data->allowedSet);
}
return result;
}
}
SlotBasedStageBuilder::SlotBasedStageBuilder(OperationContext* opCtx,
const MultipleCollectionAccessor& collections,
const CanonicalQuery& cq,
const QuerySolution& solution,
PlanYieldPolicySBE* yieldPolicy)
: BaseType(opCtx, cq, solution),
_collections(collections),
_mainNss(cq.nss()),
_yieldPolicy(yieldPolicy),
_env(std::make_unique<sbe::RuntimeEnvironment>()),
_data(std::make_unique<PlanStageStaticData>()),
_state(_opCtx,
_env,
_data.get(),
_cq.getExpCtxRaw()->variables,
_yieldPolicy,
&_slotIdGenerator,
&_frameIdGenerator,
&_spoolIdGenerator,
&_inListsSet,
&_collatorsMap,
&_sortSpecMap,
_cq.getExpCtx(),
_cq.getExpCtx()->needsMerge,
_cq.getExpCtx()->allowDiskUse) {
// Initialize '_data->queryCollator'.
_data->queryCollator = cq.getCollatorShared();
_data->runtimePlanningRootNodeId = solution.unextendedRootId();
// SERVER-52803: In the future if we need to gather more information from the QuerySolutionNode
// tree, rather than doing one-off scans for each piece of information, we should add a formal
// analysis pass here.
// Currently, we assume that each query operates on at most one collection, but a rooted $or
// queries can have more than one collscan stages with clustered collections.
auto [node, ct] = solution.getFirstNodeByType(STAGE_COLLSCAN);
auto [_, orCt] = solution.getFirstNodeByType(STAGE_OR);
const unsigned long numCollscanStages = ct;
const unsigned long numOrStages = orCt;
tassert(7182000,
str::stream() << "Found " << numCollscanStages << " nodes of type COLLSCAN, and "
<< numOrStages
<< " nodes of type OR, expected less than one COLLSCAN nodes or at "
"least one OR stage.",
numCollscanStages <= 1 || numOrStages > 0);
if (node) {
auto csn = static_cast<const CollectionScanNode*>(node);
bool doClusteredCollectionScanSbe = csn->doClusteredCollectionScanSbe();
_data->shouldTrackLatestOplogTimestamp = csn->shouldTrackLatestOplogTimestamp;
_data->shouldTrackResumeToken = csn->requestResumeToken;
_data->shouldUseTailableScan = csn->tailable;
_data->direction = csn->direction;
_data->doClusteredCollectionScanSbe = doClusteredCollectionScanSbe;
if (doClusteredCollectionScanSbe) {
_data->clusterKeyFieldName =
clustered_util::getClusterKeyFieldName(*(csn->clusteredIndex)).toString();
const auto& collection = _collections.getMainCollection();
const CollatorInterface* ccCollator = collection->getDefaultCollator();
if (ccCollator) {
_data->ccCollator = ccCollator->cloneShared();
}
}
}
}
void SlotBasedStageBuilder::analyzeTree(const QuerySolutionNode* root) {
using DfsItem = std::pair<const QuerySolutionNode*, size_t>;
absl::InlinedVector<DfsItem, 32> dfs;
dfs.emplace_back(DfsItem(root, 0));
while (!dfs.empty()) {
auto& dfsBack = dfs.back();
auto node = dfsBack.first;
// Skip if already analyzed this subtree.
if (_analysis.count(node)) {
dfs.pop_back();
continue;
}
auto childIdx = dfsBack.second;
if (childIdx < node->children.size()) {
dfsBack.second++;
dfs.emplace_back(DfsItem(node->children[childIdx].get(), 0));
} else {
_analysis.emplace(node, analyze(node));
dfs.pop_back();
}
}
}
QsnAnalysis SlotBasedStageBuilder::analyze(const QuerySolutionNode* node) {
switch (node->getType()) {
case STAGE_LIMIT:
case STAGE_SKIP:
case STAGE_MATCH:
case STAGE_SHARDING_FILTER:
case STAGE_SORT_SIMPLE:
case STAGE_SORT_DEFAULT: {
// Get the FieldSet produced by this node's child and return it.
return QsnAnalysis{getAnalysis(node->children[0]).allowedFieldSet};
}
case STAGE_OR:
case STAGE_AND_HASH:
case STAGE_AND_SORTED:
case STAGE_SORT_MERGE: {
// Union the FieldSets produced by all this node's children and return it.
auto allowedFields = getAnalysis(node->children[0]).allowedFieldSet;
for (size_t i = 1; i < node->children.size(); ++i) {
allowedFields.setUnion(getAnalysis(node->children[i]).allowedFieldSet);
}
return QsnAnalysis{std::move(allowedFields)};
}
case STAGE_IXSCAN: {
std::vector<std::string> result;
StringSet resultSet;
// Loop over the parts of the index's keyPattern and add each top-level field
// that is referenced to 'result', and then return 'result'.
auto ixn = static_cast<const IndexScanNode*>(node);
BSONObjIterator it(ixn->index.keyPattern);
while (it.more()) {
auto f = getTopLevelField(it.next().fieldNameStringData());
if (!resultSet.count(f)) {
auto str = f.toString();
resultSet.emplace(str);
result.emplace_back(std::move(str));
}
}
return QsnAnalysis{FieldSet::makeClosedSet(std::move(result))};
}
case STAGE_GROUP: {
std::vector<std::string> result;
result.emplace_back("_id");
// Loop over thel fields produced by the GroupNode, add them to 'result', and then
// return 'result'.
auto groupNode = static_cast<const GroupNode*>(node);
auto& accStmts = groupNode->accumulators;
for (size_t i = 0; i < accStmts.size(); ++i) {
result.emplace_back(accStmts[i].fieldName);
}
return QsnAnalysis{FieldSet::makeClosedSet(std::move(result))};
}
case STAGE_PROJECTION_DEFAULT:
case STAGE_PROJECTION_COVERED:
case STAGE_PROJECTION_SIMPLE: {
auto pn = static_cast<const ProjectionNode*>(node);
auto [paths, nodes] = getProjectNodes(pn->proj);
bool isInclusion = pn->proj.type() == projection_ast::ProjectType::kInclusion;
// Get the FieldSet produced by this node's child, update it with the effects of
// this projection, and return it.
auto allowedFields = getAnalysis(node->children[0]).allowedFieldSet;
allowedFields.setIntersect(makeAllowedFieldSet(isInclusion, paths, nodes));
allowedFields.setUnion(makeCreatedFieldSet(isInclusion, paths, nodes));
return QsnAnalysis{std::move(allowedFields)};
}
default: {
return {};
}
}
}
std::pair<std::unique_ptr<sbe::PlanStage>, PlanStageSlots> SlotBasedStageBuilder::buildTree() {
const bool needsRecordIdSlot = _data->shouldUseTailableScan || _data->shouldTrackResumeToken ||
_cq.getForceGenerateRecordId();
// We always produce a 'resultSlot'.
PlanStageReqs reqs;
reqs.setResultObj();
// We force the root stage to produce a 'recordId' if the iteration can be resumed (via a resume
// token or a tailable cursor) or if the caller simply expects to be able to read it.
reqs.setIf(kRecordId, needsRecordIdSlot);
// Set the target namespace to '_mainNss'. This is necessary as some QuerySolutionNodes that
// require a collection when stage building do not explicitly name which collection they are
// targeting.
reqs.setTargetNamespace(_mainNss);
// Build the SBE plan stage tree and return it.
return build(_root, reqs);
}
SlotBasedStageBuilder::PlanType SlotBasedStageBuilder::build(const QuerySolutionNode* root) {
// For a given SlotBasedStageBuilder instance, this build() method can only be called once.
invariant(!_buildHasStarted);
_buildHasStarted = true;
_root = root;
ON_BLOCK_EXIT([&] { _root = nullptr; });
auto [stage, outputs] = buildTree();
// Assert that we produced a 'resultSlot' and that we produced a 'recordIdSlot' if it was
// needed.
invariant(outputs.hasResultObj());
const bool needsRecordIdSlot = _data->shouldUseTailableScan || _data->shouldTrackResumeToken ||
_cq.getForceGenerateRecordId();
if (needsRecordIdSlot) {
invariant(outputs.has(kRecordId));
}
_data->resultSlot = outputs.getResultObjSlotIfExists();
_data->recordIdSlot = outputs.getSlotIfExists(stage_builder::PlanStageSlots::kRecordId);
return {std::move(stage), PlanStageData(std::move(_env), std::move(_data))};
}
std::pair<std::unique_ptr<sbe::PlanStage>, PlanStageSlots> SlotBasedStageBuilder::buildCollScan(
const QuerySolutionNode* root, const PlanStageReqs& reqs) {
tassert(6023400, "buildCollScan() does not support kSortKey", !reqs.hasSortKeys());
auto csn = static_cast<const CollectionScanNode*>(root);
auto fields = reqs.getFields();
auto [stage, outputs] = generateCollScan(_state,
getCurrentCollection(reqs),
csn,
std::move(fields),
_yieldPolicy,
reqs.getIsTailableCollScanResumeBranch());
if (reqs.has(kReturnKey)) {
// Assign the 'returnKeySlot' to be the empty object.
outputs.set(kReturnKey, SbSlot{_slotIdGenerator.generate(), TypeSignature::kObjectType});
stage = sbe::makeProjectStage(std::move(stage),
root->nodeId(),
outputs.get(kReturnKey).slotId,
makeFunction("newObj"_sd));
}
return {std::move(stage), std::move(outputs)};
}
std::pair<std::unique_ptr<sbe::PlanStage>, PlanStageSlots> SlotBasedStageBuilder::buildVirtualScan(
const QuerySolutionNode* root, const PlanStageReqs& reqs) {
using namespace std::literals;
tassert(7182001, "buildVirtualScan() does not support kSortKey", !reqs.hasSortKeys());
auto vsn = static_cast<const VirtualScanNode*>(root);
auto [inputTag, inputVal] = sbe::value::makeNewArray();
sbe::value::ValueGuard inputGuard{inputTag, inputVal};
auto inputView = sbe::value::getArrayView(inputVal);
if (vsn->docs.size()) {
inputView->reserve(vsn->docs.size());
for (auto& doc : vsn->docs) {
auto [tag, val] = makeValue(doc);
inputView->push_back(tag, val);