summaryrefslogtreecommitdiff
path: root/src/mongo/db/exec/plan_stats.h
blob: d7336e79a3140d7fa89e4e9ff048fd12f54dbb57 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
/**
 *    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.
 */

#pragma once

#include <cstdint>
#include <cstdlib>
#include <string>
#include <vector>

#include "mongo/db/exec/plan_stats_visitor.h"
#include "mongo/db/index/multikey_paths.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/query/plan_summary_stats.h"
#include "mongo/db/query/record_id_bound.h"
#include "mongo/db/query/stage_types.h"
#include "mongo/db/record_id.h"
#include "mongo/util/container_size_helper.h"
#include "mongo/util/time_support.h"

namespace mongo {

/**
 * The interface all specific-to-stage stats provide.
 */
struct SpecificStats {
    virtual ~SpecificStats() {}

    /**
     * Make a deep copy.
     */
    virtual std::unique_ptr<SpecificStats> clone() const = 0;

    virtual uint64_t estimateObjectSizeInBytes() const = 0;

    virtual void acceptVisitor(PlanStatsConstVisitor* visitor) const = 0;
    virtual void acceptVisitor(PlanStatsMutableVisitor* visitor) = 0;
};

// Every stage has CommonStats.
struct CommonStats {
    CommonStats() = delete;

    CommonStats(const char* type)
        : stageTypeStr(type),
          works(0),
          yields(0),
          unyields(0),
          advanced(0),
          needTime(0),
          needYield(0),
          failed(false),
          isEOF(false) {}

    uint64_t estimateObjectSizeInBytes() const {
        return filter.objsize() + sizeof(*this);
    }
    // String giving the type of the stage. Not owned.
    const char* stageTypeStr;

    // Count calls into the stage.
    size_t works;
    size_t yields;
    size_t unyields;

    // How many times was this state the return value of work(...)?
    size_t advanced;
    size_t needTime;
    size_t needYield;

    // BSON representation of a MatchExpression affixed to this node. If there
    // is no filter affixed, then 'filter' should be an empty BSONObj.
    BSONObj filter;

    // Time elapsed while working inside this stage. When this field is set to boost::none,
    // timing info will not be collected during query execution.
    //
    // The field must be populated when running explain or when running with the profiler on. It
    // must also be populated when multi planning, in order to gather stats stored in the plan
    // cache.
    boost::optional<Microseconds> executionTime;

    bool failed;
    bool isEOF;
};

// The universal container for a stage's stats.
template <typename C, typename T = void*>
struct BasePlanStageStats {
    BasePlanStageStats(const C& c, T t = {}) : stageType(t), common(c) {}

    /**
     * Make a deep copy.
     */
    BasePlanStageStats<C, T>* clone() const {
        auto stats = new BasePlanStageStats<C, T>(common, stageType);
        if (specific.get()) {
            stats->specific = specific->clone();
        }
        for (size_t i = 0; i < children.size(); ++i) {
            invariant(children[i]);
            stats->children.emplace_back(children[i]->clone());
        }
        return stats;
    }

    uint64_t estimateObjectSizeInBytes() const {
        return  // Add size of each element in 'children' vector.
            container_size_helper::estimateObjectSizeInBytes(
                children,
                [](const auto& child) { return child->estimateObjectSizeInBytes(); },
                true) +
            // Exclude the size of 'common' object since is being added later.
            (common.estimateObjectSizeInBytes() - sizeof(common)) +
            // Add 'specific' object size if exists.
            (specific ? specific->estimateObjectSizeInBytes() : 0) +
            // Add size of the object.
            sizeof(*this);
    }

    auto begin() {
        return children.begin();
    }

    auto begin() const {
        return children.begin();
    }

    auto end() {
        return children.end();
    }

    auto end() const {
        return children.end();
    }

    T stageType;

    // Stats exported by implementing the PlanStage interface.
    C common;

    // Per-stage place to stash additional information
    std::unique_ptr<SpecificStats> specific;

    // Per-stage additional debug info which is opaque to the caller. Callers should not attempt to
    // process/read this BSONObj other than for dumping the results to logs or back to the user.
    BSONObj debugInfo;

