-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
pebble_mvcc_scanner.go
1841 lines (1699 loc) · 65.4 KB
/
pebble_mvcc_scanner.go
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 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package storage
import (
"bytes"
"context"
"encoding/binary"
"sort"
"sync"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/concurrency/lock"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/uncertainty"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/pebble"
)
var maxItersBeforeSeek = util.ConstantWithMetamorphicTestRange(
"mvcc-max-iters-before-seek",
10, /* defaultValue */
0, /* min */
3, /* max */
)
// MVCCDecodingStrategy controls if and how the fetcher should decode MVCC
// timestamps from returned KV's.
type MVCCDecodingStrategy int
const (
// MVCCDecodingNotRequired is used when timestamps aren't needed.
MVCCDecodingNotRequired MVCCDecodingStrategy = iota
// MVCCDecodingRequired is used when timestamps are needed.
MVCCDecodingRequired
)
// results abstracts away a result set where pebbleMVCCScanner put()'s KVs into.
type results interface {
// clear clears the results so that its memory could be GCed.
clear()
// sizeInfo returns several pieces of information about the current size of
// the results:
// - the number of KVs currently in the results,
// - the current memory footprint of the results in bytes,
// - the increment for how much the memory footprint of the results will
// increase (in bytes) if a KV (with the corresponding lengths of the key
// and the value parts) is put into it.
//
// Note that we chose to squash all these things into a single method rather
// than defining a separate method for each parameter out of performance
// considerations.
sizeInfo(lenKey, lenValue int) (numKeys, numBytes, numBytesInc int64)
// put adds a KV into the results. An error is returned if the memory
// reservation is denied by the memory account.
put(_ context.Context, mvccKey []byte, value []byte, memAccount *mon.BoundAccount, maxNewSize int) error
// continuesFirstRow returns true if the given key belongs to the same SQL
// row as the first KV pair in the result. If the given key is not a valid
// SQL row key, returns false.
//
// This method is called _after_ having called put() with no error at least
// once, meaning that at least one key is in the results.
//
// Only called when wholeRows option is enabled.
continuesFirstRow(key roachpb.Key) bool
// maybeTrimPartialLastRow removes the last KV pairs from the result that
// are part of the same SQL row as the given key, returning the earliest key
// removed.
//
// pebbleMVCCScanner.getOne can call this method only _before_ calling
// put(). This constraint ensures that for the singleResults implementation
// of this interface, when this method is called, there is no buffered KV
// (i.e. there is no KV that has been `put` into the results but not yet
// returned on the NextKVer.NextKV call). This allows for the singleResults
// to synchronize with the colfetcher.cFetcher (via the
// storage.FirstKeyOfRowGetter) to obtain the first key of the SQL row if
// the given key belongs to that row.
//
// Only called when wholeRows option is enabled.
maybeTrimPartialLastRow(key roachpb.Key) (roachpb.Key, error)
// lastRowHasFinalColumnFamily returns true if the last key in the result is
// the maximum column family ID of the row. If so, we know that the row is
// complete. However, the inverse is not true: the final column families of
// the row may be omitted, in which case the caller has to scan to the next
// key to find out whether the row is complete.
//
// This method is called _after_ having called put() with no error at least
// once, meaning that at least one key is in the results.
//
// Only called when wholeRows option is enabled.
lastRowHasFinalColumnFamily(reverse bool) bool
}
// Struct to store MVCCScan / MVCCGet in the same binary format as that
// expected by MVCCScanDecodeKeyValue.
type pebbleResults struct {
count int64
bytes int64
repr []byte
bufs [][]byte
// lastOffsets is a ring buffer that keeps track of byte offsets for the last
// N KV pairs. It is used to discard a partial SQL row at the end of the
// result via maybeTrimPartialLastRows() -- such rows can span multiple KV
// pairs. The length of lastOffsets is interpreted as the maximum expected SQL
// row size (i.e. number of column families).
//
// lastOffsets is initialized with a fixed length giving the N number of last
// KV pair offsets to track. lastOffsetIdx contains the index in lastOffsets
// where the next KV byte offset will be written, wrapping around to 0 when it
// reaches the end of lastOffsets.
//
// The lastOffsets values are byte offsets in p.repr and p.bufs. The latest
// lastOffset (i.e. the one at lastOffsetIdx-1) will be an offset in p.repr.
// When iterating backwards through the ring buffer and crossing a byte offset
// of 0, the next iterated byte offset in the ring buffer (at i-1) will then
// point to the previous buffer in p.bufs.
//
// Actual and default 0 values in the slice are disambiguated when iterating
// backwards through p.repr and p.bufs. If we iterate to the start of all byte
// buffers without iterating through all of lastOffsets (i.e. when there are
// fewer KV pairs than the length of lastOffsets), then we must be at the start
// of lastOffsets, and any 0 values at the end are of no interest.
lastOffsetsEnabled bool // NB: significantly faster than checking lastOffsets != nil
lastOffsets []int
lastOffsetIdx int
}
// clear implements the results interface.
func (p *pebbleResults) clear() {
*p = pebbleResults{}
}
// Key value lengths take up 8 bytes (2 x Uint32).
const pebbleResultsKVLenSize = 8
func pebbleResultsKVSizeOf(lenKey, lenValue int) int {
return pebbleResultsKVLenSize + lenKey + lenValue
}
// sizeInfo implements the results interface.
func (p *pebbleResults) sizeInfo(lenKey, lenValue int) (numKeys, numBytes, numBytesInc int64) {
numKeys = p.count
numBytes = p.bytes
numBytesInc = int64(pebbleResultsKVSizeOf(lenKey, lenValue))
return numKeys, numBytes, numBytesInc
}
// put implements the results interface.
//
// The repr that MVCCScan / MVCCGet expects to provide as output goes:
// <valueLen:Uint32><keyLen:Uint32><Key><Value>
// This function adds to repr in that format.
// - maxNewSize, if positive, indicates the maximum capacity for a new repr that
// can be allocated. It is assumed that maxNewSize (when positive) is sufficient
// for the new key-value pair.
func (p *pebbleResults) put(
ctx context.Context, key []byte, value []byte, memAccount *mon.BoundAccount, maxNewSize int,
) error {
const minSize = 16
const maxSize = 128 << 20 // 128 MB
// We maintain a list of buffers, always encoding into the last one (a.k.a.
// pebbleResults.repr). The size of the buffers is exponentially increasing,
// capped at maxSize. The exponential increase allows us to amortize the
// cost of the allocation over multiple put calls. If this (key, value) pair
// needs capacity greater than maxSize, we allocate exactly the size needed.
lenKey := len(key)
lenValue := len(value)
lenToAdd := pebbleResultsKVSizeOf(lenKey, lenValue)
if len(p.repr)+lenToAdd > cap(p.repr) {
// Exponential increase by default, while ensuring that we respect
// - a hard lower bound of lenToAdd
// - a soft upper bound of maxSize
// - a hard upper bound of maxNewSize (if set).
if maxNewSize > 0 && maxNewSize < lenToAdd {
// Hard upper bound is greater than hard lower bound - this is a
// violation of our assumptions.
return errors.AssertionFailedf("maxNewSize %dB is not sufficient, %dB required", maxNewSize, lenToAdd)
}
// Exponential growth to ensure newSize >= lenToAdd.
newSize := 2 * cap(p.repr)
if newSize == 0 || newSize > maxSize {
// If the previous buffer exceeded maxSize, we don't double its
// capacity for next allocation, and instead reset the exponential
// increase, in case we had a stray huge key-value.
newSize = minSize
}
for newSize < lenToAdd {
newSize *= 2
}
// Respect soft upper-bound before hard lower-bound, since it could be
// lower than hard lower-bound.
if newSize > maxSize {
newSize = maxSize
}
// Respect hard upper-bound.
if maxNewSize > 0 && newSize > maxNewSize {
newSize = maxNewSize
}
// Now respect hard lower-bound.
if newSize < lenToAdd {
newSize = lenToAdd
}
if len(p.repr) > 0 {
p.bufs = append(p.bufs, p.repr)
}
if err := memAccount.Grow(ctx, int64(newSize)); err != nil {
return err
}
p.repr = nonZeroingMakeByteSlice(newSize)[:0]
}
startIdx := len(p.repr)
p.repr = p.repr[:startIdx+lenToAdd]
binary.LittleEndian.PutUint32(p.repr[startIdx:], uint32(lenValue))
binary.LittleEndian.PutUint32(p.repr[startIdx+4:], uint32(lenKey))
copy(p.repr[startIdx+pebbleResultsKVLenSize:], key)
copy(p.repr[startIdx+pebbleResultsKVLenSize+lenKey:], value)
p.count++
p.bytes += int64(lenToAdd)
// If we're tracking KV offsets, update the ring buffer.
if p.lastOffsetsEnabled {
p.lastOffsets[p.lastOffsetIdx] = startIdx
p.lastOffsetIdx++
// NB: Branching is significantly faster than modulo in benchmarks, likely
// because of a high branch prediction hit rate.
if p.lastOffsetIdx == len(p.lastOffsets) {
p.lastOffsetIdx = 0
}
}
return nil
}
// continuesFirstRow implements the results interface.
func (p *pebbleResults) continuesFirstRow(key roachpb.Key) bool {
repr := p.repr
if len(p.bufs) > 0 {
repr = p.bufs[0]
}
if len(repr) == 0 {
return true // no rows in the result
}
rowPrefix := getRowPrefix(key)
if rowPrefix == nil {
return false
}
return bytes.Equal(rowPrefix, getRowPrefix(extractResultKey(repr)))
}
// keyHasFinalColumnFamily returns whether the given key corresponds to the last
// column family in a SQL row. Returns false if the key is not a valid SQL key.
func keyHasFinalColumnFamily(key roachpb.Key, maxFamilyID uint32, reverse bool) bool {
colFamilyID, err := keys.DecodeFamilyKey(key)
if err != nil {
return false
}
if reverse {
return colFamilyID == 0
}
return colFamilyID == maxFamilyID
}
// lastRowHasFinalColumnFamily implements the results interface.
func (p *pebbleResults) lastRowHasFinalColumnFamily(reverse bool) bool {
lastOffsetIdx := p.lastOffsetIdx - 1 // p.lastOffsetIdx is where next offset would be stored
if lastOffsetIdx < 0 {
lastOffsetIdx = len(p.lastOffsets) - 1
}
lastOffset := p.lastOffsets[lastOffsetIdx]
key := extractResultKey(p.repr[lastOffset:])
return keyHasFinalColumnFamily(key, uint32(len(p.lastOffsets)-1), reverse)
}
// maybeTrimPartialLastRow implements the results interface.
//
// The row cannot be made up of more KV pairs than given by len(lastOffsets),
// otherwise an error is returned. Must be called before finish().
func (p *pebbleResults) maybeTrimPartialLastRow(nextKey roachpb.Key) (roachpb.Key, error) {
if !p.lastOffsetsEnabled || len(p.repr) == 0 {
return nil, nil
}
trimRowPrefix := getRowPrefix(nextKey)
if trimRowPrefix == nil {
return nil, nil
}
var firstTrimmedKey roachpb.Key
// We're iterating backwards through the p.lastOffsets ring buffer, starting
// at p.lastOffsetIdx-1 (which is where the last KV was stored). The loop
// condition simply makes sure we limit the number of iterations to the size
// of the ring buffer, to prevent wrapping around.
for i := 0; i < len(p.lastOffsets); i++ {
lastOffsetIdx := p.lastOffsetIdx - 1 // p.lastOffsetIdx is where next offset would be stored
if lastOffsetIdx < 0 {
lastOffsetIdx = len(p.lastOffsets) - 1
}
lastOffset := p.lastOffsets[lastOffsetIdx]
// The remainder of repr from the offset is now a single KV.
repr := p.repr[lastOffset:]
key := extractResultKey(repr)
rowPrefix := getRowPrefix(key)
// If the prefix belongs to a different row, we're done trimming.
if !bytes.Equal(rowPrefix, trimRowPrefix) {
return firstTrimmedKey, nil
}
// Remove this KV pair.
p.repr = p.repr[:lastOffset]
p.count--
p.bytes -= int64(len(repr))
firstTrimmedKey = key
p.lastOffsetIdx = lastOffsetIdx
p.lastOffsets[lastOffsetIdx] = 0
if len(p.repr) == 0 {
if len(p.bufs) == 0 {
// The entire result set was trimmed, so we're done.
return firstTrimmedKey, nil
}
// Pop the last buf back into repr.
p.repr = p.bufs[len(p.bufs)-1]
p.bufs = p.bufs[:len(p.bufs)-1]
}
}
return nil, errors.Errorf("row exceeds expected max size (%d): %s", len(p.lastOffsets), nextKey)
}
func (p *pebbleResults) finish() [][]byte {
if len(p.repr) > 0 {
p.bufs = append(p.bufs, p.repr)
p.repr = nil
}
return p.bufs
}
// getRowPrefix decodes a SQL row prefix from the given key. Returns nil if the
// key is not a valid SQL row, or if the prefix is the entire key.
func getRowPrefix(key roachpb.Key) []byte {
if len(key) == 0 {
return nil
}
n, err := keys.GetRowPrefixLength(key)
if err != nil || n <= 0 || n >= len(key) {
return nil
}
return key[:n]
}
// extractResultKey takes in a binary KV result representation, finds the raw
// key, decodes it as an MVCC key, and returns the key (without timestamp).
// Returns nil if the key could not be decoded. repr must be a valid, non-empty
// KV representation, otherwise this may panic.
func extractResultKey(repr []byte) roachpb.Key {
keyLen := binary.LittleEndian.Uint32(repr[4:8])
key, ok := DecodeEngineKey(repr[8 : 8+keyLen])
if !ok {
return nil
}
return key.Key
}
// pebbleMVCCScanner handles MVCCScan / MVCCGet using a Pebble iterator.
type pebbleMVCCScanner struct {
parent MVCCIterator
// memAccount is used to account for the size of the scan results.
memAccount *mon.BoundAccount
// lockTable is used to determine whether keys are locked in the in-memory
// lock table when scanning with the skipLocked option.
lockTable LockTableView
reverse bool
peeked bool
// Iteration bounds. Does not contain MVCC timestamp.
start, end roachpb.Key
// Timestamp with which MVCCScan/MVCCGet was called.
ts hlc.Timestamp
// Max number of keys to return.
maxKeys int64
// Stop adding keys once p.result.bytes matches or exceeds this threshold,
// if nonzero.
targetBytes int64
// If true, return an empty result if the first result exceeds targetBytes.
allowEmpty bool
// If set, don't return partial SQL rows (spanning multiple KV pairs) when
// hitting a limit. Partial rows at the end of the result will be trimmed. If
// allowEmpty is false, and the partial row is the first row in the result,
// the row will instead be completed by fetching additional KV pairs.
wholeRows bool
// Stop adding intents and abort scan once maxIntents threshold is reached.
// This limit is only applicable to consistent scans since they return
// intents as an error.
// Not used in inconsistent scans.
// Ignored if zero.
maxIntents int64
// Resume fields describe the resume span to return. resumeReason must be set
// to a non-zero value to return a resume span, the others are optional.
resumeReason roachpb.ResumeReason
resumeKey roachpb.Key // if unset, falls back to p.advanceKey()
resumeNextBytes int64 // set when targetBytes is exceeded
// Transaction epoch and sequence number.
txn *roachpb.Transaction
txnEpoch enginepb.TxnEpoch
txnSequence enginepb.TxnSeq
txnIgnoredSeqNums []enginepb.IgnoredSeqNumRange
// Uncertainty related fields.
uncertainty uncertainty.Interval
checkUncertainty bool
// Metadata object for unmarshalling intents.
meta enginepb.MVCCMetadata
// Bools copied over from MVCC{Scan,Get}Options. See the comment on the
// package level MVCCScan for what these mean.
inconsistent bool
skipLocked bool
tombstones bool
failOnMoreRecent bool
keyBuf []byte
savedBuf []byte
lazyFetcherBuf pebble.LazyFetcher
lazyValueBuf []byte
// cur* variables store the "current" record we're pointing to. Updated in
// updateCurrent. Note that the timestamp can be clobbered in the case of
// adding an intent from the intent history but is otherwise meaningful.
curUnsafeKey MVCCKey
curRawKey []byte
curUnsafeValue MVCCValue
curRawValue pebble.LazyValue
curRangeKeys MVCCRangeKeyStack
savedRangeKeys MVCCRangeKeyStack
results results
intents pebble.Batch
// mostRecentTS stores the largest timestamp observed that is equal to or
// above the scan timestamp. Only applicable if failOnMoreRecent is true. If
// set and no other error is hit, a WriteToOld error will be returned from
// the scan. mostRecentKey is one of the keys (not necessarily at
// mostRecentTS) that was more recent than the scan.
mostRecentTS hlc.Timestamp
mostRecentKey roachpb.Key
// Stores any error returned. If non-nil, iteration short circuits.
err error
// Number of iterations to try before we do a Seek/SeekReverse. Stays within
// [0, maxItersBeforeSeek] and defaults to maxItersBeforeSeek/2 .
itersBeforeSeek int
// machine is the state machine for how the iterator should be advanced in
// order to handle scans and reverse scans.
machine struct {
// fn indicates the advance function that needs to be called next.
fn advanceFn
// origKey is a temporary buffer used to store the "original key" when
// advancing the iterator at the new key. It is backed by keyBuf.
origKey []byte
}
}
type advanceFn int
const (
_ advanceFn = iota
// "Forward" advance states, used for non-reverse scans.
//
// advanceKeyForward indicates that the iterator needs to be advanced to the
// next key.
advanceKeyForward
// advanceKeyAtEndForward indicates that the iterator has reached the end in
// the forward direction.
advanceKeyAtEndForward
// advanceKeyAtNewKeyForward indicates that the iterator has just reached a
// new key.
advanceKeyAtNewKeyForward
// "Reverse" advance states, used for reverse scans.
//
// advanceKeyReverse indicates that the iterator needs to be advanced to the
// previous key.
advanceKeyReverse
// advanceKeyAtEndReverse indicates that the iterator has reached the end in
// the reverse direction.
advanceKeyAtEndReverse
// advanceKeyAtNewKeyReverse indicates that the iterator needs to be
// advanced to the key before the key that has just been reached.
advanceKeyAtNewKeyReverse
)
// Pool for allocating pebble MVCC Scanners.
var pebbleMVCCScannerPool = sync.Pool{
New: func() interface{} {
return &pebbleMVCCScanner{}
},
}
func (p *pebbleMVCCScanner) release() {
// Discard most memory references before placing in pool.
*p = pebbleMVCCScanner{
keyBuf: p.keyBuf,
}
pebbleMVCCScannerPool.Put(p)
}
// init sets bounds on the underlying pebble iterator, and initializes other
// fields not set by the calling method.
func (p *pebbleMVCCScanner) init(
txn *roachpb.Transaction, ui uncertainty.Interval, results results,
) {
p.itersBeforeSeek = maxItersBeforeSeek / 2
p.results = results
if txn != nil {
p.txn = txn
p.txnEpoch = txn.Epoch
p.txnSequence = txn.Sequence
p.txnIgnoredSeqNums = txn.IgnoredSeqNums
}
p.uncertainty = ui
// We must check uncertainty even if p.ts >= local_uncertainty_limit
// because the local uncertainty limit cannot be applied to values with
// synthetic timestamps. We are only able to skip uncertainty checks if
// p.ts >= global_uncertainty_limit.
p.checkUncertainty = p.ts.Less(p.uncertainty.GlobalLimit)
}
// get seeks to the start key exactly once and adds one KV to the result set.
func (p *pebbleMVCCScanner) get(ctx context.Context) {
p.parent.SeekGE(MVCCKey{Key: p.start})
if !p.iterValid() {
return
}
var added bool
if p.processRangeKeys(true /* seeked */, false /* reverse */) {
if p.updateCurrent() {
_, added = p.getOne(ctx)
}
}
p.maybeFailOnMoreRecent()
// Unlike scans, if tombstones are enabled, we synthesize point tombstones for
// MVCC range tombstones even if there is no existing point key below it.
// These are often needed for e.g. conflict checks.
if p.tombstones && !added && p.err == nil {
if rkv, ok := p.coveredByRangeKey(hlc.MinTimestamp); ok {
p.addSynthetic(ctx, p.curRangeKeys.Bounds.Key, rkv)
}
}
}
// seekToStartOfScan positions the scanner at the initial key.
func (p *pebbleMVCCScanner) seekToStartOfScan() (ok bool) {
if p.reverse {
if !p.iterSeekReverse(MVCCKey{Key: p.end}) {
p.maybeFailOnMoreRecent() // may have seen a conflicting range key
return false
}
p.machine.fn = advanceKeyReverse
} else {
if !p.iterSeek(MVCCKey{Key: p.start}) {
p.maybeFailOnMoreRecent() // may have seen a conflicting range key
return false
}
p.machine.fn = advanceKeyForward
}
return true
}
// advance advances the iterator according to the current state of the state
// machine.
func (p *pebbleMVCCScanner) advance() bool {
switch p.machine.fn {
case advanceKeyForward:
return p.advanceKeyForward()
case advanceKeyAtEndForward:
// We've reached the end of the iterator and there is
// nothing left to do.
return false
case advanceKeyAtNewKeyForward:
// We're already at the new key so there is nothing to do.
p.machine.fn = advanceKeyForward
return true
case advanceKeyReverse:
return p.advanceKeyReverse()
case advanceKeyAtEndReverse:
p.machine.fn = advanceKeyReverse
return p.advanceKeyAtEndReverse()
case advanceKeyAtNewKeyReverse:
p.machine.fn = advanceKeyReverse
return p.advanceKeyAtNewKeyReverse()
default:
p.err = errors.AssertionFailedf("unexpected advanceFn: %d", p.machine.fn)
return false
}
}
// scan iterates until a limit is exceeded, the underlying iterator is
// exhausted, or an error is encountered. If a limit was exceeded, it returns a
// resume span, resume reason, and for targetBytes the size of the next result.
func (p *pebbleMVCCScanner) scan(
ctx context.Context,
) (*roachpb.Span, roachpb.ResumeReason, int64, error) {
if p.wholeRows && !p.results.(*pebbleResults).lastOffsetsEnabled {
return nil, 0, 0, errors.AssertionFailedf("cannot use wholeRows without trackLastOffsets")
}
if !p.seekToStartOfScan() {
return nil, 0, 0, p.err
}
for ok := true; ok; {
ok, _ = p.getOne(ctx)
if ok {
ok = p.advance()
}
}
return p.afterScan()
}
// afterScan checks whether some limit was exceeded during the scan, and if so,
// it returns a resume span, resume reason, and for targetBytes the size of the
// next result.
func (p *pebbleMVCCScanner) afterScan() (*roachpb.Span, roachpb.ResumeReason, int64, error) {
p.maybeFailOnMoreRecent()
if p.err != nil {
return nil, 0, 0, p.err
}
if p.resumeReason != 0 {
resumeKey := p.resumeKey
if len(resumeKey) == 0 {
if p.reverse {
if !p.advanceKeyReverse() {
return nil, 0, 0, nil // nothing to resume
}
} else {
if !p.advanceKeyForward() {
return nil, 0, 0, nil // nothing to resume
}
}
resumeKey = p.curUnsafeKey.Key
}
var resumeSpan *roachpb.Span
if p.reverse {
// NB: this is equivalent to:
// append(roachpb.Key(nil), resumeKey...).Next()
// but with half the allocations.
resumeKeyCopy := make(roachpb.Key, len(resumeKey), len(resumeKey)+1)
copy(resumeKeyCopy, resumeKey)
resumeSpan = &roachpb.Span{
Key: p.start,
EndKey: resumeKeyCopy.Next(),
}
} else {
resumeSpan = &roachpb.Span{
Key: append(roachpb.Key(nil), resumeKey...),
EndKey: p.end,
}
}
return resumeSpan, p.resumeReason, p.resumeNextBytes, nil
}
return nil, 0, 0, nil
}
// Increments itersBeforeSeek while ensuring it stays <= maxItersBeforeSeek
func (p *pebbleMVCCScanner) incrementItersBeforeSeek() {
p.itersBeforeSeek++
if p.itersBeforeSeek > maxItersBeforeSeek {
p.itersBeforeSeek = maxItersBeforeSeek
}
}
// Decrements itersBeforeSeek while ensuring it stays positive.
func (p *pebbleMVCCScanner) decrementItersBeforeSeek() {
p.itersBeforeSeek--
if p.itersBeforeSeek < 1 {
if maxItersBeforeSeek > 0 {
p.itersBeforeSeek = 1
} else if p.itersBeforeSeek < 0 {
// maxItersBeforeSeek == 0 && p.itersBeforeSeek < 0.
p.itersBeforeSeek = 0
}
}
}
// Try to read from the current value's intent history. Assumes p.meta has been
// unmarshalled already. Returns found = true if a value was found and returned.
func (p *pebbleMVCCScanner) getFromIntentHistory() (value []byte, found bool) {
intentHistory := p.meta.IntentHistory
// upIdx is the index of the first intent in intentHistory with a sequence
// number greater than our transaction's sequence number. Subtract 1 from it
// to get the index of the intent with the highest sequence number that is
// still less than or equal to p.txnSeq.
upIdx := sort.Search(len(intentHistory), func(i int) bool {
return intentHistory[i].Sequence > p.txnSequence
})
// If the candidate intent has a sequence number that is ignored by this txn,
// iterate backward along the sorted intent history until we come across an
// intent which isn't ignored.
//
// TODO(itsbilal): Explore if this iteration can be improved through binary
// search.
for upIdx > 0 && enginepb.TxnSeqIsIgnored(p.meta.IntentHistory[upIdx-1].Sequence, p.txnIgnoredSeqNums) {
upIdx--
}
if upIdx == 0 {
// It is possible that no intent exists such that the sequence is less
// than the read sequence, and is not ignored by this transaction.
// In this case, we cannot read a value from the intent history.
return nil, false
}
intent := &p.meta.IntentHistory[upIdx-1]
return intent.Value, true
}
// Returns a write too old error if an error is not already set on the scanner
// and a more recent value was found during the scan.
func (p *pebbleMVCCScanner) maybeFailOnMoreRecent() {
if p.err != nil || p.mostRecentTS.IsEmpty() {
return
}
// The txn can't write at the existing timestamp, so we provide the error
// with the timestamp immediately after it.
p.err = roachpb.NewWriteTooOldError(p.ts, p.mostRecentTS.Next(), p.mostRecentKey)
p.results.clear()
p.intents.Reset()
}
// Returns an uncertainty error with the specified value and local timestamps,
// along with context about the reader.
func (p *pebbleMVCCScanner) uncertaintyError(
valueTs hlc.Timestamp, localTs hlc.ClockTimestamp,
) (ok bool) {
p.err = roachpb.NewReadWithinUncertaintyIntervalError(
p.ts, p.uncertainty.LocalLimit, p.txn, valueTs, localTs)
p.results.clear()
p.intents.Reset()
return false
}
// Get one tuple into the result set. This method will make at most one
// 'results.put' call regardless of whether 'put' returns an error or not.
// - ok indicates whether the iteration should continue.
// - added indicates whether a tuple was included into the result set.
// (ok=true, added=false) indicates that the current key was skipped for some
// reason, but the iteration should continue.
// (ok=false, added=true) indicates that the KV was included into the result but
// the iteration should stop.
//
// The scanner must be positioned on a point key, possibly with an overlapping
// range key. Range keys are processed separately in processRangeKeys().
func (p *pebbleMVCCScanner) getOne(ctx context.Context) (ok, added bool) {
if !p.curUnsafeKey.Timestamp.IsEmpty() {
// Range key where read ts >= range key ts >= point key ts. Synthesize a
// point tombstone for it. Range key conflict checks are done in
// processRangeKeys().
if rkv, ok := p.coveredByRangeKey(p.curUnsafeKey.Timestamp); ok {
return p.addSynthetic(ctx, p.curUnsafeKey.Key, rkv)
}
// We are eagerly fetching and decoding the value, even though it may be
// too recent. With some care, this could be optimized to be lazy.
v, valid := p.getFromLazyValue()
if !valid {
return false, false
}
if extended, valid := p.tryDecodeCurrentValueSimple(v); !valid {
return false, false
} else if extended {
if !p.decodeCurrentValueExtended(v) {
return false, false
}
}
// ts < read_ts
if p.curUnsafeKey.Timestamp.Less(p.ts) {
// 1. Fast path: there is no intent and our read timestamp is newer
// than the most recent version's timestamp.
return p.add(ctx, p.curUnsafeKey.Key, p.curRawKey, p.curUnsafeValue.Value.RawBytes)
}
// ts == read_ts
if p.curUnsafeKey.Timestamp.EqOrdering(p.ts) {
if p.failOnMoreRecent {
// 2. Our txn's read timestamp is equal to the most recent
// version's timestamp and the scanner has been configured to
// throw a write too old error on equal or more recent versions.
if p.skipLocked {
if locked, ok := p.isKeyLockedByConflictingTxn(ctx, p.curRawKey); !ok {
return false, false
} else if locked {
// 2a. the scanner was configured to skip locked keys, and
// this key was locked, so we can advance past it without
// raising the write too old error.
return true /* ok */, false
}
}
// 2b. We need to raise a write too old error. Merge the current
// timestamp with the maximum timestamp we've seen so we know to
// return an error, but then keep scanning so that we can return
// the largest possible time.
p.mostRecentTS.Forward(p.curUnsafeKey.Timestamp)
if len(p.mostRecentKey) == 0 {
p.mostRecentKey = append(p.mostRecentKey, p.curUnsafeKey.Key...)
}
return true /* ok */, false
}
// 3. There is no intent and our read timestamp is equal to the most
// recent version's timestamp.
return p.add(ctx, p.curUnsafeKey.Key, p.curRawKey, p.curUnsafeValue.Value.RawBytes)
}
// ts > read_ts
if p.failOnMoreRecent {
// 4. Our txn's read timestamp is less than the most recent
// version's timestamp and the scanner has been configured to
// throw a write too old error on equal or more recent versions.
if p.skipLocked {
if locked, ok := p.isKeyLockedByConflictingTxn(ctx, p.curRawKey); !ok {
return false, false
} else if locked {
// 4a. the scanner was configured to skip locked keys, and
// this key was locked, so we can advance past it without
// raising the write too old error.
return true /* ok */, false
}
}
// 4b. We need to raise a write too old error. Merge the current
// timestamp with the maximum timestamp we've seen so we know to
// return an error, but then keep scanning so that we can return
// the largest possible time.
p.mostRecentTS.Forward(p.curUnsafeKey.Timestamp)
if len(p.mostRecentKey) == 0 {
p.mostRecentKey = append(p.mostRecentKey, p.curUnsafeKey.Key...)
}
return true /* ok */, false
}
if p.checkUncertainty {
// 5. Our txn's read timestamp is less than the max timestamp
// seen by the txn. We need to check for clock uncertainty
// errors.
localTS := p.curUnsafeValue.GetLocalTimestamp(p.curUnsafeKey.Timestamp)
if p.uncertainty.IsUncertain(p.curUnsafeKey.Timestamp, localTS) {
return p.uncertaintyError(p.curUnsafeKey.Timestamp, localTS), false
}
// This value is not within the reader's uncertainty window, but
// there could be other uncertain committed values, so seek and
// check uncertainty using the uncertainty interval's GlobalLimit.
return p.seekVersion(ctx, p.uncertainty.GlobalLimit, true)
}
// 6. Our txn's read timestamp is greater than or equal to the
// max timestamp seen by the txn so clock uncertainty checks are
// unnecessary. We need to seek to the desired version of the
// value (i.e. one with a timestamp earlier than our read
// timestamp).
return p.seekVersion(ctx, p.ts, false)
}
if !p.decodeCurrentMetadata() {
return false, false
}
if len(p.meta.RawBytes) != 0 {
// 7. Emit immediately if the value is inline.
return p.add(ctx, p.curUnsafeKey.Key, p.curRawKey, p.meta.RawBytes)
}
if p.meta.Txn == nil {
p.err = errors.Errorf("intent without transaction")
return false, false
}
metaTS := p.meta.Timestamp.ToTimestamp()
// metaTS is the timestamp of an intent value, which we may or may
// not end up ignoring, depending on factors codified below. If we do ignore
// the intent then we want to read at a lower timestamp that's strictly
// below the intent timestamp (to skip the intent), but also does not exceed
// our read timestamp (to avoid erroneously picking up future committed
// values); this timestamp is prevTS.
prevTS := p.ts
if metaTS.LessEq(p.ts) {
prevTS = metaTS.Prev()
}
ownIntent := p.txn != nil && p.meta.Txn.ID.Equal(p.txn.ID)
if !ownIntent {
conflictingIntent := metaTS.LessEq(p.ts) || p.failOnMoreRecent
if !conflictingIntent {
// 8. The key contains an intent, but we're reading below the intent.
// Seek to the desired version, checking for uncertainty if necessary.
//
// Note that if we own the intent (i.e. we're reading transactionally)
// we want to read the intent regardless of our read timestamp and fall
// into case 11 below.
if p.checkUncertainty {
// The intent's provisional value may be within the uncertainty window.
// Or there could be a different, uncertain committed value in the
// window. To detect either case, seek to and past the uncertainty
// interval's global limit and check uncertainty as we scan.
return p.seekVersion(ctx, p.uncertainty.GlobalLimit, true)
}
return p.seekVersion(ctx, p.ts, false)
}
if p.inconsistent {
// 9. The key contains an intent and we're doing an inconsistent
// read at a timestamp newer than the intent. We ignore the
// intent by insisting that the timestamp we're reading at is a
// historical timestamp < the intent timestamp. However, we
// return the intent separately; the caller may want to resolve
// it.
//
// p.intents is a pebble.Batch which grows its byte slice capacity in
// chunks to amortize allocations. The memMonitor is under-counting here
// by only accounting for the key and value bytes.
if !p.addCurIntent(ctx) {
return false, false
}
return p.seekVersion(ctx, prevTS, false)
}
if p.skipLocked {
// 10. The scanner has been configured with the skipLocked option. Ignore
// intents written by other transactions and seek to the next key.
// However, we return the intent separately if we have room; the caller
// may want to resolve it. Unlike below, this intent will not result in
// a WriteIntentError because MVCC{Scan,Get}Options.errOnIntents returns
// false when skipLocked in enabled.
if p.maxIntents == 0 || int64(p.intents.Count()) < p.maxIntents {
if !p.addCurIntent(ctx) {
return false, false
}
}
return true /* ok */, false
}
// 11. The key contains an intent which was not written by our
// transaction and either:
// - our read timestamp is equal to or newer than that of the
// intent
// - our read timestamp is older than that of the intent but
// the intent is in our transaction's uncertainty interval
// - our read timestamp is older than that of the intent but
// we want to fail on more recent writes
// Note that this will trigger an error higher up the stack. We
// continue scanning so that we can return all of the intents
// in the scan range.
if !p.addCurIntent(ctx) {
return false, false
}
// Limit number of intents returned in write intent error.
if p.maxIntents > 0 && int64(p.intents.Count()) >= p.maxIntents {
p.resumeReason = roachpb.RESUME_INTENT_LIMIT
return false, false
}
return true /* ok */, false
}
if p.txnEpoch == p.meta.Txn.Epoch {
if p.txnSequence >= p.meta.Txn.Sequence && !enginepb.TxnSeqIsIgnored(p.meta.Txn.Sequence, p.txnIgnoredSeqNums) {
// 12. We're reading our own txn's intent at an equal or higher sequence.
// Note that we read at the intent timestamp, not at our read timestamp
// as the intent timestamp may have been pushed forward by another
// transaction. Txn's always need to read their own writes.
return p.seekVersion(ctx, metaTS, false)
}
// 13. We're reading our own txn's intent at a lower sequence than is
// currently present in the intent. This means the intent we're seeing
// was written at a higher sequence than the read and that there may or
// may not be earlier versions of the intent (with lower sequence
// numbers) that we should read. If there exists a value in the intent
// history that has a sequence number equal to or less than the read
// sequence, read that value.
if intentValueRaw, found := p.getFromIntentHistory(); found {
// If we're adding a value due to a previous intent, we want to populate
// the timestamp as of current metaTimestamp. Note that this may be
// controversial as this maybe be neither the write timestamp when this
// intent was written. However, this was the only case in which a value