summaryrefslogtreecommitdiff
path: root/src/mongo/db/query/index_bounds_test.cpp
blob: d5cc470b3af721e810c8ecc252444790dc427d45 (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
/**
 *    Copyright (C) 2013 10gen Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    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
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    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 GNU Affero General 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.
 */

/**
 * This file contains tests for mongo/db/query/index_bounds.cpp
 */

#include "mongo/db/query/index_bounds.h"
#include "mongo/db/json.h"
#include "mongo/db/jsobj.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/text.h"
#include "mongo/util/mongoutils/str.h"

using namespace mongo;

namespace {

    //
    // Validation
    //

    TEST(IndexBoundsTest, ValidBasic) {
        OrderedIntervalList list("foo");
        list.intervals.push_back(Interval(BSON("" << 7 << "" << 20), true, true));
        IndexBounds bounds;
        bounds.fields.push_back(list);

        // Go forwards with data indexed forwards.
        ASSERT(bounds.isValidFor(BSON("foo" << 1), 1));
        // Go backwards with data indexed backwards.
        ASSERT(bounds.isValidFor(BSON("foo" << -1), -1));
        // Bounds are not oriented along the direction of traversal.
        ASSERT_FALSE(bounds.isValidFor(BSON("foo" << 1), -1));

        // Bounds must match the index exactly.
        ASSERT_FALSE(bounds.isValidFor(BSON("foo" << 1 << "bar" << 1), 1));
        ASSERT_FALSE(bounds.isValidFor(BSON("bar" << 1), 1));
    }

    TEST(IndexBoundsTest, ValidTwoFields) {
        OrderedIntervalList list("foo");
        list.intervals.push_back(Interval(BSON("" << 7 << "" << 20), true, true));
        IndexBounds bounds;
        bounds.fields.push_back(list);

        // Let's add another field
        OrderedIntervalList otherList("bar");
        otherList.intervals.push_back(Interval(BSON("" << 0 << "" << 3), true, true));
        bounds.fields.push_back(otherList);

        // These are OK.
        ASSERT(bounds.isValidFor(BSON("foo" << 1 << "bar" << 1), 1));
        ASSERT(bounds.isValidFor(BSON("foo" << -1 << "bar" << -1), -1));

        // Direction(s) don't match.
        ASSERT_FALSE(bounds.isValidFor(BSON("foo" << -1 << "bar" << 1), -1));
        ASSERT_FALSE(bounds.isValidFor(BSON("foo" << 1 << "bar" << -1), -1));

        // Index doesn't match.
        ASSERT_FALSE(bounds.isValidFor(BSON("foo" << 1), 1));
        ASSERT_FALSE(bounds.isValidFor(BSON("bar" << 1 << "foo" << 1), 1));
    }

    TEST(IndexBoundsTest, ValidIntervalsInOrder) {
        OrderedIntervalList list("foo");
        // Whether navigated forward or backward, there's no valid ordering for these two intervals.
        list.intervals.push_back(Interval(BSON("" << 7 << "" << 20), true, true));
        list.intervals.push_back(Interval(BSON("" << 0 << "" << 5), true, true));
        IndexBounds bounds;
        bounds.fields.push_back(list);
        ASSERT_FALSE(bounds.isValidFor(BSON("foo" << 1), 1));
        ASSERT_FALSE(bounds.isValidFor(BSON("foo" << -1), 1));
        ASSERT_FALSE(bounds.isValidFor(BSON("foo" << 1), -1));
        ASSERT_FALSE(bounds.isValidFor(BSON("foo" << -1), -1));
    }

    TEST(IndexBoundsTest, ValidNoOverlappingIntervals) {
        OrderedIntervalList list("foo");
        // overlapping intervals not allowed.
        list.intervals.push_back(Interval(BSON("" << 7 << "" << 20), true, true));
        list.intervals.push_back(Interval(BSON("" << 19 << "" << 25), true, true));
        IndexBounds bounds;
        bounds.fields.push_back(list);
        ASSERT_FALSE(bounds.isValidFor(BSON("foo" << 1), 1));
    }

    TEST(IndexBoundsTest, ValidOverlapOnlyWhenBothOpen) {
        OrderedIntervalList list("foo");
        list.intervals.push_back(Interval(BSON("" << 7 << "" << 20), true, false));
        list.intervals.push_back(Interval(BSON("" << 20 << "" << 25), false, true));
        IndexBounds bounds;
        bounds.fields.push_back(list);
        ASSERT(bounds.isValidFor(BSON("foo" << 1), 1));
    }

    //
    // Tests for OrderedIntervalList::complement()
    //

    /**
     * Get a BSONObj which represents the interval from
     * MinKey to 'end'.
     */
    BSONObj minKeyIntObj(int end) {
        BSONObjBuilder bob;
        bob.appendMinKey("");
        bob.appendNumber("", end);
        return bob.obj();
    }

    /**
     * Get a BSONObj which represents the interval from
     * 'start' to MaxKey.
     */
    BSONObj maxKeyIntObj(int start) {
        BSONObjBuilder bob;
        bob.appendNumber("", start);
        bob.appendMaxKey("");
        return bob.obj();
    }

    /**
     * Get a BSONObj which represents the interval
     * [MinKey, MaxKey].
     */
    BSONObj allValues() {
        BSONObjBuilder bob;
        bob.appendMinKey("");
        bob.appendMaxKey("");
        return bob.obj();
    }

    /**
     * Test that if we complement the OIL twice,
     * we get back the original OIL.
     */
     void testDoubleComplement(const OrderedIntervalList* oil) {
         OrderedIntervalList clone;
         for (size_t i = 0; i < oil->intervals.size(); ++i) {
             clone.intervals.push_back(oil->intervals[i]);
         }

         clone.complement();
         clone.complement();

         ASSERT_EQUALS(oil->intervals.size(), clone.intervals.size());
         for (size_t i = 0; i < oil->intervals.size(); ++i) {
             ASSERT_EQUALS(Interval::INTERVAL_EQUALS,
                oil->intervals[i].compare(clone.intervals[i]));
         }
     }

    // Complement of empty is [MinKey, MaxKey]
    TEST(IndexBoundsTest, ComplementEmptyOil) {
        OrderedIntervalList oil;
        testDoubleComplement(&oil);
        oil.complement();
        ASSERT_EQUALS(oil.intervals.size(), 1U);
        ASSERT_EQUALS(Interval::INTERVAL_EQUALS, oil.intervals[0].compare(
            Interval(allValues(), true, true)));
    }

    // Complement of [MinKey, MaxKey] is empty
    TEST(IndexBoundsTest, ComplementAllValues) {
        OrderedIntervalList oil;
        oil.intervals.push_back(Interval(allValues(), true, true));
        testDoubleComplement(&oil);
        oil.complement();
        ASSERT_EQUALS(oil.intervals.size(), 0U);
    }

    // Complement of [MinKey, 3), [5, MaxKey) is
    // [3, 5), [MaxKey, MaxKey].
    TEST(IndexBoundsTest, ComplementRanges) {
        OrderedIntervalList oil;
        oil.intervals.push_back(Interval(minKeyIntObj(3), true, false));
        oil.intervals.push_back(Interval(maxKeyIntObj(5), true, false));
        testDoubleComplement(&oil);
        oil.complement();
        ASSERT_EQUALS(oil.intervals.size(), 2U);
        ASSERT_EQUALS(Interval::INTERVAL_EQUALS, oil.intervals[0].compare(
            Interval(BSON("" << 3 << "" << 5), true, false)));

        // Make the interval [MaxKey, MaxKey].
        BSONObjBuilder bob;
        bob.appendMaxKey("");
        bob.appendMaxKey("");
        BSONObj maxKeyInt = bob.obj();

        ASSERT_EQUALS(Interval::INTERVAL_EQUALS, oil.intervals[1].compare(
            Interval(maxKeyInt, true, true)));
    }

    // Complement of (MinKey, 3), (3, MaxKey) is
    // [MinKey, MinKey], [3, 3], [MaxKey, MaxKey].
    TEST(IndexBoundsTest, ComplementRanges2) {
        OrderedIntervalList oil;
        oil.intervals.push_back(Interval(minKeyIntObj(3), false, false));
        oil.intervals.push_back(Interval(maxKeyIntObj(3), false, false));
        testDoubleComplement(&oil);
        oil.complement();
        ASSERT_EQUALS(oil.intervals.size(), 3U);

        // First interval is [MinKey, MinKey]
        BSONObjBuilder minBob;
        minBob.appendMinKey("");
        minBob.appendMinKey("");
        BSONObj minObj = minBob.obj();
        ASSERT_EQUALS(Interval::INTERVAL_EQUALS, oil.intervals[0].compare(
            Interval(minObj, true, true)));

        // Second is [3, 3]
        ASSERT_EQUALS(Interval::INTERVAL_EQUALS, oil.intervals[1].compare(
            Interval(BSON("" << 3 << "" << 3), true, true)));

        // Third is [MaxKey, MaxKey]
        BSONObjBuilder maxBob;
        maxBob.appendMaxKey("");
        maxBob.appendMaxKey("");
        BSONObj maxObj = maxBob.obj();
        ASSERT_EQUALS(Interval::INTERVAL_EQUALS, oil.intervals[2].compare(
            Interval(maxObj, true, true)));
    }

    //
    // Iteration over
    //

    TEST(IndexBoundsCheckerTest, StartKey) {
        OrderedIntervalList fooList("foo");
        fooList.intervals.push_back(Interval(BSON("" << 7 << "" << 20), true, true));

        OrderedIntervalList barList("bar");
        barList.intervals.push_back(Interval(BSON("" << 0 << "" << 5), false, false));

        IndexBounds bounds;
        bounds.fields.push_back(fooList);
        bounds.fields.push_back(barList);
        IndexBoundsChecker it(&bounds, BSON("foo" << 1 << "bar" << 1), 1);

        IndexSeekPoint seekPoint;
        it.getStartSeekPoint(&seekPoint);

        ASSERT_EQUALS(seekPoint.keySuffix[0]->numberInt(), 7);
        ASSERT_EQUALS(seekPoint.suffixInclusive[0], true);
        ASSERT_EQUALS(seekPoint.keySuffix[1]->numberInt(), 0);
        ASSERT_EQUALS(seekPoint.suffixInclusive[1], false);
    }

    TEST(IndexBoundsCheckerTest, CheckEnd) {
        OrderedIntervalList fooList("foo");
        fooList.intervals.push_back(Interval(BSON("" << 7 << "" << 20), true, true));
        fooList.intervals.push_back(Interval(BSON("" << 21 << "" << 30), true, false));

        OrderedIntervalList barList("bar");
        barList.intervals.push_back(Interval(BSON("" << 0 << "" << 5), false, false));

        IndexBounds bounds;
        bounds.fields.push_back(fooList);
        bounds.fields.push_back(barList);
        IndexBoundsChecker it(&bounds, BSON("foo" << 1 << "bar" << 1), 1);

        IndexSeekPoint seekPoint;
        IndexBoundsChecker::KeyState state;

        // Start at something in our range.
        state = it.checkKey(BSON("" << 7 << "" << 1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // Second field moves past the end, but we're not done, since there's still an interval in
        // the previous field that the key hasn't advanced to.
        state = it.checkKey(BSON("" << 20 << "" << 5), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 1);
        ASSERT(seekPoint.prefixExclusive);

        // The next index key is in the second interval for 'foo' and there is a valid interval for
        // 'bar'.
        state = it.checkKey(BSON("" << 22 << "" << 1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // The next index key is very close to the end of the open interval for foo, and it's past
        // the interval for 'bar'.  Since the interval for foo is open, we are asked to move
        // forward, since we possibly could.
        state = it.checkKey(BSON("" << 29.9 << "" << 5), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 1);
        ASSERT(seekPoint.prefixExclusive);
    }

    TEST(IndexBoundsCheckerTest, MoveIntervalForwardToNextInterval) {
        OrderedIntervalList fooList("foo");
        fooList.intervals.push_back(Interval(BSON("" << 7 << "" << 20), true, true));
        fooList.intervals.push_back(Interval(BSON("" << 21 << "" << 30), true, false));

        OrderedIntervalList barList("bar");
        barList.intervals.push_back(Interval(BSON("" << 0 << "" << 5), false, false));

        IndexBounds bounds;
        bounds.fields.push_back(fooList);
        bounds.fields.push_back(barList);
        IndexBoundsChecker it(&bounds, BSON("foo" << 1 << "bar" << 1), 1);

        IndexSeekPoint seekPoint;
        IndexBoundsChecker::KeyState state;

        // Start at something in our range.
        state = it.checkKey(BSON("" << 7 << "" << 1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // "foo" moves between two intervals.
        state = it.checkKey(BSON("" << 20.5 << "" << 1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 0);
        // Should be told to move exactly to the next interval's beginning.
        ASSERT_EQUALS(seekPoint.prefixExclusive, false);
        ASSERT_EQUALS(seekPoint.keySuffix[0]->numberInt(), 21);
        ASSERT_EQUALS(seekPoint.suffixInclusive[0], true);
        ASSERT_EQUALS(seekPoint.keySuffix[1]->numberInt(), 0);
        ASSERT_EQUALS(seekPoint.suffixInclusive[1], false);
    }

    TEST(IndexBoundsCheckerTest, MoveIntervalForwardManyIntervals) {
        OrderedIntervalList fooList("foo");
        fooList.intervals.push_back(Interval(BSON("" << 7 << "" << 20), true, true));
        fooList.intervals.push_back(Interval(BSON("" << 21 << "" << 30), true, false));
        fooList.intervals.push_back(Interval(BSON("" << 31 << "" << 40), true, false));
        fooList.intervals.push_back(Interval(BSON("" << 41 << "" << 50), true, false));

        IndexBounds bounds;
        bounds.fields.push_back(fooList);
        IndexBoundsChecker it(&bounds, BSON("foo" << 1), 1);

        IndexSeekPoint seekPoint;
        IndexBoundsChecker::KeyState state;

        // Start at something in our range.
        state = it.checkKey(BSON("" << 7), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // "foo" moves forward a few intervals.
        state = it.checkKey(BSON("" << 42), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);
    }

    TEST(IndexBoundsCheckerTest, SimpleCheckKey) {
        OrderedIntervalList fooList("foo");
        fooList.intervals.push_back(Interval(BSON("" << 7 << "" << 20), true, true));

        OrderedIntervalList barList("bar");
        barList.intervals.push_back(Interval(BSON("" << 0 << "" << 5), false, true));

        IndexBounds bounds;
        bounds.fields.push_back(fooList);
        bounds.fields.push_back(barList);
        IndexBoundsChecker it(&bounds, BSON("foo" << 1 << "bar" << 1), 1);

        IndexSeekPoint seekPoint;
        IndexBoundsChecker::KeyState state;

        // Start at something in our range.
        state = it.checkKey(BSON("" << 7 << "" << 1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // The rightmost key is past the range.  We should be told to move past the key before the
        // one whose interval we exhausted.
        state = it.checkKey(BSON("" << 7 << "" << 5.00001), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 1);
        ASSERT_EQUALS(seekPoint.prefixExclusive, true);

        // Move a little forward, but note that the rightmost key isn't in the interval yet.
        state = it.checkKey(BSON("" << 7.2 << "" << 0), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 1);
        ASSERT_EQUALS(seekPoint.prefixExclusive, false);
        ASSERT_EQUALS(seekPoint.keySuffix[1]->numberInt(), 0);
        ASSERT_EQUALS(seekPoint.suffixInclusive[1], false);

        // Move to the edge of both intervals, 20,5
        state = it.checkKey(BSON("" << 20 << "" << 5), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // And a little beyond.
        state = it.checkKey(BSON("" << 20 << "" << 5.1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::DONE);
    }

    TEST(IndexBoundsCheckerTest, FirstKeyMovedIsOKSecondKeyMustMove) {
        OrderedIntervalList fooList("foo");
        fooList.intervals.push_back(Interval(BSON("" << 0 << "" << 9), true, true));
        fooList.intervals.push_back(Interval(BSON("" << 10 << "" << 20), true, true));

        OrderedIntervalList barList("bar");
        barList.intervals.push_back(Interval(BSON("" << 0 << "" << 5), false, true));

        IndexBounds bounds;
        bounds.fields.push_back(fooList);
        bounds.fields.push_back(barList);
        IndexBoundsChecker it(&bounds, BSON("foo" << 1 << "bar" << 1), 1);

        IndexSeekPoint seekPoint;
        IndexBoundsChecker::KeyState state;

        // Start at something in our range.
        state = it.checkKey(BSON("" << 0 << "" << 1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // First key moves to next interval, second key needs to be advanced.
        state = it.checkKey(BSON("" << 10 << "" << -1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 1);
        ASSERT_EQUALS(seekPoint.prefixExclusive, false);
        ASSERT_EQUALS(seekPoint.keySuffix[1]->numberInt(), 0);
        ASSERT_EQUALS(seekPoint.suffixInclusive[1], false);
    }

    TEST(IndexBoundsCheckerTest, SecondIntervalMustRewind) {
        OrderedIntervalList first("first");
        first.intervals.push_back(Interval(BSON("" << 25 << "" << 30), true, true));

        OrderedIntervalList second("second");
        second.intervals.push_back(Interval(BSON("" << 0 << "" << 0), true, true));
        second.intervals.push_back(Interval(BSON("" << 9 << "" << 9), true, true));

        IndexBounds bounds;
        bounds.fields.push_back(first);
        bounds.fields.push_back(second);

        BSONObj idx = BSON("first" << 1 << "second" << 1);
        ASSERT(bounds.isValidFor(idx, 1));
        IndexBoundsChecker it(&bounds, idx, 1);

        IndexSeekPoint seekPoint;
        IndexBoundsChecker::KeyState state;

        state = it.checkKey(BSON("" << 25 << "" << 0), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        state = it.checkKey(BSON("" << 25 << "" << 1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 1);
        ASSERT_EQUALS(seekPoint.prefixExclusive, false);
        ASSERT_EQUALS(seekPoint.keySuffix[1]->numberInt(), 9);
        ASSERT_EQUALS(seekPoint.suffixInclusive[1], true);

        state = it.checkKey(BSON("" << 25 << "" << 9), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // First key moved forward.  The second key moved back to a valid state but it's behind
        // the interval that the checker thought it was in.
        state = it.checkKey(BSON("" << 26 << "" << 0), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);
    }

    TEST(IndexBoundsCheckerTest, SimpleCheckKeyBackwards) {
        OrderedIntervalList fooList("foo");
        fooList.intervals.push_back(Interval(BSON("" << 20 << "" << 7), true, true));

        OrderedIntervalList barList("bar");
        barList.intervals.push_back(Interval(BSON("" << 5 << "" << 0), true, false));

        IndexBounds bounds;
        bounds.fields.push_back(fooList);
        bounds.fields.push_back(barList);

        BSONObj idx = BSON("foo" << -1 << "bar" << -1);
        ASSERT(bounds.isValidFor(idx, 1));
        IndexBoundsChecker it(&bounds, idx, 1);

        IndexSeekPoint seekPoint;
        IndexBoundsChecker::KeyState state;

        // Start at something in our range.
        state = it.checkKey(BSON("" << 20 << "" << 5), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // The rightmost key is past the range.  We should be told to move past the key before the
        // one whose interval we exhausted.
        state = it.checkKey(BSON("" << 20 << "" << 0), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 1);
        ASSERT_EQUALS(seekPoint.prefixExclusive, true);

        // Move a little forward, but note that the rightmost key isn't in the interval yet.
        state = it.checkKey(BSON("" << 19 << "" << 6), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 1);
        ASSERT_EQUALS(seekPoint.prefixExclusive, false);
        ASSERT_EQUALS(seekPoint.keySuffix[1]->numberInt(), 5);
        ASSERT_EQUALS(seekPoint.suffixInclusive[1], true);

        // Move to the edge of both intervals
        state = it.checkKey(BSON("" << 7 << "" << 0.01), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // And a little beyond.
        state = it.checkKey(BSON("" << 7 << "" << 0), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::DONE);
    }

    TEST(IndexBoundsCheckerTest, CheckEndBackwards) {
        OrderedIntervalList fooList("foo");
        fooList.intervals.push_back(Interval(BSON("" << 30 << "" << 21), true, true));
        fooList.intervals.push_back(Interval(BSON("" << 20 << "" << 7), true, false));

        OrderedIntervalList barList("bar");
        barList.intervals.push_back(Interval(BSON("" << 0 << "" << 5), false, false));

        IndexBounds bounds;
        bounds.fields.push_back(fooList);
        bounds.fields.push_back(barList);

        BSONObj idx = BSON("foo" << 1 << "bar" << -1);
        ASSERT(bounds.isValidFor(idx, -1));
        IndexBoundsChecker it(&bounds, idx, -1);

        IndexSeekPoint seekPoint;
        IndexBoundsChecker::KeyState state;

        // Start at something in our range.
        state = it.checkKey(BSON("" << 30 << "" << 1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // Second field moves past the end, but we're not done, since there's still an interval in
        // the previous field that the key hasn't advanced to.
        state = it.checkKey(BSON("" << 30 << "" << 5), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 1);
        ASSERT(seekPoint.prefixExclusive);

        // The next index key is in the second interval for 'foo' and there is a valid interval for
        // 'bar'.
        state = it.checkKey(BSON("" << 20 << "" << 1), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::VALID);

        // The next index key is very close to the end of the open interval for foo, and it's past
        // the interval for 'bar'.  Since the interval for foo is open, we are asked to move
        // forward, since we possibly could.
        state = it.checkKey(BSON("" << 7.001 << "" << 5), &seekPoint);
        ASSERT_EQUALS(state, IndexBoundsChecker::MUST_ADVANCE);
        ASSERT_EQUALS(seekPoint.prefixLen, 1);
        ASSERT(seekPoint.prefixExclusive);
    }

    //
    // IndexBoundsChecker::findIntervalForField
    //

    /**
     * Returns string representation of IndexBoundsChecker::Location.
     */
    std::string toString(IndexBoundsChecker::Location location) {
        switch(location) {
        case IndexBoundsChecker::BEHIND: return "BEHIND";
        case IndexBoundsChecker::WITHIN: return "WITHIN";
        case IndexBoundsChecker::AHEAD: return "AHEAD";
        }
        invariant(0);
    }

    /**
     * Test function for findIntervalForField.
     * Constructs a list of point intervals from 'points' and searches for 'key'
     * using findIntervalForField(). Verifies expected location and index (if expectedLocation
     * is BEHIND or WITHIN).
     * 'points' is provided in BSON format: {points: [pt1, pt2, pt4, ...]
     */
    void testFindIntervalForField(int key, const BSONObj& pointsObj, const int expectedDirection,
                                  IndexBoundsChecker::Location expectedLocation,
                                  size_t expectedIntervalIndex) {
        // Create key BSONElement.
        BSONObj keyObj = BSON("" << key);
        BSONElement keyElt = keyObj.firstElement();

        // Construct point intervals.
        OrderedIntervalList oil("foo");
        BSONObjIterator i(pointsObj.getObjectField("points"));
        while (i.more()) {
            BSONElement e = i.next();
            int j = e.numberInt();
            oil.intervals.push_back(Interval(BSON("" << j << "" << j), true, true));
        }
        size_t intervalIndex = 0;
        IndexBoundsChecker::Location location =
            IndexBoundsChecker::findIntervalForField(keyElt, oil, expectedDirection, &intervalIndex);
        if (expectedLocation != location) {
            mongoutils::str::stream ss;
            ss << "Unexpected location from findIntervalForField: key=" << keyElt
               << "; intervals=" << oil.toString() << "; direction=" << expectedDirection
               << ". Expected: " << toString(expectedLocation)
               << ". Actual: " << toString(location);
            FAIL(ss);
        }
        // Check interval index if location is BEHIND or WITHIN.
        if ((IndexBoundsChecker::BEHIND == expectedLocation ||
             IndexBoundsChecker::WITHIN == expectedLocation) &&
            expectedIntervalIndex != intervalIndex) {
            mongoutils::str::stream ss;
            ss << "Unexpected interval index from findIntervalForField: key=" << keyElt
               << "; intervals=" << oil.toString() << "; direction=" << expectedDirection
               << "; location= " << toString(location)
               << ". Expected: " << expectedIntervalIndex
               << ". Actual: " << intervalIndex;
            FAIL(ss);
        }
    }

    TEST(IndexBoundsCheckerTest, FindIntervalForField) {
        // No intervals
        BSONObj pointsObj = fromjson("{points: []}");
        testFindIntervalForField(5, pointsObj, 1, IndexBoundsChecker::AHEAD, 0U);
        testFindIntervalForField(5, pointsObj, -1, IndexBoundsChecker::AHEAD, 0U);

        // One interval
        pointsObj = fromjson("{points: [5]}");
        testFindIntervalForField(4, pointsObj, 1, IndexBoundsChecker::BEHIND, 0U);
        testFindIntervalForField(5, pointsObj, 1, IndexBoundsChecker::WITHIN, 0U);
        testFindIntervalForField(6, pointsObj, 1, IndexBoundsChecker::AHEAD, 0U);

        // One interval - reverse direction
        pointsObj = fromjson("{points: [5]}");
        testFindIntervalForField(6, pointsObj, -1, IndexBoundsChecker::BEHIND, 0U);
        testFindIntervalForField(5, pointsObj, -1, IndexBoundsChecker::WITHIN, 0U);
        testFindIntervalForField(4, pointsObj, -1, IndexBoundsChecker::AHEAD, 0U);

        // Two intervals
        // Verifies off-by-one handling in upper bound of binary search.
        pointsObj = fromjson("{points: [5, 7]}");
        testFindIntervalForField(4, pointsObj, 1, IndexBoundsChecker::BEHIND, 0U);
        testFindIntervalForField(5, pointsObj, 1, IndexBoundsChecker::WITHIN, 0U);
        testFindIntervalForField(6, pointsObj, 1, IndexBoundsChecker::BEHIND, 1U);
        testFindIntervalForField(7, pointsObj, 1, IndexBoundsChecker::WITHIN, 1U);
        testFindIntervalForField(8, pointsObj, 1, IndexBoundsChecker::AHEAD, 0U);

        // Two intervals - reverse direction
        // Verifies off-by-one handling in upper bound of binary search.
        pointsObj = fromjson("{points: [7, 5]}");
        testFindIntervalForField(8, pointsObj, -1, IndexBoundsChecker::BEHIND, 0U);
        testFindIntervalForField(7, pointsObj, -1, IndexBoundsChecker::WITHIN, 0U);
        testFindIntervalForField(6, pointsObj, -1, IndexBoundsChecker::BEHIND, 1U);
        testFindIntervalForField(5, pointsObj, -1, IndexBoundsChecker::WITHIN, 1U);
        testFindIntervalForField(4, pointsObj, -1, IndexBoundsChecker::AHEAD, 0U);

        // Multiple intervals - odd number of intervals.
        pointsObj = fromjson("{points: [1, 3, 5, 7, 9]}");
        testFindIntervalForField(0, pointsObj, 1, IndexBoundsChecker::BEHIND, 0U);
        testFindIntervalForField(1, pointsObj, 1, IndexBoundsChecker::WITHIN, 0U);
        testFindIntervalForField(2, pointsObj, 1, IndexBoundsChecker::BEHIND, 1U);
        testFindIntervalForField(3, pointsObj, 1, IndexBoundsChecker::WITHIN, 1U);
        testFindIntervalForField(4, pointsObj, 1, IndexBoundsChecker::BEHIND, 2U);
        testFindIntervalForField(5, pointsObj, 1, IndexBoundsChecker::WITHIN, 2U);
        testFindIntervalForField(6, pointsObj, 1, IndexBoundsChecker::BEHIND, 3U);
        testFindIntervalForField(7, pointsObj, 1, IndexBoundsChecker::WITHIN, 3U);
        testFindIntervalForField(8, pointsObj, 1, IndexBoundsChecker::BEHIND, 4U);
        testFindIntervalForField(9, pointsObj, 1, IndexBoundsChecker::WITHIN, 4U);
        testFindIntervalForField(10, pointsObj, 1, IndexBoundsChecker::AHEAD, 0U);

        // Multiple intervals - even number of intervals, reverse direction
        // Interval order has to match direction.
        pointsObj = fromjson("{points: [7, 5, 3, 1]}");
        testFindIntervalForField(8, pointsObj, -1, IndexBoundsChecker::BEHIND, 0U);
        testFindIntervalForField(7, pointsObj, -1, IndexBoundsChecker::WITHIN, 0U);
        testFindIntervalForField(6, pointsObj, -1, IndexBoundsChecker::BEHIND, 1U);
        testFindIntervalForField(5, pointsObj, -1, IndexBoundsChecker::WITHIN, 1U);
        testFindIntervalForField(4, pointsObj, -1, IndexBoundsChecker::BEHIND, 2U);
        testFindIntervalForField(3, pointsObj, -1, IndexBoundsChecker::WITHIN, 2U);
        testFindIntervalForField(2, pointsObj, -1, IndexBoundsChecker::BEHIND, 3U);
        testFindIntervalForField(1, pointsObj, -1, IndexBoundsChecker::WITHIN, 3U);
        testFindIntervalForField(0, pointsObj, -1, IndexBoundsChecker::AHEAD, 0U);
    }

}  // namespace