    // The stats of the node's children.
    std::vector<std::unique_ptr<BasePlanStageStats<C, T>>> children;

private:
    BasePlanStageStats(const BasePlanStageStats<C, T>&) = delete;
    BasePlanStageStats& operator=(const BasePlanStageStats<C, T>&) = delete;
};

using PlanStageStats = BasePlanStageStats<CommonStats, StageType>;

struct AndHashStats : public SpecificStats {
    AndHashStats() = default;

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<AndHashStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return container_size_helper::estimateObjectSizeInBytes(mapAfterChild) + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // How many entries are in the map after each child?
    // child 'i' produced children[i].common.advanced RecordIds, of which mapAfterChild[i] were
    // intersections.
    std::vector<size_t> mapAfterChild;

    // mapAfterChild[mapAfterChild.size() - 1] WSMswere match tested.
    // commonstats.advanced is how many passed.

    // What's our current memory usage?
    size_t memUsage = 0u;

    // What's our memory limit?
    size_t memLimit = 0u;
};

struct AndSortedStats : public SpecificStats {
    AndSortedStats() = default;

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<AndSortedStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return container_size_helper::estimateObjectSizeInBytes(failedAnd) + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // How many results from each child did not pass the AND?
    std::vector<size_t> failedAnd;
};

struct CachedPlanStats : public SpecificStats {
    CachedPlanStats() = default;

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<CachedPlanStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    boost::optional<std::string> replanReason;
};

struct CollectionScanStats : public SpecificStats {
    CollectionScanStats() : docsTested(0), direction(1) {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<CollectionScanStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // How many documents did we check against our filter?
    size_t docsTested;

    // >0 if we're traversing the collection forwards. <0 if we're traversing it
    // backwards.
    int direction;

    bool tailable{false};

    // The start location of a forward scan and end location for a reverse scan.
    boost::optional<RecordIdBound> minRecord;

    // The end location of a reverse scan and start location for a forward scan.
    boost::optional<RecordIdBound> maxRecord;
};

struct CountStats : public SpecificStats {
    CountStats() : nCounted(0), nSkipped(0) {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<CountStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // The result of the count.
    long long nCounted;

    // The number of results we skipped over.
    long long nSkipped;
};

struct CountScanStats : public SpecificStats {
    CountScanStats()
        : indexVersion(0),
          isMultiKey(false),
          isPartial(false),
          isSparse(false),
          isUnique(false),
          keysExamined(0) {}

    std::unique_ptr<SpecificStats> clone() const final {
        auto specific = std::make_unique<CountScanStats>(*this);
        // BSON objects have to be explicitly copied.
        specific->keyPattern = keyPattern.getOwned();
        specific->collation = collation.getOwned();
        specific->startKey = startKey.getOwned();
        specific->endKey = endKey.getOwned();
        return specific;
    }

    uint64_t estimateObjectSizeInBytes() const {
        return container_size_helper::estimateObjectSizeInBytes(
                   multiKeyPaths,
                   [](const auto& keyPath) {
                       // Calculate the size of each std::set in 'multiKeyPaths'.
                       return container_size_helper::estimateObjectSizeInBytes(keyPath);
                   },
                   true) +
            keyPattern.objsize() + collation.objsize() + startKey.objsize() + endKey.objsize() +
            indexName.capacity() + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    std::string indexName;

    BSONObj keyPattern;

    BSONObj collation;

    // The starting/ending key(s) of the index scan.
    // startKey and endKey contain the fields of keyPattern, with values
    // that match the corresponding index bounds.
    BSONObj startKey;
    BSONObj endKey;
    // Whether or not those keys are inclusive or exclusive bounds.
    bool startKeyInclusive;
    bool endKeyInclusive;

    int indexVersion;

    // Set to true if the index used for the count scan is multikey.
    bool isMultiKey;

    // Represents which prefixes of the indexed field(s) cause the index to be multikey.
    MultikeyPaths multiKeyPaths;

    bool isPartial;
    bool isSparse;
    bool isUnique;

    size_t keysExamined;
};

struct DeleteStats : public SpecificStats {
    DeleteStats() = default;

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<DeleteStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    size_t docsDeleted = 0u;
    size_t bytesDeleted = 0u;
};

struct BatchedDeleteStats : public DeleteStats {
    BatchedDeleteStats() = default;

    // Unlike a standard multi:true delete, BatchedDeleteStage can complete with PlanStage::IS_EOF
    // before deleting all the documents that match the query, if a 'BatchedDeleteStageParams'
    // 'pass' target is met.
    //
    // True indicates the operation reaches completion because a 'pass' target is met.
    //
    // False indicates either (1) the operation hasn't reached completion or (2) the operation
    // removed all the documents that matched the criteria to reach completion - this is always the
    // case with the default 'BatchedDeleteStageParams'.
    bool passTargetMet = false;
};

struct DistinctScanStats : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        auto specific = std::make_unique<DistinctScanStats>(*this);
        // BSON objects have to be explicitly copied.
        specific->keyPattern = keyPattern.getOwned();
        specific->collation = collation.getOwned();
        specific->indexBounds = indexBounds.getOwned();
        return specific;
    }

    uint64_t estimateObjectSizeInBytes() const {
        return container_size_helper::estimateObjectSizeInBytes(
                   multiKeyPaths,
                   [](const auto& keyPath) {
                       // Calculate the size of each std::set in 'multiKeyPaths'.
                       return container_size_helper::estimateObjectSizeInBytes(keyPath);
                   },
                   true) +
            keyPattern.objsize() + collation.objsize() + indexBounds.objsize() +
            indexName.capacity() + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // How many keys did we look at while distinct-ing?
    size_t keysExamined = 0;

    BSONObj keyPattern;

    BSONObj collation;

    // Properties of the index used for the distinct scan.
    std::string indexName;
    int indexVersion = 0;

    // Set to true if the index used for the distinct scan is multikey.
    bool isMultiKey = false;

    // Represents which prefixes of the indexed field(s) cause the index to be multikey.
    MultikeyPaths multiKeyPaths;

    bool isPartial = false;
    bool isSparse = false;
    bool isUnique = false;

    // >1 if we're traversing the index forwards and <1 if we're traversing it backwards.
    int direction = 1;

    // A BSON representation of the distinct scan's index bounds.
    BSONObj indexBounds;
};

struct FetchStats : public SpecificStats {
    FetchStats() = default;

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<FetchStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // Have we seen anything that already had an object?
    size_t alreadyHasObj = 0u;

    // The total number of full documents touched by the fetch stage.
    size_t docsExamined = 0u;
};

struct IDHackStats : public SpecificStats {
    IDHackStats() : keysExamined(0), docsExamined(0) {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<IDHackStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return indexName.capacity() + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    std::string indexName;

    // Number of entries retrieved from the index while executing the idhack.
    size_t keysExamined;

    // Number of documents retrieved from the collection while executing the idhack.
    size_t docsExamined;
};

struct ReturnKeyStats : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<ReturnKeyStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }
};

struct IndexScanStats : public SpecificStats {
    IndexScanStats()
        : indexVersion(0),
          direction(1),
          isMultiKey(false),
          isPartial(false),
          isSparse(false),
          isUnique(false),
          dupsTested(0),
          dupsDropped(0),
          keysExamined(0),
          seeks(0) {}

    std::unique_ptr<SpecificStats> clone() const final {
        auto specific = std::make_unique<IndexScanStats>(*this);
        // BSON objects have to be explicitly copied.
        specific->keyPattern = keyPattern.getOwned();
        specific->collation = collation.getOwned();
        specific->indexBounds = indexBounds.getOwned();
        return specific;
    }

    uint64_t estimateObjectSizeInBytes() const {
        return container_size_helper::estimateObjectSizeInBytes(
                   multiKeyPaths,
                   [](const auto& keyPath) {
                       // Calculate the size of each std::set in 'multiKeyPaths'.
                       return container_size_helper::estimateObjectSizeInBytes(keyPath);
                   },
                   true) +
            keyPattern.objsize() + collation.objsize() + indexBounds.objsize() +
            indexName.capacity() + indexType.capacity() + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // Index type being used.
    std::string indexType;

    // name of the index being used
    std::string indexName;

    BSONObj keyPattern;

    BSONObj collation;

    int indexVersion;

    // A BSON (opaque, ie. hands off other than toString() it) representation of the bounds
    // used.
    BSONObj indexBounds;

    // >1 if we're traversing the index along with its order. <1 if we're traversing it
    // against the order.
    int direction;

    // index properties
    // Whether this index is over a field that contain array values.
    bool isMultiKey;

    // Represents which prefixes of the indexed field(s) cause the index to be multikey.
    MultikeyPaths multiKeyPaths;

    bool isPartial;
    bool isSparse;
    bool isUnique;

    size_t dupsTested;
    size_t dupsDropped;

    // Number of entries retrieved from the index during the scan.
    size_t keysExamined;

    // Number of times the index cursor is re-positioned during the execution of the scan.
    size_t seeks;
};

struct LimitStats : public SpecificStats {
    LimitStats() : limit(0) {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<LimitStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    size_t limit;
};

struct MockStats : public SpecificStats {
    MockStats() {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<MockStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }
};

struct MultiPlanStats : public SpecificStats {
    MultiPlanStats() {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<MultiPlanStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }
};

struct OrStats : public SpecificStats {
    OrStats() = default;

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<OrStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    size_t dupsTested = 0u;
    size_t dupsDropped = 0u;
};

struct ProjectionStats : public SpecificStats {
    ProjectionStats() {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<ProjectionStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return projObj.objsize() + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // Object specifying the projection transformation to apply.
    BSONObj projObj;
};

struct SortStats : public SpecificStats {
    SortStats() = default;
    SortStats(uint64_t limit, uint64_t maxMemoryUsageBytes)
        : limit(limit), maxMemoryUsageBytes(maxMemoryUsageBytes) {}

    std::unique_ptr<SpecificStats> clone() const {
        return std::make_unique<SortStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sortPattern.objsize() + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // The pattern according to which we are sorting.
    BSONObj sortPattern;

    // The number of results to return from the sort.
    uint64_t limit = 0u;

    // The maximum number of bytes of memory we're willing to use during execution of the sort. If
    // this limit is exceeded and 'allowDiskUse' is false, the query will fail at execution time. If
    // 'allowDiskUse' is true, the data will be spilled to disk.
    uint64_t maxMemoryUsageBytes = 0u;

    // The amount of data we've sorted in bytes. At various times this data may be buffered in
    // memory or disk-resident, depending on the configuration of 'maxMemoryUsageBytes' and whether
    // disk use is allowed.
    uint64_t totalDataSizeBytes = 0u;

    // The number of keys that we've sorted.
    uint64_t keysSorted = 0u;

    // The number of times that we spilled data to disk during the execution of this query.
    uint64_t spills = 0u;
};

struct MergeSortStats : public SpecificStats {
    MergeSortStats() = default;

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<MergeSortStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sortPattern.objsize() + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    size_t dupsTested = 0u;
    size_t dupsDropped = 0u;

    // The pattern according to which we are sorting.
    BSONObj sortPattern;
};

struct ShardingFilterStats : public SpecificStats {
    ShardingFilterStats() : chunkSkips(0) {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<ShardingFilterStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    size_t chunkSkips;
};

struct SkipStats : public SpecificStats {
    SkipStats() : skip(0) {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<SkipStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    size_t skip;
};

struct IntervalStats {
    // Number of results found in the covering of this interval.
    long long numResultsBuffered = 0;
    // Number of documents in this interval returned to the parent stage.
    long long numResultsReturned = 0;

    // Min distance of this interval - always inclusive.
    double minDistanceAllowed = -1;
    // Max distance of this interval - inclusive iff inclusiveMaxDistanceAllowed.
    double maxDistanceAllowed = -1;
    // True only in the last interval.
    bool inclusiveMaxDistanceAllowed = false;
};

struct NearStats : public SpecificStats {
    NearStats() : indexVersion(0) {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<NearStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return container_size_helper::estimateObjectSizeInBytes(intervalStats) +
            keyPattern.objsize() + indexName.capacity() + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    std::vector<IntervalStats> intervalStats;
    std::string indexName;
    // btree index version, not geo index version
    int indexVersion;
    BSONObj keyPattern;
};

struct UpdateStats : public SpecificStats {
    UpdateStats() : nMatched(0), nModified(0), isModUpdate(false), nUpserted(0) {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<UpdateStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return objInserted.objsize() + sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // The number of documents which match the query part of the update.
    size_t nMatched;

    // The number of documents modified by this update.
    size_t nModified;

    // True iff this is a $mod update.
    bool isModUpdate;

    // Will be 1 if this is an {upsert: true} update that did an insert, 0 otherwise.
    size_t nUpserted;

    // The object that was inserted. This is an empty document if no insert was performed.
    BSONObj objInserted;
};

struct TextMatchStats : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<TextMatchStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return parsedTextQuery.objsize() + indexPrefix.objsize() + indexName.capacity() +
            sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    std::string indexName;

    // Human-readable form of the FTSQuery associated with the text stage.
    BSONObj parsedTextQuery;

    int textIndexVersion{0};

    // Index keys that precede the "text" index key.
    BSONObj indexPrefix;

    size_t docsRejected{0};
};

struct TextOrStats : public SpecificStats {
    TextOrStats() : fetches(0) {}

    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<TextOrStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    size_t fetches;
};

struct TrialStats : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<TrialStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    size_t trialPeriodMaxWorks = 0;
    double successThreshold = 0;

    size_t trialWorks = 0;
    size_t trialAdvanced = 0;

    bool trialCompleted = false;
    bool trialSucceeded = false;
};

struct GroupStats : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<GroupStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // Tracks an estimate of the total size of all documents output by the group stage in bytes.
    size_t totalOutputDataSizeBytes = 0;

    // The number of times that we spilled data to disk while grouping the data.
    uint64_t spills = 0u;
};

struct DocumentSourceCursorStats : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<DocumentSourceCursorStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this) +
            (planSummaryStats.estimateObjectSizeInBytes() - sizeof(planSummaryStats));
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    PlanSummaryStats planSummaryStats;
};

struct DocumentSourceLookupStats : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<DocumentSourceLookupStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this) +
            (planSummaryStats.estimateObjectSizeInBytes() - sizeof(planSummaryStats));
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // Tracks the summary stats in aggregate across all executions of the subpipeline.
    PlanSummaryStats planSummaryStats;
};

struct UnionWithStats final : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<UnionWithStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this) +
            (planSummaryStats.estimateObjectSizeInBytes() - sizeof(planSummaryStats));
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // Tracks the summary stats of the subpipeline.
    PlanSummaryStats planSummaryStats;
};

struct DocumentSourceFacetStats : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<DocumentSourceFacetStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this) +
            (planSummaryStats.estimateObjectSizeInBytes() - sizeof(planSummaryStats));
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    // Tracks the cumulative summary stats across all facets.
    PlanSummaryStats planSummaryStats;
};

struct UnpackTimeseriesBucketStats final : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<UnpackTimeseriesBucketStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    size_t nBucketsUnpacked = 0u;
};

struct SampleFromTimeseriesBucketStats final : public SpecificStats {
    std::unique_ptr<SpecificStats> clone() const final {
        return std::make_unique<SampleFromTimeseriesBucketStats>(*this);
    }

    uint64_t estimateObjectSizeInBytes() const {
        return sizeof(*this);
    }

    void acceptVisitor(PlanStatsConstVisitor* visitor) const final {
        visitor->visit(this);
    }

    void acceptVisitor(PlanStatsMutableVisitor* visitor) final {
        visitor->visit(this);
    }

    size_t nBucketsDiscarded = 0u;
    size_t dupsTested = 0u;
    size_t dupsDropped = 0u;
};
}  // namespace mongo