Line data Source code
1 : // Copyright 2011 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package pebble
6 :
7 : import (
8 : "bytes"
9 : "context"
10 : "io"
11 : "sync"
12 : "unsafe"
13 :
14 : "github.com/cockroachdb/errors"
15 : "github.com/cockroachdb/pebble/internal/base"
16 : "github.com/cockroachdb/pebble/internal/bytealloc"
17 : "github.com/cockroachdb/pebble/internal/fastrand"
18 : "github.com/cockroachdb/pebble/internal/humanize"
19 : "github.com/cockroachdb/pebble/internal/invariants"
20 : "github.com/cockroachdb/pebble/internal/keyspan"
21 : "github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
22 : "github.com/cockroachdb/pebble/internal/manifest"
23 : "github.com/cockroachdb/pebble/internal/rangekeystack"
24 : "github.com/cockroachdb/pebble/sstable"
25 : "github.com/cockroachdb/redact"
26 : )
27 :
28 : // iterPos describes the state of the internal iterator, in terms of whether it
29 : // is at the position returned to the user (cur), one ahead of the position
30 : // returned (next for forward iteration and prev for reverse iteration). The cur
31 : // position is split into two states, for forward and reverse iteration, since
32 : // we need to differentiate for switching directions.
33 : //
34 : // There is subtlety in what is considered the current position of the Iterator.
35 : // The internal iterator exposes a sequence of internal keys. There is not
36 : // always a single internalIterator position corresponding to the position
37 : // returned to the user. Consider the example:
38 : //
39 : // a.MERGE.9 a.MERGE.8 a.MERGE.7 a.SET.6 b.DELETE.9 b.DELETE.5 b.SET.4
40 : // \ /
41 : // \ Iterator.Key() = 'a' /
42 : //
43 : // The Iterator exposes one valid position at user key 'a' and the two exhausted
44 : // positions at the beginning and end of iteration. The underlying
45 : // internalIterator contains 7 valid positions and 2 exhausted positions.
46 : //
47 : // Iterator positioning methods must set iterPos to iterPosCur{Foward,Backward}
48 : // iff the user key at the current internalIterator position equals the
49 : // Iterator.Key returned to the user. This guarantees that a call to nextUserKey
50 : // or prevUserKey will advance to the next or previous iterator position.
51 : // iterPosCur{Forward,Backward} does not make any guarantee about the internal
52 : // iterator position among internal keys with matching user keys, and it will
53 : // vary subtly depending on the particular key kinds encountered. In the above
54 : // example, the iterator returning 'a' may set iterPosCurForward if the internal
55 : // iterator is positioned at any of a.MERGE.9, a.MERGE.8, a.MERGE.7 or a.SET.6.
56 : //
57 : // When setting iterPos to iterPosNext or iterPosPrev, the internal iterator
58 : // must be advanced to the first internalIterator position at a user key greater
59 : // (iterPosNext) or less (iterPosPrev) than the key returned to the user. An
60 : // internalIterator position that's !Valid() must also be considered greater or
61 : // less—depending on the direction of iteration—than the last valid Iterator
62 : // position.
63 : type iterPos int8
64 :
65 : const (
66 : iterPosCurForward iterPos = 0
67 : iterPosNext iterPos = 1
68 : iterPosPrev iterPos = -1
69 : iterPosCurReverse iterPos = -2
70 :
71 : // For limited iteration. When the iterator is at iterPosCurForwardPaused
72 : // - Next*() call should behave as if the internal iterator is already
73 : // at next (akin to iterPosNext).
74 : // - Prev*() call should behave as if the internal iterator is at the
75 : // current key (akin to iterPosCurForward).
76 : //
77 : // Similar semantics apply to CurReversePaused.
78 : iterPosCurForwardPaused iterPos = 2
79 : iterPosCurReversePaused iterPos = -3
80 : )
81 :
82 : // Approximate gap in bytes between samples of data read during iteration.
83 : // This is multiplied with a default ReadSamplingMultiplier of 1 << 4 to yield
84 : // 1 << 20 (1MB). The 1MB factor comes from:
85 : // https://github.com/cockroachdb/pebble/issues/29#issuecomment-494477985
86 : const readBytesPeriod uint64 = 1 << 16
87 :
88 : var errReversePrefixIteration = errors.New("pebble: unsupported reverse prefix iteration")
89 :
90 : // IteratorMetrics holds per-iterator metrics. These do not change over the
91 : // lifetime of the iterator.
92 : type IteratorMetrics struct {
93 : // The read amplification experienced by this iterator. This is the sum of
94 : // the memtables, the L0 sublevels and the non-empty Ln levels. Higher read
95 : // amplification generally results in slower reads, though allowing higher
96 : // read amplification can also result in faster writes.
97 : ReadAmp int
98 : }
99 :
100 : // IteratorStatsKind describes the two kind of iterator stats.
101 : type IteratorStatsKind int8
102 :
103 : const (
104 : // InterfaceCall represents calls to Iterator.
105 : InterfaceCall IteratorStatsKind = iota
106 : // InternalIterCall represents calls by Iterator to its internalIterator.
107 : InternalIterCall
108 : // NumStatsKind is the number of kinds, and is used for array sizing.
109 : NumStatsKind
110 : )
111 :
112 : // IteratorStats contains iteration stats.
113 : type IteratorStats struct {
114 : // ForwardSeekCount includes SeekGE, SeekPrefixGE, First.
115 : ForwardSeekCount [NumStatsKind]int
116 : // ReverseSeek includes SeekLT, Last.
117 : ReverseSeekCount [NumStatsKind]int
118 : // ForwardStepCount includes Next.
119 : ForwardStepCount [NumStatsKind]int
120 : // ReverseStepCount includes Prev.
121 : ReverseStepCount [NumStatsKind]int
122 : InternalStats InternalIteratorStats
123 : RangeKeyStats RangeKeyIteratorStats
124 : }
125 :
126 : var _ redact.SafeFormatter = &IteratorStats{}
127 :
128 : // InternalIteratorStats contains miscellaneous stats produced by internal
129 : // iterators.
130 : type InternalIteratorStats = base.InternalIteratorStats
131 :
132 : // RangeKeyIteratorStats contains miscellaneous stats about range keys
133 : // encountered by the iterator.
134 : type RangeKeyIteratorStats struct {
135 : // Count records the number of range keys encountered during
136 : // iteration. Range keys may be counted multiple times if the iterator
137 : // leaves a range key's bounds and then returns.
138 : Count int
139 : // ContainedPoints records the number of point keys encountered within the
140 : // bounds of a range key. Note that this includes point keys with suffixes
141 : // that sort both above and below the covering range key's suffix.
142 : ContainedPoints int
143 : // SkippedPoints records the count of the subset of ContainedPoints point
144 : // keys that were skipped during iteration due to range-key masking. It does
145 : // not include point keys that were never loaded because a
146 : // RangeKeyMasking.Filter excluded the entire containing block.
147 : SkippedPoints int
148 : }
149 :
150 : // Merge adds all of the argument's statistics to the receiver. It may be used
151 : // to accumulate stats across multiple iterators.
152 1 : func (s *RangeKeyIteratorStats) Merge(o RangeKeyIteratorStats) {
153 1 : s.Count += o.Count
154 1 : s.ContainedPoints += o.ContainedPoints
155 1 : s.SkippedPoints += o.SkippedPoints
156 1 : }
157 :
158 : // LazyValue is a lazy value. See the long comment in base.LazyValue.
159 : type LazyValue = base.LazyValue
160 :
161 : // Iterator iterates over a DB's key/value pairs in key order.
162 : //
163 : // An iterator must be closed after use, but it is not necessary to read an
164 : // iterator until exhaustion.
165 : //
166 : // An iterator is not goroutine-safe, but it is safe to use multiple iterators
167 : // concurrently, with each in a dedicated goroutine.
168 : //
169 : // It is also safe to use an iterator concurrently with modifying its
170 : // underlying DB, if that DB permits modification. However, the resultant
171 : // key/value pairs are not guaranteed to be a consistent snapshot of that DB
172 : // at a particular point in time.
173 : //
174 : // If an iterator encounters an error during any operation, it is stored by
175 : // the Iterator and surfaced through the Error method. All absolute
176 : // positioning methods (eg, SeekLT, SeekGT, First, Last, etc) reset any
177 : // accumulated error before positioning. All relative positioning methods (eg,
178 : // Next, Prev) return without advancing if the iterator has an accumulated
179 : // error.
180 : type Iterator struct {
181 : // The context is stored here since (a) Iterators are expected to be
182 : // short-lived (since they pin memtables and sstables), (b) plumbing a
183 : // context into every method is very painful, (c) they do not (yet) respect
184 : // context cancellation and are only used for tracing.
185 : ctx context.Context
186 : opts IterOptions
187 : merge Merge
188 : comparer base.Comparer
189 : iter internalIterator
190 : pointIter topLevelIterator
191 : // Either readState or version is set, but not both.
192 : readState *readState
193 : version *version
194 : // rangeKey holds iteration state specific to iteration over range keys.
195 : // The range key field may be nil if the Iterator has never been configured
196 : // to iterate over range keys. Its non-nilness cannot be used to determine
197 : // if the Iterator is currently iterating over range keys: For that, consult
198 : // the IterOptions using opts.rangeKeys(). If non-nil, its rangeKeyIter
199 : // field is guaranteed to be non-nil too.
200 : rangeKey *iteratorRangeKeyState
201 : // rangeKeyMasking holds state for range-key masking of point keys.
202 : rangeKeyMasking rangeKeyMasking
203 : err error
204 : // When iterValidityState=IterValid, key represents the current key, which
205 : // is backed by keyBuf.
206 : key []byte
207 : keyBuf []byte
208 : value LazyValue
209 : // For use in LazyValue.Clone.
210 : valueBuf []byte
211 : fetcher base.LazyFetcher
212 : // For use in LazyValue.Value.
213 : lazyValueBuf []byte
214 : valueCloser io.Closer
215 : // boundsBuf holds two buffers used to store the lower and upper bounds.
216 : // Whenever the Iterator's bounds change, the new bounds are copied into
217 : // boundsBuf[boundsBufIdx]. The two bounds share a slice to reduce
218 : // allocations. opts.LowerBound and opts.UpperBound point into this slice.
219 : boundsBuf [2][]byte
220 : boundsBufIdx int
221 : // iterKey, iterValue reflect the latest position of iter, except when
222 : // SetBounds is called. In that case, these are explicitly set to nil.
223 : iterKey *InternalKey
224 : iterValue LazyValue
225 : alloc *iterAlloc
226 : getIterAlloc *getIterAlloc
227 : prefixOrFullSeekKey []byte
228 : readSampling readSampling
229 : stats IteratorStats
230 : externalReaders [][]*sstable.Reader
231 :
232 : // Following fields used when constructing an iterator stack, eg, in Clone
233 : // and SetOptions or when re-fragmenting a batch's range keys/range dels.
234 : // Non-nil if this Iterator includes a Batch.
235 : batch *Batch
236 : newIters tableNewIters
237 : newIterRangeKey keyspanimpl.TableNewSpanIter
238 : lazyCombinedIter lazyCombinedIter
239 : seqNum uint64
240 : // batchSeqNum is used by Iterators over indexed batches to detect when the
241 : // underlying batch has been mutated. The batch beneath an indexed batch may
242 : // be mutated while the Iterator is open, but new keys are not surfaced
243 : // until the next call to SetOptions.
244 : batchSeqNum uint64
245 : // batch{PointIter,RangeDelIter,RangeKeyIter} are used when the Iterator is
246 : // configured to read through an indexed batch. If a batch is set, these
247 : // iterators will be included within the iterator stack regardless of
248 : // whether the batch currently contains any keys of their kind. These
249 : // pointers are used during a call to SetOptions to refresh the Iterator's
250 : // view of its indexed batch.
251 : batchPointIter batchIter
252 : batchRangeDelIter keyspan.Iter
253 : batchRangeKeyIter keyspan.Iter
254 : // merging is a pointer to this iterator's point merging iterator. It
255 : // appears here because key visibility is handled by the merging iterator.
256 : // During SetOptions on an iterator over an indexed batch, this field is
257 : // used to update the merging iterator's batch snapshot.
258 : merging *mergingIter
259 :
260 : // Keeping the bools here after all the 8 byte aligned fields shrinks the
261 : // sizeof this struct by 24 bytes.
262 :
263 : // INVARIANT:
264 : // iterValidityState==IterAtLimit <=>
265 : // pos==iterPosCurForwardPaused || pos==iterPosCurReversePaused
266 : iterValidityState IterValidityState
267 : // Set to true by SetBounds, SetOptions. Causes the Iterator to appear
268 : // exhausted externally, while preserving the correct iterValidityState for
269 : // the iterator's internal state. Preserving the correct internal validity
270 : // is used for SeekPrefixGE(..., trySeekUsingNext), and SeekGE/SeekLT
271 : // optimizations after "no-op" calls to SetBounds and SetOptions.
272 : requiresReposition bool
273 : // The position of iter. When this is iterPos{Prev,Next} the iter has been
274 : // moved past the current key-value, which can only happen if
275 : // iterValidityState=IterValid, i.e., there is something to return to the
276 : // client for the current position.
277 : pos iterPos
278 : // Relates to the prefixOrFullSeekKey field above.
279 : hasPrefix bool
280 : // Used for deriving the value of SeekPrefixGE(..., trySeekUsingNext),
281 : // and SeekGE/SeekLT optimizations
282 : lastPositioningOp lastPositioningOpKind
283 : // Used for determining when it's safe to perform SeekGE optimizations that
284 : // reuse the iterator state to avoid the cost of a full seek if the iterator
285 : // is already positioned in the correct place. If the iterator's view of its
286 : // indexed batch was just refreshed, some optimizations cannot be applied on
287 : // the first seek after the refresh:
288 : // - SeekGE has a no-op optimization that does not seek on the internal
289 : // iterator at all if the iterator is already in the correct place.
290 : // This optimization cannot be performed if the internal iterator was
291 : // last positioned when the iterator had a different view of an
292 : // underlying batch.
293 : // - Seek[Prefix]GE set flags.TrySeekUsingNext()=true when the seek key is
294 : // greater than the previous operation's seek key, under the expectation
295 : // that the various internal iterators can use their current position to
296 : // avoid a full expensive re-seek. This applies to the batchIter as well.
297 : // However, if the view of the batch was just refreshed, the batchIter's
298 : // position is not useful because it may already be beyond new keys less
299 : // than the seek key. To prevent the use of this optimization in
300 : // batchIter, Seek[Prefix]GE set flags.BatchJustRefreshed()=true if this
301 : // bit is enabled.
302 : batchJustRefreshed bool
303 : // batchOnlyIter is set to true for Batch.NewBatchOnlyIter.
304 : batchOnlyIter bool
305 : // Used in some tests to disable the random disabling of seek optimizations.
306 : forceEnableSeekOpt bool
307 : // Set to true if NextPrefix is not currently permitted. Defaults to false
308 : // in case an iterator never had any bounds.
309 : nextPrefixNotPermittedByUpperBound bool
310 : }
311 :
312 : // cmp is a convenience shorthand for the i.comparer.Compare function.
313 1 : func (i *Iterator) cmp(a, b []byte) int {
314 1 : return i.comparer.Compare(a, b)
315 1 : }
316 :
317 : // split is a convenience shorthand for the i.comparer.Split function.
318 1 : func (i *Iterator) split(a []byte) int {
319 1 : return i.comparer.Split(a)
320 1 : }
321 :
322 : // equal is a convenience shorthand for the i.comparer.Equal function.
323 1 : func (i *Iterator) equal(a, b []byte) bool {
324 1 : return i.comparer.Equal(a, b)
325 1 : }
326 :
327 : // iteratorRangeKeyState holds an iterator's range key iteration state.
328 : type iteratorRangeKeyState struct {
329 : opts *IterOptions
330 : cmp base.Compare
331 : split base.Split
332 : // rangeKeyIter holds the range key iterator stack that iterates over the
333 : // merged spans across the entirety of the LSM.
334 : rangeKeyIter keyspan.FragmentIterator
335 : iiter keyspan.InterleavingIter
336 : // stale is set to true when the range key state recorded here (in start,
337 : // end and keys) may not be in sync with the current range key at the
338 : // interleaving iterator's current position.
339 : //
340 : // When the interelaving iterator passes over a new span, it invokes the
341 : // SpanChanged hook defined on the `rangeKeyMasking` type, which sets stale
342 : // to true if the span is non-nil.
343 : //
344 : // The parent iterator may not be positioned over the interleaving
345 : // iterator's current position (eg, i.iterPos = iterPos{Next,Prev}), so
346 : // {keys,start,end} are only updated to the new range key during a call to
347 : // Iterator.saveRangeKey.
348 : stale bool
349 : // updated is used to signal to the Iterator client whether the state of
350 : // range keys has changed since the previous iterator position through the
351 : // `RangeKeyChanged` method. It's set to true during an Iterator positioning
352 : // operation that changes the state of the current range key. Each Iterator
353 : // positioning operation sets it back to false before executing.
354 : //
355 : // TODO(jackson): The lifecycle of {stale,updated,prevPosHadRangeKey} is
356 : // intricate and confusing. Try to refactor to reduce complexity.
357 : updated bool
358 : // prevPosHadRangeKey records whether the previous Iterator position had a
359 : // range key (HasPointAndRage() = (_, true)). It's updated at the beginning
360 : // of each new Iterator positioning operation. It's required by saveRangeKey to
361 : // to set `updated` appropriately: Without this record of the previous iterator
362 : // state, it's ambiguous whether an iterator only temporarily stepped onto a
363 : // position without a range key.
364 : prevPosHadRangeKey bool
365 : // rangeKeyOnly is set to true if at the current iterator position there is
366 : // no point key, only a range key start boundary.
367 : rangeKeyOnly bool
368 : // hasRangeKey is true when the current iterator position has a covering
369 : // range key (eg, a range key with bounds [<lower>,<upper>) such that
370 : // <lower> ≤ Key() < <upper>).
371 : hasRangeKey bool
372 : // start and end are the [start, end) boundaries of the current range keys.
373 : start []byte
374 : end []byte
375 :
376 : rangeKeyBuffers
377 :
378 : // iterConfig holds fields that are used for the construction of the
379 : // iterator stack, but do not need to be directly accessed during iteration.
380 : // This struct is bundled within the iteratorRangeKeyState struct to reduce
381 : // allocations.
382 : iterConfig rangekeystack.UserIteratorConfig
383 : }
384 :
385 : type rangeKeyBuffers struct {
386 : // keys is sorted by Suffix ascending.
387 : keys []RangeKeyData
388 : // buf is used to save range-key data before moving the range-key iterator.
389 : // Start and end boundaries, suffixes and values are all copied into buf.
390 : buf bytealloc.A
391 : // internal holds buffers used by the range key internal iterators.
392 : internal rangekeystack.Buffers
393 : }
394 :
395 1 : func (b *rangeKeyBuffers) PrepareForReuse() {
396 1 : const maxKeysReuse = 100
397 1 : if len(b.keys) > maxKeysReuse {
398 0 : b.keys = nil
399 0 : }
400 : // Avoid caching the key buf if it is overly large. The constant is
401 : // fairly arbitrary.
402 1 : if cap(b.buf) >= maxKeyBufCacheSize {
403 1 : b.buf = nil
404 1 : } else {
405 1 : b.buf = b.buf[:0]
406 1 : }
407 1 : b.internal.PrepareForReuse()
408 : }
409 :
410 1 : func (i *iteratorRangeKeyState) init(cmp base.Compare, split base.Split, opts *IterOptions) {
411 1 : i.cmp = cmp
412 1 : i.split = split
413 1 : i.opts = opts
414 1 : }
415 :
416 : var iterRangeKeyStateAllocPool = sync.Pool{
417 1 : New: func() interface{} {
418 1 : return &iteratorRangeKeyState{}
419 1 : },
420 : }
421 :
422 : // isEphemeralPosition returns true iff the current iterator position is
423 : // ephemeral, and won't be visited during subsequent relative positioning
424 : // operations.
425 : //
426 : // The iterator position resulting from a SeekGE or SeekPrefixGE that lands on a
427 : // straddling range key without a coincident point key is such a position.
428 1 : func (i *Iterator) isEphemeralPosition() bool {
429 1 : return i.opts.rangeKeys() && i.rangeKey != nil && i.rangeKey.rangeKeyOnly &&
430 1 : !i.equal(i.rangeKey.start, i.key)
431 1 : }
432 :
433 : type lastPositioningOpKind int8
434 :
435 : const (
436 : unknownLastPositionOp lastPositioningOpKind = iota
437 : seekPrefixGELastPositioningOp
438 : seekGELastPositioningOp
439 : seekLTLastPositioningOp
440 : // internalNextOp is a special internal iterator positioning operation used
441 : // by CanDeterministicallySingleDelete. It exists for enforcing requirements
442 : // around calling CanDeterministicallySingleDelete at most once per external
443 : // iterator position.
444 : internalNextOp
445 : )
446 :
447 : // Limited iteration mode. Not for use with prefix iteration.
448 : //
449 : // SeekGE, SeekLT, Prev, Next have WithLimit variants, that pause the iterator
450 : // at the limit in a best-effort manner. The client should behave correctly
451 : // even if the limits are ignored. These limits are not "deep", in that they
452 : // are not passed down to the underlying collection of internalIterators. This
453 : // is because the limits are transient, and apply only until the next
454 : // iteration call. They serve mainly as a way to bound the amount of work when
455 : // two (or more) Iterators are being coordinated at a higher level.
456 : //
457 : // In limited iteration mode:
458 : // - Avoid using Iterator.Valid if the last call was to a *WithLimit() method.
459 : // The return value from the *WithLimit() method provides a more precise
460 : // disposition.
461 : // - The limit is exclusive for forward and inclusive for reverse.
462 : //
463 : //
464 : // Limited iteration mode & range keys
465 : //
466 : // Limited iteration interacts with range-key iteration. When range key
467 : // iteration is enabled, range keys are interleaved at their start boundaries.
468 : // Limited iteration must ensure that if a range key exists within the limit,
469 : // the iterator visits the range key.
470 : //
471 : // During forward limited iteration, this is trivial: An overlapping range key
472 : // must have a start boundary less than the limit, and the range key's start
473 : // boundary will be interleaved and found to be within the limit.
474 : //
475 : // During reverse limited iteration, the tail of the range key may fall within
476 : // the limit. The range key must be surfaced even if the range key's start
477 : // boundary is less than the limit, and if there are no point keys between the
478 : // current iterator position and the limit. To provide this guarantee, reverse
479 : // limited iteration ignores the limit as long as there is a range key
480 : // overlapping the iteration position.
481 :
482 : // IterValidityState captures the state of the Iterator.
483 : type IterValidityState int8
484 :
485 : const (
486 : // IterExhausted represents an Iterator that is exhausted.
487 : IterExhausted IterValidityState = iota
488 : // IterValid represents an Iterator that is valid.
489 : IterValid
490 : // IterAtLimit represents an Iterator that has a non-exhausted
491 : // internalIterator, but has reached a limit without any key for the
492 : // caller.
493 : IterAtLimit
494 : )
495 :
496 : // readSampling stores variables used to sample a read to trigger a read
497 : // compaction
498 : type readSampling struct {
499 : bytesUntilReadSampling uint64
500 : initialSamplePassed bool
501 : pendingCompactions readCompactionQueue
502 : // forceReadSampling is used for testing purposes to force a read sample on every
503 : // call to Iterator.maybeSampleRead()
504 : forceReadSampling bool
505 : }
506 :
507 1 : func (i *Iterator) findNextEntry(limit []byte) {
508 1 : i.iterValidityState = IterExhausted
509 1 : i.pos = iterPosCurForward
510 1 : if i.opts.rangeKeys() && i.rangeKey != nil {
511 1 : i.rangeKey.rangeKeyOnly = false
512 1 : }
513 :
514 : // Close the closer for the current value if one was open.
515 1 : if i.closeValueCloser() != nil {
516 1 : return
517 1 : }
518 :
519 1 : for i.iterKey != nil {
520 1 : key := *i.iterKey
521 1 :
522 1 : // The topLevelIterator.StrictSeekPrefixGE contract requires that in
523 1 : // prefix mode [i.hasPrefix=t], every point key returned by the internal
524 1 : // iterator must have the current iteration prefix.
525 1 : if invariants.Enabled && i.hasPrefix {
526 1 : // Range keys are an exception to the contract and may return a different
527 1 : // prefix. This case is explicitly handled in the switch statement below.
528 1 : if key.Kind() != base.InternalKeyKindRangeKeySet {
529 1 : if n := i.split(key.UserKey); !i.equal(i.prefixOrFullSeekKey, key.UserKey[:n]) {
530 0 : i.opts.logger.Fatalf("pebble: prefix violation: key %q does not have prefix %q\n", key.UserKey, i.prefixOrFullSeekKey)
531 0 : }
532 : }
533 : }
534 :
535 : // Compare with limit every time we start at a different user key.
536 : // Note that given the best-effort contract of limit, we could avoid a
537 : // comparison in the common case by doing this only after
538 : // i.nextUserKey is called for the deletes below. However that makes
539 : // the behavior non-deterministic (since the behavior will vary based
540 : // on what has been compacted), which makes it hard to test with the
541 : // metamorphic test. So we forego that performance optimization.
542 1 : if limit != nil && i.cmp(limit, i.iterKey.UserKey) <= 0 {
543 1 : i.iterValidityState = IterAtLimit
544 1 : i.pos = iterPosCurForwardPaused
545 1 : return
546 1 : }
547 :
548 : // If the user has configured a SkipPoint function, invoke it to see
549 : // whether we should skip over the current user key.
550 1 : if i.opts.SkipPoint != nil && key.Kind() != InternalKeyKindRangeKeySet && i.opts.SkipPoint(i.iterKey.UserKey) {
551 1 : // NB: We could call nextUserKey, but in some cases the SkipPoint
552 1 : // predicate function might be cheaper than nextUserKey's key copy
553 1 : // and key comparison. This should be the case for MVCC suffix
554 1 : // comparisons, for example. In the future, we could expand the
555 1 : // SkipPoint interface to give the implementor more control over
556 1 : // whether we skip over just the internal key, the user key, or even
557 1 : // the key prefix.
558 1 : i.stats.ForwardStepCount[InternalIterCall]++
559 1 : i.iterKey, i.iterValue = i.iter.Next()
560 1 : continue
561 : }
562 :
563 1 : switch key.Kind() {
564 1 : case InternalKeyKindRangeKeySet:
565 1 : if i.hasPrefix {
566 1 : if n := i.split(key.UserKey); !i.equal(i.prefixOrFullSeekKey, key.UserKey[:n]) {
567 1 : return
568 1 : }
569 : }
570 : // Save the current key.
571 1 : i.keyBuf = append(i.keyBuf[:0], key.UserKey...)
572 1 : i.key = i.keyBuf
573 1 : i.value = LazyValue{}
574 1 : // There may also be a live point key at this userkey that we have
575 1 : // not yet read. We need to find the next entry with this user key
576 1 : // to find it. Save the range key so we don't lose it when we Next
577 1 : // the underlying iterator.
578 1 : i.saveRangeKey()
579 1 : pointKeyExists := i.nextPointCurrentUserKey()
580 1 : if i.err != nil {
581 0 : i.iterValidityState = IterExhausted
582 0 : return
583 0 : }
584 1 : i.rangeKey.rangeKeyOnly = !pointKeyExists
585 1 : i.iterValidityState = IterValid
586 1 : return
587 :
588 1 : case InternalKeyKindDelete, InternalKeyKindSingleDelete, InternalKeyKindDeleteSized:
589 1 : // NB: treating InternalKeyKindSingleDelete as equivalent to DEL is not
590 1 : // only simpler, but is also necessary for correctness due to
591 1 : // InternalKeyKindSSTableInternalObsoleteBit.
592 1 : i.nextUserKey()
593 1 : continue
594 :
595 1 : case InternalKeyKindSet, InternalKeyKindSetWithDelete:
596 1 : i.keyBuf = append(i.keyBuf[:0], key.UserKey...)
597 1 : i.key = i.keyBuf
598 1 : i.value = i.iterValue
599 1 : i.iterValidityState = IterValid
600 1 : i.saveRangeKey()
601 1 : return
602 :
603 1 : case InternalKeyKindMerge:
604 1 : // Resolving the merge may advance us to the next point key, which
605 1 : // may be covered by a different set of range keys. Save the range
606 1 : // key state so we don't lose it.
607 1 : i.saveRangeKey()
608 1 : if i.mergeForward(key) {
609 1 : i.iterValidityState = IterValid
610 1 : return
611 1 : }
612 :
613 : // The merge didn't yield a valid key, either because the value
614 : // merger indicated it should be deleted, or because an error was
615 : // encountered.
616 1 : i.iterValidityState = IterExhausted
617 1 : if i.err != nil {
618 1 : return
619 1 : }
620 1 : if i.pos != iterPosNext {
621 0 : i.nextUserKey()
622 0 : }
623 1 : if i.closeValueCloser() != nil {
624 0 : return
625 0 : }
626 1 : i.pos = iterPosCurForward
627 :
628 0 : default:
629 0 : i.err = base.CorruptionErrorf("pebble: invalid internal key kind: %d", errors.Safe(key.Kind()))
630 0 : i.iterValidityState = IterExhausted
631 0 : return
632 : }
633 : }
634 :
635 : // Is iterKey nil due to an error?
636 1 : if err := i.iter.Error(); err != nil {
637 1 : i.err = err
638 1 : i.iterValidityState = IterExhausted
639 1 : }
640 : }
641 :
642 1 : func (i *Iterator) nextPointCurrentUserKey() bool {
643 1 : // If the user has configured a SkipPoint function and the current user key
644 1 : // would be skipped by it, there's no need to step forward looking for a
645 1 : // point key. If we were to find one, it should be skipped anyways.
646 1 : if i.opts.SkipPoint != nil && i.opts.SkipPoint(i.key) {
647 1 : return false
648 1 : }
649 :
650 1 : i.pos = iterPosCurForward
651 1 :
652 1 : i.iterKey, i.iterValue = i.iter.Next()
653 1 : i.stats.ForwardStepCount[InternalIterCall]++
654 1 : if i.iterKey == nil {
655 1 : if err := i.iter.Error(); err != nil {
656 0 : i.err = err
657 1 : } else {
658 1 : i.pos = iterPosNext
659 1 : }
660 1 : return false
661 : }
662 1 : if !i.equal(i.key, i.iterKey.UserKey) {
663 1 : i.pos = iterPosNext
664 1 : return false
665 1 : }
666 :
667 1 : key := *i.iterKey
668 1 : switch key.Kind() {
669 0 : case InternalKeyKindRangeKeySet:
670 0 : // RangeKeySets must always be interleaved as the first internal key
671 0 : // for a user key.
672 0 : i.err = base.CorruptionErrorf("pebble: unexpected range key set mid-user key")
673 0 : return false
674 :
675 1 : case InternalKeyKindDelete, InternalKeyKindSingleDelete, InternalKeyKindDeleteSized:
676 1 : // NB: treating InternalKeyKindSingleDelete as equivalent to DEL is not
677 1 : // only simpler, but is also necessary for correctness due to
678 1 : // InternalKeyKindSSTableInternalObsoleteBit.
679 1 : return false
680 :
681 1 : case InternalKeyKindSet, InternalKeyKindSetWithDelete:
682 1 : i.value = i.iterValue
683 1 : return true
684 :
685 1 : case InternalKeyKindMerge:
686 1 : return i.mergeForward(key)
687 :
688 0 : default:
689 0 : i.err = base.CorruptionErrorf("pebble: invalid internal key kind: %d", errors.Safe(key.Kind()))
690 0 : return false
691 : }
692 : }
693 :
694 : // mergeForward resolves a MERGE key, advancing the underlying iterator forward
695 : // to merge with subsequent keys with the same userkey. mergeForward returns a
696 : // boolean indicating whether or not the merge yielded a valid key. A merge may
697 : // not yield a valid key if an error occurred, in which case i.err is non-nil,
698 : // or the user's value merger specified the key to be deleted.
699 : //
700 : // mergeForward does not update iterValidityState.
701 1 : func (i *Iterator) mergeForward(key base.InternalKey) (valid bool) {
702 1 : var iterValue []byte
703 1 : iterValue, _, i.err = i.iterValue.Value(nil)
704 1 : if i.err != nil {
705 0 : return false
706 0 : }
707 1 : var valueMerger ValueMerger
708 1 : valueMerger, i.err = i.merge(key.UserKey, iterValue)
709 1 : if i.err != nil {
710 0 : return false
711 0 : }
712 :
713 1 : i.mergeNext(key, valueMerger)
714 1 : if i.err != nil {
715 1 : return false
716 1 : }
717 :
718 1 : var needDelete bool
719 1 : var value []byte
720 1 : value, needDelete, i.valueCloser, i.err = finishValueMerger(
721 1 : valueMerger, true /* includesBase */)
722 1 : i.value = base.MakeInPlaceValue(value)
723 1 : if i.err != nil {
724 0 : return false
725 0 : }
726 1 : if needDelete {
727 1 : _ = i.closeValueCloser()
728 1 : return false
729 1 : }
730 1 : return true
731 : }
732 :
733 1 : func (i *Iterator) closeValueCloser() error {
734 1 : if i.valueCloser != nil {
735 0 : i.err = i.valueCloser.Close()
736 0 : i.valueCloser = nil
737 0 : }
738 1 : return i.err
739 : }
740 :
741 1 : func (i *Iterator) nextUserKey() {
742 1 : if i.iterKey == nil {
743 1 : return
744 1 : }
745 1 : trailer := i.iterKey.Trailer
746 1 : done := i.iterKey.Trailer <= base.InternalKeyZeroSeqnumMaxTrailer
747 1 : if i.iterValidityState != IterValid {
748 1 : i.keyBuf = append(i.keyBuf[:0], i.iterKey.UserKey...)
749 1 : i.key = i.keyBuf
750 1 : }
751 1 : for {
752 1 : i.stats.ForwardStepCount[InternalIterCall]++
753 1 : i.iterKey, i.iterValue = i.iter.Next()
754 1 : if i.iterKey == nil {
755 1 : if err := i.iter.Error(); err != nil {
756 1 : i.err = err
757 1 : return
758 1 : }
759 : }
760 : // NB: We're guaranteed to be on the next user key if the previous key
761 : // had a zero sequence number (`done`), or the new key has a trailer
762 : // greater or equal to the previous key's trailer. This is true because
763 : // internal keys with the same user key are sorted by Trailer in
764 : // strictly monotonically descending order. We expect the trailer
765 : // optimization to trigger around 50% of the time with randomly
766 : // distributed writes. We expect it to trigger very frequently when
767 : // iterating through ingested sstables, which contain keys that all have
768 : // the same sequence number.
769 1 : if done || i.iterKey == nil || i.iterKey.Trailer >= trailer {
770 1 : break
771 : }
772 1 : if !i.equal(i.key, i.iterKey.UserKey) {
773 1 : break
774 : }
775 1 : done = i.iterKey.Trailer <= base.InternalKeyZeroSeqnumMaxTrailer
776 1 : trailer = i.iterKey.Trailer
777 : }
778 : }
779 :
780 1 : func (i *Iterator) maybeSampleRead() {
781 1 : // This method is only called when a public method of Iterator is
782 1 : // returning, and below we exclude the case were the iterator is paused at
783 1 : // a limit. The effect of these choices is that keys that are deleted, but
784 1 : // are encountered during iteration, are not accounted for in the read
785 1 : // sampling and will not cause read driven compactions, even though we are
786 1 : // incurring cost in iterating over them. And this issue is not limited to
787 1 : // Iterator, which does not see the effect of range deletes, which may be
788 1 : // causing iteration work in mergingIter. It is not clear at this time
789 1 : // whether this is a deficiency worth addressing.
790 1 : if i.iterValidityState != IterValid {
791 1 : return
792 1 : }
793 1 : if i.readState == nil {
794 1 : return
795 1 : }
796 1 : if i.readSampling.forceReadSampling {
797 1 : i.sampleRead()
798 1 : return
799 1 : }
800 1 : samplingPeriod := int32(int64(readBytesPeriod) * i.readState.db.opts.Experimental.ReadSamplingMultiplier)
801 1 : if samplingPeriod <= 0 {
802 0 : return
803 0 : }
804 1 : bytesRead := uint64(len(i.key) + i.value.Len())
805 1 : for i.readSampling.bytesUntilReadSampling < bytesRead {
806 1 : i.readSampling.bytesUntilReadSampling += uint64(fastrand.Uint32n(2 * uint32(samplingPeriod)))
807 1 : // The block below tries to adjust for the case where this is the
808 1 : // first read in a newly-opened iterator. As bytesUntilReadSampling
809 1 : // starts off at zero, we don't want to sample the first read of
810 1 : // every newly-opened iterator, but we do want to sample some of them.
811 1 : if !i.readSampling.initialSamplePassed {
812 1 : i.readSampling.initialSamplePassed = true
813 1 : if fastrand.Uint32n(uint32(i.readSampling.bytesUntilReadSampling)) > uint32(bytesRead) {
814 1 : continue
815 : }
816 : }
817 1 : i.sampleRead()
818 : }
819 1 : i.readSampling.bytesUntilReadSampling -= bytesRead
820 : }
821 :
822 1 : func (i *Iterator) sampleRead() {
823 1 : var topFile *manifest.FileMetadata
824 1 : topLevel, numOverlappingLevels := numLevels, 0
825 1 : mi := i.merging
826 1 : if mi == nil {
827 1 : return
828 1 : }
829 1 : if len(mi.levels) > 1 {
830 1 : mi.ForEachLevelIter(func(li *levelIter) bool {
831 1 : l := manifest.LevelToInt(li.level)
832 1 : if f := li.iterFile; f != nil {
833 1 : var containsKey bool
834 1 : if i.pos == iterPosNext || i.pos == iterPosCurForward ||
835 1 : i.pos == iterPosCurForwardPaused {
836 1 : containsKey = i.cmp(f.SmallestPointKey.UserKey, i.key) <= 0
837 1 : } else if i.pos == iterPosPrev || i.pos == iterPosCurReverse ||
838 1 : i.pos == iterPosCurReversePaused {
839 1 : containsKey = i.cmp(f.LargestPointKey.UserKey, i.key) >= 0
840 1 : }
841 : // Do nothing if the current key is not contained in f's
842 : // bounds. We could seek the LevelIterator at this level
843 : // to find the right file, but the performance impacts of
844 : // doing that are significant enough to negate the benefits
845 : // of read sampling in the first place. See the discussion
846 : // at:
847 : // https://github.com/cockroachdb/pebble/pull/1041#issuecomment-763226492
848 1 : if containsKey {
849 1 : numOverlappingLevels++
850 1 : if numOverlappingLevels >= 2 {
851 1 : // Terminate the loop early if at least 2 overlapping levels are found.
852 1 : return true
853 1 : }
854 1 : topLevel = l
855 1 : topFile = f
856 : }
857 : }
858 1 : return false
859 : })
860 : }
861 1 : if topFile == nil || topLevel >= numLevels {
862 1 : return
863 1 : }
864 1 : if numOverlappingLevels >= 2 {
865 1 : allowedSeeks := topFile.AllowedSeeks.Add(-1)
866 1 : if allowedSeeks == 0 {
867 1 :
868 1 : // Since the compaction queue can handle duplicates, we can keep
869 1 : // adding to the queue even once allowedSeeks hits 0.
870 1 : // In fact, we NEED to keep adding to the queue, because the queue
871 1 : // is small and evicts older and possibly useful compactions.
872 1 : topFile.AllowedSeeks.Add(topFile.InitAllowedSeeks)
873 1 :
874 1 : read := readCompaction{
875 1 : start: topFile.SmallestPointKey.UserKey,
876 1 : end: topFile.LargestPointKey.UserKey,
877 1 : level: topLevel,
878 1 : fileNum: topFile.FileNum,
879 1 : }
880 1 : i.readSampling.pendingCompactions.add(&read, i.cmp)
881 1 : }
882 : }
883 : }
884 :
885 1 : func (i *Iterator) findPrevEntry(limit []byte) {
886 1 : i.iterValidityState = IterExhausted
887 1 : i.pos = iterPosCurReverse
888 1 : if i.opts.rangeKeys() && i.rangeKey != nil {
889 1 : i.rangeKey.rangeKeyOnly = false
890 1 : }
891 :
892 : // Close the closer for the current value if one was open.
893 1 : if i.valueCloser != nil {
894 0 : i.err = i.valueCloser.Close()
895 0 : i.valueCloser = nil
896 0 : if i.err != nil {
897 0 : i.iterValidityState = IterExhausted
898 0 : return
899 0 : }
900 : }
901 :
902 1 : var valueMerger ValueMerger
903 1 : firstLoopIter := true
904 1 : rangeKeyBoundary := false
905 1 : // The code below compares with limit in multiple places. As documented in
906 1 : // findNextEntry, this is being done to make the behavior of limit
907 1 : // deterministic to allow for metamorphic testing. It is not required by
908 1 : // the best-effort contract of limit.
909 1 : for i.iterKey != nil {
910 1 : key := *i.iterKey
911 1 :
912 1 : // NB: We cannot pause if the current key is covered by a range key.
913 1 : // Otherwise, the user might not ever learn of a range key that covers
914 1 : // the key space being iterated over in which there are no point keys.
915 1 : // Since limits are best effort, ignoring the limit in this case is
916 1 : // allowed by the contract of limit.
917 1 : if firstLoopIter && limit != nil && i.cmp(limit, i.iterKey.UserKey) > 0 && !i.rangeKeyWithinLimit(limit) {
918 1 : i.iterValidityState = IterAtLimit
919 1 : i.pos = iterPosCurReversePaused
920 1 : return
921 1 : }
922 1 : firstLoopIter = false
923 1 :
924 1 : if i.iterValidityState == IterValid {
925 1 : if !i.equal(key.UserKey, i.key) {
926 1 : // We've iterated to the previous user key.
927 1 : i.pos = iterPosPrev
928 1 : if valueMerger != nil {
929 1 : var needDelete bool
930 1 : var value []byte
931 1 : value, needDelete, i.valueCloser, i.err = finishValueMerger(valueMerger, true /* includesBase */)
932 1 : i.value = base.MakeInPlaceValue(value)
933 1 : if i.err == nil && needDelete {
934 1 : // The point key at this key is deleted. If we also have
935 1 : // a range key boundary at this key, we still want to
936 1 : // return. Otherwise, we need to continue looking for
937 1 : // a live key.
938 1 : i.value = LazyValue{}
939 1 : if rangeKeyBoundary {
940 0 : i.rangeKey.rangeKeyOnly = true
941 1 : } else {
942 1 : i.iterValidityState = IterExhausted
943 1 : if i.closeValueCloser() == nil {
944 1 : continue
945 : }
946 : }
947 : }
948 : }
949 1 : if i.err != nil {
950 0 : i.iterValidityState = IterExhausted
951 0 : }
952 1 : return
953 : }
954 : }
955 :
956 : // If the user has configured a SkipPoint function, invoke it to see
957 : // whether we should skip over the current user key.
958 1 : if i.opts.SkipPoint != nil && key.Kind() != InternalKeyKindRangeKeySet && i.opts.SkipPoint(key.UserKey) {
959 1 : // NB: We could call prevUserKey, but in some cases the SkipPoint
960 1 : // predicate function might be cheaper than prevUserKey's key copy
961 1 : // and key comparison. This should be the case for MVCC suffix
962 1 : // comparisons, for example. In the future, we could expand the
963 1 : // SkipPoint interface to give the implementor more control over
964 1 : // whether we skip over just the internal key, the user key, or even
965 1 : // the key prefix.
966 1 : i.stats.ReverseStepCount[InternalIterCall]++
967 1 : i.iterKey, i.iterValue = i.iter.Prev()
968 1 : if i.iterKey == nil {
969 1 : if err := i.iter.Error(); err != nil {
970 0 : i.err = err
971 0 : i.iterValidityState = IterExhausted
972 0 : return
973 0 : }
974 : }
975 1 : if limit != nil && i.iterKey != nil && i.cmp(limit, i.iterKey.UserKey) > 0 && !i.rangeKeyWithinLimit(limit) {
976 1 : i.iterValidityState = IterAtLimit
977 1 : i.pos = iterPosCurReversePaused
978 1 : return
979 1 : }
980 1 : continue
981 : }
982 :
983 1 : switch key.Kind() {
984 1 : case InternalKeyKindRangeKeySet:
985 1 : // Range key start boundary markers are interleaved with the maximum
986 1 : // sequence number, so if there's a point key also at this key, we
987 1 : // must've already iterated over it.
988 1 : // This is the final entry at this user key, so we may return
989 1 : i.rangeKey.rangeKeyOnly = i.iterValidityState != IterValid
990 1 : i.keyBuf = append(i.keyBuf[:0], key.UserKey...)
991 1 : i.key = i.keyBuf
992 1 : i.iterValidityState = IterValid
993 1 : i.saveRangeKey()
994 1 : // In all other cases, previous iteration requires advancing to
995 1 : // iterPosPrev in order to determine if the key is live and
996 1 : // unshadowed by another key at the same user key. In this case,
997 1 : // because range key start boundary markers are always interleaved
998 1 : // at the maximum sequence number, we know that there aren't any
999 1 : // additional keys with the same user key in the backward direction.
1000 1 : //
1001 1 : // We Prev the underlying iterator once anyways for consistency, so
1002 1 : // that we can maintain the invariant during backward iteration that
1003 1 : // i.iterPos = iterPosPrev.
1004 1 : i.stats.ReverseStepCount[InternalIterCall]++
1005 1 : i.iterKey, i.iterValue = i.iter.Prev()
1006 1 :
1007 1 : // Set rangeKeyBoundary so that on the next iteration, we know to
1008 1 : // return the key even if the MERGE point key is deleted.
1009 1 : rangeKeyBoundary = true
1010 :
1011 1 : case InternalKeyKindDelete, InternalKeyKindSingleDelete, InternalKeyKindDeleteSized:
1012 1 : i.value = LazyValue{}
1013 1 : i.iterValidityState = IterExhausted
1014 1 : valueMerger = nil
1015 1 : i.stats.ReverseStepCount[InternalIterCall]++
1016 1 : i.iterKey, i.iterValue = i.iter.Prev()
1017 1 : // Compare with the limit. We could optimize by only checking when
1018 1 : // we step to the previous user key, but detecting that requires a
1019 1 : // comparison too. Note that this position may already passed a
1020 1 : // number of versions of this user key, but they are all deleted, so
1021 1 : // the fact that a subsequent Prev*() call will not see them is
1022 1 : // harmless. Also note that this is the only place in the loop,
1023 1 : // other than the firstLoopIter and SkipPoint cases above, where we
1024 1 : // could step to a different user key and start processing it for
1025 1 : // returning to the caller.
1026 1 : if limit != nil && i.iterKey != nil && i.cmp(limit, i.iterKey.UserKey) > 0 && !i.rangeKeyWithinLimit(limit) {
1027 1 : i.iterValidityState = IterAtLimit
1028 1 : i.pos = iterPosCurReversePaused
1029 1 : return
1030 1 : }
1031 1 : continue
1032 :
1033 1 : case InternalKeyKindSet, InternalKeyKindSetWithDelete:
1034 1 : i.keyBuf = append(i.keyBuf[:0], key.UserKey...)
1035 1 : i.key = i.keyBuf
1036 1 : // iterValue is owned by i.iter and could change after the Prev()
1037 1 : // call, so use valueBuf instead. Note that valueBuf is only used
1038 1 : // in this one instance; everywhere else (eg. in findNextEntry),
1039 1 : // we just point i.value to the unsafe i.iter-owned value buffer.
1040 1 : i.value, i.valueBuf = i.iterValue.Clone(i.valueBuf[:0], &i.fetcher)
1041 1 : i.saveRangeKey()
1042 1 : i.iterValidityState = IterValid
1043 1 : i.iterKey, i.iterValue = i.iter.Prev()
1044 1 : i.stats.ReverseStepCount[InternalIterCall]++
1045 1 : valueMerger = nil
1046 1 : continue
1047 :
1048 1 : case InternalKeyKindMerge:
1049 1 : if i.iterValidityState == IterExhausted {
1050 1 : i.keyBuf = append(i.keyBuf[:0], key.UserKey...)
1051 1 : i.key = i.keyBuf
1052 1 : i.saveRangeKey()
1053 1 : var iterValue []byte
1054 1 : iterValue, _, i.err = i.iterValue.Value(nil)
1055 1 : if i.err != nil {
1056 0 : return
1057 0 : }
1058 1 : valueMerger, i.err = i.merge(i.key, iterValue)
1059 1 : if i.err != nil {
1060 0 : return
1061 0 : }
1062 1 : i.iterValidityState = IterValid
1063 1 : } else if valueMerger == nil {
1064 1 : // Extract value before iterValue since we use value before iterValue
1065 1 : // and the underlying iterator is not required to provide backing
1066 1 : // memory for both simultaneously.
1067 1 : var value []byte
1068 1 : var callerOwned bool
1069 1 : value, callerOwned, i.err = i.value.Value(i.lazyValueBuf)
1070 1 : if callerOwned {
1071 0 : i.lazyValueBuf = value[:0]
1072 0 : }
1073 1 : if i.err != nil {
1074 0 : i.iterValidityState = IterExhausted
1075 0 : return
1076 0 : }
1077 1 : valueMerger, i.err = i.merge(i.key, value)
1078 1 : var iterValue []byte
1079 1 : iterValue, _, i.err = i.iterValue.Value(nil)
1080 1 : if i.err != nil {
1081 0 : i.iterValidityState = IterExhausted
1082 0 : return
1083 0 : }
1084 1 : if i.err == nil {
1085 1 : i.err = valueMerger.MergeNewer(iterValue)
1086 1 : }
1087 1 : if i.err != nil {
1088 0 : i.iterValidityState = IterExhausted
1089 0 : return
1090 0 : }
1091 1 : } else {
1092 1 : var iterValue []byte
1093 1 : iterValue, _, i.err = i.iterValue.Value(nil)
1094 1 : if i.err != nil {
1095 0 : i.iterValidityState = IterExhausted
1096 0 : return
1097 0 : }
1098 1 : i.err = valueMerger.MergeNewer(iterValue)
1099 1 : if i.err != nil {
1100 0 : i.iterValidityState = IterExhausted
1101 0 : return
1102 0 : }
1103 : }
1104 1 : i.iterKey, i.iterValue = i.iter.Prev()
1105 1 : i.stats.ReverseStepCount[InternalIterCall]++
1106 1 : continue
1107 :
1108 0 : default:
1109 0 : i.err = base.CorruptionErrorf("pebble: invalid internal key kind: %d", errors.Safe(key.Kind()))
1110 0 : i.iterValidityState = IterExhausted
1111 0 : return
1112 : }
1113 : }
1114 : // i.iterKey == nil, so broke out of the preceding loop.
1115 :
1116 : // Is iterKey nil due to an error?
1117 1 : if i.err = i.iter.Error(); i.err != nil {
1118 1 : i.iterValidityState = IterExhausted
1119 1 : return
1120 1 : }
1121 :
1122 1 : if i.iterValidityState == IterValid {
1123 1 : i.pos = iterPosPrev
1124 1 : if valueMerger != nil {
1125 1 : var needDelete bool
1126 1 : var value []byte
1127 1 : value, needDelete, i.valueCloser, i.err = finishValueMerger(valueMerger, true /* includesBase */)
1128 1 : i.value = base.MakeInPlaceValue(value)
1129 1 : if i.err == nil && needDelete {
1130 1 : i.key = nil
1131 1 : i.value = LazyValue{}
1132 1 : i.iterValidityState = IterExhausted
1133 1 : }
1134 : }
1135 1 : if i.err != nil {
1136 0 : i.iterValidityState = IterExhausted
1137 0 : }
1138 : }
1139 : }
1140 :
1141 1 : func (i *Iterator) prevUserKey() {
1142 1 : if i.iterKey == nil {
1143 1 : return
1144 1 : }
1145 1 : if i.iterValidityState != IterValid {
1146 1 : // If we're going to compare against the prev key, we need to save the
1147 1 : // current key.
1148 1 : i.keyBuf = append(i.keyBuf[:0], i.iterKey.UserKey...)
1149 1 : i.key = i.keyBuf
1150 1 : }
1151 1 : for {
1152 1 : i.iterKey, i.iterValue = i.iter.Prev()
1153 1 : i.stats.ReverseStepCount[InternalIterCall]++
1154 1 : if i.iterKey == nil {
1155 1 : if err := i.iter.Error(); err != nil {
1156 0 : i.err = err
1157 0 : i.iterValidityState = IterExhausted
1158 0 : }
1159 1 : break
1160 : }
1161 1 : if !i.equal(i.key, i.iterKey.UserKey) {
1162 1 : break
1163 : }
1164 : }
1165 : }
1166 :
1167 1 : func (i *Iterator) mergeNext(key InternalKey, valueMerger ValueMerger) {
1168 1 : // Save the current key.
1169 1 : i.keyBuf = append(i.keyBuf[:0], key.UserKey...)
1170 1 : i.key = i.keyBuf
1171 1 :
1172 1 : // Loop looking for older values for this key and merging them.
1173 1 : for {
1174 1 : i.iterKey, i.iterValue = i.iter.Next()
1175 1 : i.stats.ForwardStepCount[InternalIterCall]++
1176 1 : if i.iterKey == nil {
1177 1 : if i.err = i.iter.Error(); i.err != nil {
1178 1 : return
1179 1 : }
1180 1 : i.pos = iterPosNext
1181 1 : return
1182 : }
1183 1 : key = *i.iterKey
1184 1 : if !i.equal(i.key, key.UserKey) {
1185 1 : // We've advanced to the next key.
1186 1 : i.pos = iterPosNext
1187 1 : return
1188 1 : }
1189 1 : switch key.Kind() {
1190 1 : case InternalKeyKindDelete, InternalKeyKindSingleDelete, InternalKeyKindDeleteSized:
1191 1 : // We've hit a deletion tombstone. Return everything up to this
1192 1 : // point.
1193 1 : //
1194 1 : // NB: treating InternalKeyKindSingleDelete as equivalent to DEL is not
1195 1 : // only simpler, but is also necessary for correctness due to
1196 1 : // InternalKeyKindSSTableInternalObsoleteBit.
1197 1 : return
1198 :
1199 1 : case InternalKeyKindSet, InternalKeyKindSetWithDelete:
1200 1 : // We've hit a Set value. Merge with the existing value and return.
1201 1 : var iterValue []byte
1202 1 : iterValue, _, i.err = i.iterValue.Value(nil)
1203 1 : if i.err != nil {
1204 0 : return
1205 0 : }
1206 1 : i.err = valueMerger.MergeOlder(iterValue)
1207 1 : return
1208 :
1209 1 : case InternalKeyKindMerge:
1210 1 : // We've hit another Merge value. Merge with the existing value and
1211 1 : // continue looping.
1212 1 : var iterValue []byte
1213 1 : iterValue, _, i.err = i.iterValue.Value(nil)
1214 1 : if i.err != nil {
1215 0 : return
1216 0 : }
1217 1 : i.err = valueMerger.MergeOlder(iterValue)
1218 1 : if i.err != nil {
1219 0 : return
1220 0 : }
1221 1 : continue
1222 :
1223 0 : case InternalKeyKindRangeKeySet:
1224 0 : // The RANGEKEYSET marker must sort before a MERGE at the same user key.
1225 0 : i.err = base.CorruptionErrorf("pebble: out of order range key marker")
1226 0 : return
1227 :
1228 0 : default:
1229 0 : i.err = base.CorruptionErrorf("pebble: invalid internal key kind: %d", errors.Safe(key.Kind()))
1230 0 : return
1231 : }
1232 : }
1233 : }
1234 :
1235 : // SeekGE moves the iterator to the first key/value pair whose key is greater
1236 : // than or equal to the given key. Returns true if the iterator is pointing at
1237 : // a valid entry and false otherwise.
1238 1 : func (i *Iterator) SeekGE(key []byte) bool {
1239 1 : return i.SeekGEWithLimit(key, nil) == IterValid
1240 1 : }
1241 :
1242 : // SeekGEWithLimit moves the iterator to the first key/value pair whose key is
1243 : // greater than or equal to the given key.
1244 : //
1245 : // If limit is provided, it serves as a best-effort exclusive limit. If the
1246 : // first key greater than or equal to the given search key is also greater than
1247 : // or equal to limit, the Iterator may pause and return IterAtLimit. Because
1248 : // limits are best-effort, SeekGEWithLimit may return a key beyond limit.
1249 : //
1250 : // If the Iterator is configured to iterate over range keys, SeekGEWithLimit
1251 : // guarantees it will surface any range keys with bounds overlapping the
1252 : // keyspace [key, limit).
1253 1 : func (i *Iterator) SeekGEWithLimit(key []byte, limit []byte) IterValidityState {
1254 1 : if i.rangeKey != nil {
1255 1 : // NB: Check Valid() before clearing requiresReposition.
1256 1 : i.rangeKey.prevPosHadRangeKey = i.rangeKey.hasRangeKey && i.Valid()
1257 1 : // If we have a range key but did not expose it at the previous iterator
1258 1 : // position (because the iterator was not at a valid position), updated
1259 1 : // must be true. This ensures that after an iterator op sequence like:
1260 1 : // - Next() → (IterValid, RangeBounds() = [a,b))
1261 1 : // - NextWithLimit(...) → (IterAtLimit, RangeBounds() = -)
1262 1 : // - SeekGE(...) → (IterValid, RangeBounds() = [a,b))
1263 1 : // the iterator returns RangeKeyChanged()=true.
1264 1 : //
1265 1 : // The remainder of this function will only update i.rangeKey.updated if
1266 1 : // the iterator moves into a new range key, or out of the current range
1267 1 : // key.
1268 1 : i.rangeKey.updated = i.rangeKey.hasRangeKey && !i.Valid() && i.opts.rangeKeys()
1269 1 : }
1270 1 : lastPositioningOp := i.lastPositioningOp
1271 1 : // Set it to unknown, since this operation may not succeed, in which case
1272 1 : // the SeekGE following this should not make any assumption about iterator
1273 1 : // position.
1274 1 : i.lastPositioningOp = unknownLastPositionOp
1275 1 : i.requiresReposition = false
1276 1 : i.err = nil // clear cached iteration error
1277 1 : i.hasPrefix = false
1278 1 : i.stats.ForwardSeekCount[InterfaceCall]++
1279 1 : if lowerBound := i.opts.GetLowerBound(); lowerBound != nil && i.cmp(key, lowerBound) < 0 {
1280 1 : key = lowerBound
1281 1 : } else if upperBound := i.opts.GetUpperBound(); upperBound != nil && i.cmp(key, upperBound) > 0 {
1282 1 : key = upperBound
1283 1 : }
1284 1 : seekInternalIter := true
1285 1 :
1286 1 : var flags base.SeekGEFlags
1287 1 : if i.batchJustRefreshed {
1288 1 : i.batchJustRefreshed = false
1289 1 : flags = flags.EnableBatchJustRefreshed()
1290 1 : }
1291 1 : if lastPositioningOp == seekGELastPositioningOp {
1292 1 : cmp := i.cmp(i.prefixOrFullSeekKey, key)
1293 1 : // If this seek is to the same or later key, and the iterator is
1294 1 : // already positioned there, this is a noop. This can be helpful for
1295 1 : // sparse key spaces that have many deleted keys, where one can avoid
1296 1 : // the overhead of iterating past them again and again.
1297 1 : if cmp <= 0 {
1298 1 : if !flags.BatchJustRefreshed() &&
1299 1 : (i.iterValidityState == IterExhausted ||
1300 1 : (i.iterValidityState == IterValid && i.cmp(key, i.key) <= 0 &&
1301 1 : (limit == nil || i.cmp(i.key, limit) < 0))) {
1302 1 : // Noop
1303 1 : if !invariants.Enabled || !disableSeekOpt(key, uintptr(unsafe.Pointer(i))) || i.forceEnableSeekOpt {
1304 1 : i.lastPositioningOp = seekGELastPositioningOp
1305 1 : return i.iterValidityState
1306 1 : }
1307 : }
1308 : // cmp == 0 is not safe to optimize since
1309 : // - i.pos could be at iterPosNext, due to a merge.
1310 : // - Even if i.pos were at iterPosCurForward, we could have a DELETE,
1311 : // SET pair for a key, and the iterator would have moved past DELETE
1312 : // but stayed at iterPosCurForward. A similar situation occurs for a
1313 : // MERGE, SET pair where the MERGE is consumed and the iterator is
1314 : // at the SET.
1315 : // We also leverage the IterAtLimit <=> i.pos invariant defined in the
1316 : // comment on iterValidityState, to exclude any cases where i.pos
1317 : // is iterPosCur{Forward,Reverse}Paused. This avoids the need to
1318 : // special-case those iterator positions and their interactions with
1319 : // TrySeekUsingNext, as the main uses for TrySeekUsingNext in CockroachDB
1320 : // do not use limited Seeks in the first place.
1321 1 : if cmp < 0 && i.iterValidityState != IterAtLimit && limit == nil {
1322 1 : flags = flags.EnableTrySeekUsingNext()
1323 1 : }
1324 1 : if invariants.Enabled && flags.TrySeekUsingNext() && !i.forceEnableSeekOpt && disableSeekOpt(key, uintptr(unsafe.Pointer(i))) {
1325 1 : flags = flags.DisableTrySeekUsingNext()
1326 1 : }
1327 1 : if !flags.BatchJustRefreshed() && i.pos == iterPosCurForwardPaused && i.cmp(key, i.iterKey.UserKey) <= 0 {
1328 1 : // Have some work to do, but don't need to seek, and we can
1329 1 : // start doing findNextEntry from i.iterKey.
1330 1 : seekInternalIter = false
1331 1 : }
1332 : }
1333 : }
1334 1 : if seekInternalIter {
1335 1 : i.iterKey, i.iterValue = i.iter.SeekGE(key, flags)
1336 1 : i.stats.ForwardSeekCount[InternalIterCall]++
1337 1 : if err := i.iter.Error(); err != nil {
1338 1 : i.err = err
1339 1 : i.iterValidityState = IterExhausted
1340 1 : return i.iterValidityState
1341 1 : }
1342 : }
1343 1 : i.findNextEntry(limit)
1344 1 : i.maybeSampleRead()
1345 1 : if i.Error() == nil {
1346 1 : // Prepare state for a future noop optimization.
1347 1 : i.prefixOrFullSeekKey = append(i.prefixOrFullSeekKey[:0], key...)
1348 1 : i.lastPositioningOp = seekGELastPositioningOp
1349 1 : }
1350 1 : return i.iterValidityState
1351 : }
1352 :
1353 : // SeekPrefixGE moves the iterator to the first key/value pair whose key is
1354 : // greater than or equal to the given key and which has the same "prefix" as
1355 : // the given key. The prefix for a key is determined by the user-defined
1356 : // Comparer.Split function. The iterator will not observe keys not matching the
1357 : // "prefix" of the search key. Calling SeekPrefixGE puts the iterator in prefix
1358 : // iteration mode. The iterator remains in prefix iteration until a subsequent
1359 : // call to another absolute positioning method (SeekGE, SeekLT, First,
1360 : // Last). Reverse iteration (Prev) is not supported when an iterator is in
1361 : // prefix iteration mode. Returns true if the iterator is pointing at a valid
1362 : // entry and false otherwise.
1363 : //
1364 : // The semantics of SeekPrefixGE are slightly unusual and designed for
1365 : // iteration to be able to take advantage of bloom filters that have been
1366 : // created on the "prefix". If you're not using bloom filters, there is no
1367 : // reason to use SeekPrefixGE.
1368 : //
1369 : // An example Split function may separate a timestamp suffix from the prefix of
1370 : // the key.
1371 : //
1372 : // Split(<key>@<timestamp>) -> <key>
1373 : //
1374 : // Consider the keys "a@1", "a@2", "aa@3", "aa@4". The prefixes for these keys
1375 : // are "a", and "aa". Note that despite "a" and "aa" sharing a prefix by the
1376 : // usual definition, those prefixes differ by the definition of the Split
1377 : // function. To see how this works, consider the following set of calls on this
1378 : // data set:
1379 : //
1380 : // SeekPrefixGE("a@0") -> "a@1"
1381 : // Next() -> "a@2"
1382 : // Next() -> EOF
1383 : //
1384 : // If you're just looking to iterate over keys with a shared prefix, as
1385 : // defined by the configured comparer, set iterator bounds instead:
1386 : //
1387 : // iter := db.NewIter(&pebble.IterOptions{
1388 : // LowerBound: []byte("prefix"),
1389 : // UpperBound: []byte("prefiy"),
1390 : // })
1391 : // for iter.First(); iter.Valid(); iter.Next() {
1392 : // // Only keys beginning with "prefix" will be visited.
1393 : // }
1394 : //
1395 : // See ExampleIterator_SeekPrefixGE for a working example.
1396 : //
1397 : // When iterating with range keys enabled, all range keys encountered are
1398 : // truncated to the seek key's prefix's bounds. The truncation of the upper
1399 : // bound requires that the database's Comparer is configured with a
1400 : // ImmediateSuccessor method. For example, a SeekPrefixGE("a@9") call with the
1401 : // prefix "a" will truncate range key bounds to [a,ImmediateSuccessor(a)].
1402 1 : func (i *Iterator) SeekPrefixGE(key []byte) bool {
1403 1 : if i.rangeKey != nil {
1404 1 : // NB: Check Valid() before clearing requiresReposition.
1405 1 : i.rangeKey.prevPosHadRangeKey = i.rangeKey.hasRangeKey && i.Valid()
1406 1 : // If we have a range key but did not expose it at the previous iterator
1407 1 : // position (because the iterator was not at a valid position), updated
1408 1 : // must be true. This ensures that after an iterator op sequence like:
1409 1 : // - Next() → (IterValid, RangeBounds() = [a,b))
1410 1 : // - NextWithLimit(...) → (IterAtLimit, RangeBounds() = -)
1411 1 : // - SeekPrefixGE(...) → (IterValid, RangeBounds() = [a,b))
1412 1 : // the iterator returns RangeKeyChanged()=true.
1413 1 : //
1414 1 : // The remainder of this function will only update i.rangeKey.updated if
1415 1 : // the iterator moves into a new range key, or out of the current range
1416 1 : // key.
1417 1 : i.rangeKey.updated = i.rangeKey.hasRangeKey && !i.Valid() && i.opts.rangeKeys()
1418 1 : }
1419 1 : lastPositioningOp := i.lastPositioningOp
1420 1 : // Set it to unknown, since this operation may not succeed, in which case
1421 1 : // the SeekPrefixGE following this should not make any assumption about
1422 1 : // iterator position.
1423 1 : i.lastPositioningOp = unknownLastPositionOp
1424 1 : i.requiresReposition = false
1425 1 : i.err = nil // clear cached iteration error
1426 1 : i.stats.ForwardSeekCount[InterfaceCall]++
1427 1 : if i.comparer.ImmediateSuccessor == nil && i.opts.KeyTypes != IterKeyTypePointsOnly {
1428 0 : panic("pebble: ImmediateSuccessor must be provided for SeekPrefixGE with range keys")
1429 : }
1430 1 : prefixLen := i.split(key)
1431 1 : keyPrefix := key[:prefixLen]
1432 1 : var flags base.SeekGEFlags
1433 1 : if i.batchJustRefreshed {
1434 1 : flags = flags.EnableBatchJustRefreshed()
1435 1 : i.batchJustRefreshed = false
1436 1 : }
1437 1 : if lastPositioningOp == seekPrefixGELastPositioningOp {
1438 1 : if !i.hasPrefix {
1439 0 : panic("lastPositioningOpsIsSeekPrefixGE is true, but hasPrefix is false")
1440 : }
1441 : // The iterator has not been repositioned after the last SeekPrefixGE.
1442 : // See if we are seeking to a larger key, since then we can optimize
1443 : // the seek by using next. Note that we could also optimize if Next
1444 : // has been called, if the iterator is not exhausted and the current
1445 : // position is <= the seek key. We are keeping this limited for now
1446 : // since such optimizations require care for correctness, and to not
1447 : // become de-optimizations (if one usually has to do all the next
1448 : // calls and then the seek). This SeekPrefixGE optimization
1449 : // specifically benefits CockroachDB.
1450 1 : cmp := i.cmp(i.prefixOrFullSeekKey, keyPrefix)
1451 1 : // cmp == 0 is not safe to optimize since
1452 1 : // - i.pos could be at iterPosNext, due to a merge.
1453 1 : // - Even if i.pos were at iterPosCurForward, we could have a DELETE,
1454 1 : // SET pair for a key, and the iterator would have moved past DELETE
1455 1 : // but stayed at iterPosCurForward. A similar situation occurs for a
1456 1 : // MERGE, SET pair where the MERGE is consumed and the iterator is
1457 1 : // at the SET.
1458 1 : // In general some versions of i.prefix could have been consumed by
1459 1 : // the iterator, so we only optimize for cmp < 0.
1460 1 : if cmp < 0 {
1461 1 : flags = flags.EnableTrySeekUsingNext()
1462 1 : }
1463 1 : if invariants.Enabled && flags.TrySeekUsingNext() && !i.forceEnableSeekOpt && disableSeekOpt(key, uintptr(unsafe.Pointer(i))) {
1464 1 : flags = flags.DisableTrySeekUsingNext()
1465 1 : }
1466 : }
1467 : // Make a copy of the prefix so that modifications to the key after
1468 : // SeekPrefixGE returns does not affect the stored prefix.
1469 1 : if cap(i.prefixOrFullSeekKey) < prefixLen {
1470 1 : i.prefixOrFullSeekKey = make([]byte, prefixLen)
1471 1 : } else {
1472 1 : i.prefixOrFullSeekKey = i.prefixOrFullSeekKey[:prefixLen]
1473 1 : }
1474 1 : i.hasPrefix = true
1475 1 : copy(i.prefixOrFullSeekKey, keyPrefix)
1476 1 :
1477 1 : if lowerBound := i.opts.GetLowerBound(); lowerBound != nil && i.cmp(key, lowerBound) < 0 {
1478 1 : if n := i.split(lowerBound); !bytes.Equal(i.prefixOrFullSeekKey, lowerBound[:n]) {
1479 1 : i.err = errors.New("pebble: SeekPrefixGE supplied with key outside of lower bound")
1480 1 : i.iterValidityState = IterExhausted
1481 1 : return false
1482 1 : }
1483 0 : key = lowerBound
1484 1 : } else if upperBound := i.opts.GetUpperBound(); upperBound != nil && i.cmp(key, upperBound) > 0 {
1485 1 : if n := i.split(upperBound); !bytes.Equal(i.prefixOrFullSeekKey, upperBound[:n]) {
1486 1 : i.err = errors.New("pebble: SeekPrefixGE supplied with key outside of upper bound")
1487 1 : i.iterValidityState = IterExhausted
1488 1 : return false
1489 1 : }
1490 0 : key = upperBound
1491 : }
1492 1 : i.iterKey, i.iterValue = i.iter.SeekPrefixGE(i.prefixOrFullSeekKey, key, flags)
1493 1 : i.stats.ForwardSeekCount[InternalIterCall]++
1494 1 : i.findNextEntry(nil)
1495 1 : i.maybeSampleRead()
1496 1 : if i.Error() == nil {
1497 1 : i.lastPositioningOp = seekPrefixGELastPositioningOp
1498 1 : }
1499 1 : return i.iterValidityState == IterValid
1500 : }
1501 :
1502 : // Deterministic disabling of the seek optimizations. It uses the iterator
1503 : // pointer, since we want diversity in iterator behavior for the same key. Used
1504 : // for tests.
1505 1 : func disableSeekOpt(key []byte, ptr uintptr) bool {
1506 1 : // Fibonacci hash https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/
1507 1 : simpleHash := (11400714819323198485 * uint64(ptr)) >> 63
1508 1 : return key != nil && key[0]&byte(1) == 0 && simpleHash == 0
1509 1 : }
1510 :
1511 : // SeekLT moves the iterator to the last key/value pair whose key is less than
1512 : // the given key. Returns true if the iterator is pointing at a valid entry and
1513 : // false otherwise.
1514 1 : func (i *Iterator) SeekLT(key []byte) bool {
1515 1 : return i.SeekLTWithLimit(key, nil) == IterValid
1516 1 : }
1517 :
1518 : // SeekLTWithLimit moves the iterator to the last key/value pair whose key is
1519 : // less than the given key.
1520 : //
1521 : // If limit is provided, it serves as a best-effort inclusive limit. If the last
1522 : // key less than the given search key is also less than limit, the Iterator may
1523 : // pause and return IterAtLimit. Because limits are best-effort, SeekLTWithLimit
1524 : // may return a key beyond limit.
1525 : //
1526 : // If the Iterator is configured to iterate over range keys, SeekLTWithLimit
1527 : // guarantees it will surface any range keys with bounds overlapping the
1528 : // keyspace up to limit.
1529 1 : func (i *Iterator) SeekLTWithLimit(key []byte, limit []byte) IterValidityState {
1530 1 : if i.rangeKey != nil {
1531 1 : // NB: Check Valid() before clearing requiresReposition.
1532 1 : i.rangeKey.prevPosHadRangeKey = i.rangeKey.hasRangeKey && i.Valid()
1533 1 : // If we have a range key but did not expose it at the previous iterator
1534 1 : // position (because the iterator was not at a valid position), updated
1535 1 : // must be true. This ensures that after an iterator op sequence like:
1536 1 : // - Next() → (IterValid, RangeBounds() = [a,b))
1537 1 : // - NextWithLimit(...) → (IterAtLimit, RangeBounds() = -)
1538 1 : // - SeekLTWithLimit(...) → (IterValid, RangeBounds() = [a,b))
1539 1 : // the iterator returns RangeKeyChanged()=true.
1540 1 : //
1541 1 : // The remainder of this function will only update i.rangeKey.updated if
1542 1 : // the iterator moves into a new range key, or out of the current range
1543 1 : // key.
1544 1 : i.rangeKey.updated = i.rangeKey.hasRangeKey && !i.Valid() && i.opts.rangeKeys()
1545 1 : }
1546 1 : lastPositioningOp := i.lastPositioningOp
1547 1 : // Set it to unknown, since this operation may not succeed, in which case
1548 1 : // the SeekLT following this should not make any assumption about iterator
1549 1 : // position.
1550 1 : i.lastPositioningOp = unknownLastPositionOp
1551 1 : i.batchJustRefreshed = false
1552 1 : i.requiresReposition = false
1553 1 : i.err = nil // clear cached iteration error
1554 1 : i.stats.ReverseSeekCount[InterfaceCall]++
1555 1 : if upperBound := i.opts.GetUpperBound(); upperBound != nil && i.cmp(key, upperBound) > 0 {
1556 1 : key = upperBound
1557 1 : } else if lowerBound := i.opts.GetLowerBound(); lowerBound != nil && i.cmp(key, lowerBound) < 0 {
1558 1 : key = lowerBound
1559 1 : }
1560 1 : i.hasPrefix = false
1561 1 : seekInternalIter := true
1562 1 : // The following noop optimization only applies when i.batch == nil, since
1563 1 : // an iterator over a batch is iterating over mutable data, that may have
1564 1 : // changed since the last seek.
1565 1 : if lastPositioningOp == seekLTLastPositioningOp && i.batch == nil {
1566 1 : cmp := i.cmp(key, i.prefixOrFullSeekKey)
1567 1 : // If this seek is to the same or earlier key, and the iterator is
1568 1 : // already positioned there, this is a noop. This can be helpful for
1569 1 : // sparse key spaces that have many deleted keys, where one can avoid
1570 1 : // the overhead of iterating past them again and again.
1571 1 : if cmp <= 0 {
1572 1 : // NB: when pos != iterPosCurReversePaused, the invariant
1573 1 : // documented earlier implies that iterValidityState !=
1574 1 : // IterAtLimit.
1575 1 : if i.iterValidityState == IterExhausted ||
1576 1 : (i.iterValidityState == IterValid && i.cmp(i.key, key) < 0 &&
1577 1 : (limit == nil || i.cmp(limit, i.key) <= 0)) {
1578 1 : if !invariants.Enabled || !disableSeekOpt(key, uintptr(unsafe.Pointer(i))) {
1579 1 : i.lastPositioningOp = seekLTLastPositioningOp
1580 1 : return i.iterValidityState
1581 1 : }
1582 : }
1583 1 : if i.pos == iterPosCurReversePaused && i.cmp(i.iterKey.UserKey, key) < 0 {
1584 1 : // Have some work to do, but don't need to seek, and we can
1585 1 : // start doing findPrevEntry from i.iterKey.
1586 1 : seekInternalIter = false
1587 1 : }
1588 : }
1589 : }
1590 1 : if seekInternalIter {
1591 1 : i.iterKey, i.iterValue = i.iter.SeekLT(key, base.SeekLTFlagsNone)
1592 1 : i.stats.ReverseSeekCount[InternalIterCall]++
1593 1 : if err := i.iter.Error(); err != nil {
1594 1 : i.err = err
1595 1 : i.iterValidityState = IterExhausted
1596 1 : return i.iterValidityState
1597 1 : }
1598 : }
1599 1 : i.findPrevEntry(limit)
1600 1 : i.maybeSampleRead()
1601 1 : if i.Error() == nil && i.batch == nil {
1602 1 : // Prepare state for a future noop optimization.
1603 1 : i.prefixOrFullSeekKey = append(i.prefixOrFullSeekKey[:0], key...)
1604 1 : i.lastPositioningOp = seekLTLastPositioningOp
1605 1 : }
1606 1 : return i.iterValidityState
1607 : }
1608 :
1609 : // First moves the iterator the the first key/value pair. Returns true if the
1610 : // iterator is pointing at a valid entry and false otherwise.
1611 1 : func (i *Iterator) First() bool {
1612 1 : if i.rangeKey != nil {
1613 1 : // NB: Check Valid() before clearing requiresReposition.
1614 1 : i.rangeKey.prevPosHadRangeKey = i.rangeKey.hasRangeKey && i.Valid()
1615 1 : // If we have a range key but did not expose it at the previous iterator
1616 1 : // position (because the iterator was not at a valid position), updated
1617 1 : // must be true. This ensures that after an iterator op sequence like:
1618 1 : // - Next() → (IterValid, RangeBounds() = [a,b))
1619 1 : // - NextWithLimit(...) → (IterAtLimit, RangeBounds() = -)
1620 1 : // - First(...) → (IterValid, RangeBounds() = [a,b))
1621 1 : // the iterator returns RangeKeyChanged()=true.
1622 1 : //
1623 1 : // The remainder of this function will only update i.rangeKey.updated if
1624 1 : // the iterator moves into a new range key, or out of the current range
1625 1 : // key.
1626 1 : i.rangeKey.updated = i.rangeKey.hasRangeKey && !i.Valid() && i.opts.rangeKeys()
1627 1 : }
1628 1 : i.err = nil // clear cached iteration error
1629 1 : i.hasPrefix = false
1630 1 : i.batchJustRefreshed = false
1631 1 : i.lastPositioningOp = unknownLastPositionOp
1632 1 : i.requiresReposition = false
1633 1 : i.stats.ForwardSeekCount[InterfaceCall]++
1634 1 :
1635 1 : i.iterFirstWithinBounds()
1636 1 : if i.err != nil {
1637 0 : i.iterValidityState = IterExhausted
1638 0 : return false
1639 0 : }
1640 1 : i.findNextEntry(nil)
1641 1 : i.maybeSampleRead()
1642 1 : return i.iterValidityState == IterValid
1643 : }
1644 :
1645 : // Last moves the iterator the the last key/value pair. Returns true if the
1646 : // iterator is pointing at a valid entry and false otherwise.
1647 1 : func (i *Iterator) Last() bool {
1648 1 : if i.rangeKey != nil {
1649 1 : // NB: Check Valid() before clearing requiresReposition.
1650 1 : i.rangeKey.prevPosHadRangeKey = i.rangeKey.hasRangeKey && i.Valid()
1651 1 : // If we have a range key but did not expose it at the previous iterator
1652 1 : // position (because the iterator was not at a valid position), updated
1653 1 : // must be true. This ensures that after an iterator op sequence like:
1654 1 : // - Next() → (IterValid, RangeBounds() = [a,b))
1655 1 : // - NextWithLimit(...) → (IterAtLimit, RangeBounds() = -)
1656 1 : // - Last(...) → (IterValid, RangeBounds() = [a,b))
1657 1 : // the iterator returns RangeKeyChanged()=true.
1658 1 : //
1659 1 : // The remainder of this function will only update i.rangeKey.updated if
1660 1 : // the iterator moves into a new range key, or out of the current range
1661 1 : // key.
1662 1 : i.rangeKey.updated = i.rangeKey.hasRangeKey && !i.Valid() && i.opts.rangeKeys()
1663 1 : }
1664 1 : i.err = nil // clear cached iteration error
1665 1 : i.hasPrefix = false
1666 1 : i.batchJustRefreshed = false
1667 1 : i.lastPositioningOp = unknownLastPositionOp
1668 1 : i.requiresReposition = false
1669 1 : i.stats.ReverseSeekCount[InterfaceCall]++
1670 1 :
1671 1 : i.iterLastWithinBounds()
1672 1 : if i.err != nil {
1673 0 : i.iterValidityState = IterExhausted
1674 0 : return false
1675 0 : }
1676 1 : i.findPrevEntry(nil)
1677 1 : i.maybeSampleRead()
1678 1 : return i.iterValidityState == IterValid
1679 : }
1680 :
1681 : // Next moves the iterator to the next key/value pair. Returns true if the
1682 : // iterator is pointing at a valid entry and false otherwise.
1683 1 : func (i *Iterator) Next() bool {
1684 1 : return i.nextWithLimit(nil) == IterValid
1685 1 : }
1686 :
1687 : // NextWithLimit moves the iterator to the next key/value pair.
1688 : //
1689 : // If limit is provided, it serves as a best-effort exclusive limit. If the next
1690 : // key is greater than or equal to limit, the Iterator may pause and return
1691 : // IterAtLimit. Because limits are best-effort, NextWithLimit may return a key
1692 : // beyond limit.
1693 : //
1694 : // If the Iterator is configured to iterate over range keys, NextWithLimit
1695 : // guarantees it will surface any range keys with bounds overlapping the
1696 : // keyspace up to limit.
1697 1 : func (i *Iterator) NextWithLimit(limit []byte) IterValidityState {
1698 1 : return i.nextWithLimit(limit)
1699 1 : }
1700 :
1701 : // NextPrefix moves the iterator to the next key/value pair with a key
1702 : // containing a different prefix than the current key. Prefixes are determined
1703 : // by Comparer.Split. Exhausts the iterator if invoked while in prefix-iteration
1704 : // mode.
1705 : //
1706 : // It is not permitted to invoke NextPrefix while at a IterAtLimit position.
1707 : // When called in this condition, NextPrefix has non-deterministic behavior.
1708 : //
1709 : // It is not permitted to invoke NextPrefix when the Iterator has an
1710 : // upper-bound that is a versioned MVCC key (see the comment for
1711 : // Comparer.Split). It returns an error in this case.
1712 1 : func (i *Iterator) NextPrefix() bool {
1713 1 : if i.nextPrefixNotPermittedByUpperBound {
1714 1 : i.lastPositioningOp = unknownLastPositionOp
1715 1 : i.requiresReposition = false
1716 1 : i.err = errors.Errorf("NextPrefix not permitted with upper bound %s",
1717 1 : i.comparer.FormatKey(i.opts.UpperBound))
1718 1 : i.iterValidityState = IterExhausted
1719 1 : return false
1720 1 : }
1721 1 : if i.hasPrefix {
1722 1 : i.iterValidityState = IterExhausted
1723 1 : return false
1724 1 : }
1725 1 : return i.nextPrefix() == IterValid
1726 : }
1727 :
1728 1 : func (i *Iterator) nextPrefix() IterValidityState {
1729 1 : if i.rangeKey != nil {
1730 1 : // NB: Check Valid() before clearing requiresReposition.
1731 1 : i.rangeKey.prevPosHadRangeKey = i.rangeKey.hasRangeKey && i.Valid()
1732 1 : // If we have a range key but did not expose it at the previous iterator
1733 1 : // position (because the iterator was not at a valid position), updated
1734 1 : // must be true. This ensures that after an iterator op sequence like:
1735 1 : // - Next() → (IterValid, RangeBounds() = [a,b))
1736 1 : // - NextWithLimit(...) → (IterAtLimit, RangeBounds() = -)
1737 1 : // - NextWithLimit(...) → (IterValid, RangeBounds() = [a,b))
1738 1 : // the iterator returns RangeKeyChanged()=true.
1739 1 : //
1740 1 : // The remainder of this function will only update i.rangeKey.updated if
1741 1 : // the iterator moves into a new range key, or out of the current range
1742 1 : // key.
1743 1 : i.rangeKey.updated = i.rangeKey.hasRangeKey && !i.Valid() && i.opts.rangeKeys()
1744 1 : }
1745 :
1746 : // Although NextPrefix documents that behavior at IterAtLimit is undefined,
1747 : // this function handles these cases as a simple prefix-agnostic Next. This
1748 : // is done for deterministic behavior in the metamorphic tests.
1749 : //
1750 : // TODO(jackson): If the metamorphic test operation generator is adjusted to
1751 : // make generation of some operations conditional on the previous
1752 : // operations, then we can remove this behavior and explicitly error.
1753 :
1754 1 : i.lastPositioningOp = unknownLastPositionOp
1755 1 : i.requiresReposition = false
1756 1 : switch i.pos {
1757 1 : case iterPosCurForward:
1758 1 : // Positioned on the current key. Advance to the next prefix.
1759 1 : i.internalNextPrefix(i.split(i.key))
1760 0 : case iterPosCurForwardPaused:
1761 : // Positioned at a limit. Implement as a prefix-agnostic Next. See TODO
1762 : // up above. The iterator is already positioned at the next key.
1763 1 : case iterPosCurReverse:
1764 1 : // Switching directions.
1765 1 : // Unless the iterator was exhausted, reverse iteration needs to
1766 1 : // position the iterator at iterPosPrev.
1767 1 : if i.iterKey != nil {
1768 0 : i.err = errors.New("switching from reverse to forward but iter is not at prev")
1769 0 : i.iterValidityState = IterExhausted
1770 0 : return i.iterValidityState
1771 0 : }
1772 : // The Iterator is exhausted and i.iter is positioned before the first
1773 : // key. Reposition to point to the first internal key.
1774 1 : i.iterFirstWithinBounds()
1775 0 : case iterPosCurReversePaused:
1776 0 : // Positioned at a limit. Implement as a prefix-agnostic Next. See TODO
1777 0 : // up above.
1778 0 : //
1779 0 : // Switching directions; The iterator must not be exhausted since it
1780 0 : // paused.
1781 0 : if i.iterKey == nil {
1782 0 : i.err = errors.New("switching paused from reverse to forward but iter is exhausted")
1783 0 : i.iterValidityState = IterExhausted
1784 0 : return i.iterValidityState
1785 0 : }
1786 0 : i.nextUserKey()
1787 1 : case iterPosPrev:
1788 1 : // The underlying iterator is pointed to the previous key (this can
1789 1 : // only happen when switching iteration directions).
1790 1 : if i.iterKey == nil {
1791 1 : // We're positioned before the first key. Need to reposition to point to
1792 1 : // the first key.
1793 1 : i.iterFirstWithinBounds()
1794 1 : } else {
1795 1 : // Move the internal iterator back onto the user key stored in
1796 1 : // i.key. iterPosPrev guarantees that it's positioned at the last
1797 1 : // key with the user key less than i.key, so we're guaranteed to
1798 1 : // land on the correct key with a single Next.
1799 1 : i.iterKey, i.iterValue = i.iter.Next()
1800 1 : if i.iterKey == nil {
1801 1 : // This should only be possible if i.iter.Next() encountered an
1802 1 : // error.
1803 1 : if i.iter.Error() == nil {
1804 0 : i.opts.logger.Fatalf("pebble: invariant violation: Nexting internal iterator from iterPosPrev found nothing")
1805 0 : }
1806 : // NB: Iterator.Error() will return i.iter.Error().
1807 1 : i.iterValidityState = IterExhausted
1808 1 : return i.iterValidityState
1809 : }
1810 1 : if invariants.Enabled && !i.equal(i.iterKey.UserKey, i.key) {
1811 0 : i.opts.logger.Fatalf("pebble: invariant violation: Nexting internal iterator from iterPosPrev landed on %q, not %q",
1812 0 : i.iterKey.UserKey, i.key)
1813 0 : }
1814 : }
1815 : // The internal iterator is now positioned at i.key. Advance to the next
1816 : // prefix.
1817 1 : i.internalNextPrefix(i.split(i.key))
1818 1 : case iterPosNext:
1819 1 : // Already positioned on the next key. Only call nextPrefixKey if the
1820 1 : // next key shares the same prefix.
1821 1 : if i.iterKey != nil {
1822 1 : currKeyPrefixLen := i.split(i.key)
1823 1 : iterKeyPrefixLen := i.split(i.iterKey.UserKey)
1824 1 : if bytes.Equal(i.iterKey.UserKey[:iterKeyPrefixLen], i.key[:currKeyPrefixLen]) {
1825 1 : i.internalNextPrefix(currKeyPrefixLen)
1826 1 : }
1827 : }
1828 : }
1829 :
1830 1 : i.stats.ForwardStepCount[InterfaceCall]++
1831 1 : i.findNextEntry(nil /* limit */)
1832 1 : i.maybeSampleRead()
1833 1 : return i.iterValidityState
1834 : }
1835 :
1836 1 : func (i *Iterator) internalNextPrefix(currKeyPrefixLen int) {
1837 1 : if i.iterKey == nil {
1838 1 : return
1839 1 : }
1840 : // The Next "fast-path" is not really a fast-path when there is more than
1841 : // one version. However, even with TableFormatPebblev3, there is a small
1842 : // slowdown (~10%) for one version if we remove it and only call NextPrefix.
1843 : // When there are two versions, only calling NextPrefix is ~30% faster.
1844 1 : i.stats.ForwardStepCount[InternalIterCall]++
1845 1 : if i.iterKey, i.iterValue = i.iter.Next(); i.iterKey == nil {
1846 1 : return
1847 1 : }
1848 1 : iterKeyPrefixLen := i.split(i.iterKey.UserKey)
1849 1 : if !bytes.Equal(i.iterKey.UserKey[:iterKeyPrefixLen], i.key[:currKeyPrefixLen]) {
1850 1 : return
1851 1 : }
1852 1 : i.stats.ForwardStepCount[InternalIterCall]++
1853 1 : i.prefixOrFullSeekKey = i.comparer.ImmediateSuccessor(i.prefixOrFullSeekKey[:0], i.key[:currKeyPrefixLen])
1854 1 : i.iterKey, i.iterValue = i.iter.NextPrefix(i.prefixOrFullSeekKey)
1855 1 : if invariants.Enabled && i.iterKey != nil {
1856 1 : if iterKeyPrefixLen := i.split(i.iterKey.UserKey); i.cmp(i.iterKey.UserKey[:iterKeyPrefixLen], i.prefixOrFullSeekKey) < 0 {
1857 0 : panic(errors.AssertionFailedf("pebble: iter.NextPrefix did not advance beyond the current prefix: now at %q; expected to be geq %q",
1858 0 : i.iterKey, i.prefixOrFullSeekKey))
1859 : }
1860 : }
1861 : }
1862 :
1863 1 : func (i *Iterator) nextWithLimit(limit []byte) IterValidityState {
1864 1 : i.stats.ForwardStepCount[InterfaceCall]++
1865 1 : if i.hasPrefix {
1866 1 : if limit != nil {
1867 1 : i.err = errors.New("cannot use limit with prefix iteration")
1868 1 : i.iterValidityState = IterExhausted
1869 1 : return i.iterValidityState
1870 1 : } else if i.iterValidityState == IterExhausted {
1871 1 : // No-op, already exhausted. We avoid executing the Next because it
1872 1 : // can break invariants: Specifically, a file that fails the bloom
1873 1 : // filter test may result in its level being removed from the
1874 1 : // merging iterator. The level's removal can cause a lazy combined
1875 1 : // iterator to miss range keys and trigger a switch to combined
1876 1 : // iteration at a larger key, breaking keyspan invariants.
1877 1 : return i.iterValidityState
1878 1 : }
1879 : }
1880 1 : if i.err != nil {
1881 1 : return i.iterValidityState
1882 1 : }
1883 1 : if i.rangeKey != nil {
1884 1 : // NB: Check Valid() before clearing requiresReposition.
1885 1 : i.rangeKey.prevPosHadRangeKey = i.rangeKey.hasRangeKey && i.Valid()
1886 1 : // If we have a range key but did not expose it at the previous iterator
1887 1 : // position (because the iterator was not at a valid position), updated
1888 1 : // must be true. This ensures that after an iterator op sequence like:
1889 1 : // - Next() → (IterValid, RangeBounds() = [a,b))
1890 1 : // - NextWithLimit(...) → (IterAtLimit, RangeBounds() = -)
1891 1 : // - NextWithLimit(...) → (IterValid, RangeBounds() = [a,b))
1892 1 : // the iterator returns RangeKeyChanged()=true.
1893 1 : //
1894 1 : // The remainder of this function will only update i.rangeKey.updated if
1895 1 : // the iterator moves into a new range key, or out of the current range
1896 1 : // key.
1897 1 : i.rangeKey.updated = i.rangeKey.hasRangeKey && !i.Valid() && i.opts.rangeKeys()
1898 1 : }
1899 1 : i.lastPositioningOp = unknownLastPositionOp
1900 1 : i.requiresReposition = false
1901 1 : switch i.pos {
1902 1 : case iterPosCurForward:
1903 1 : i.nextUserKey()
1904 1 : case iterPosCurForwardPaused:
1905 : // Already at the right place.
1906 1 : case iterPosCurReverse:
1907 1 : // Switching directions.
1908 1 : // Unless the iterator was exhausted, reverse iteration needs to
1909 1 : // position the iterator at iterPosPrev.
1910 1 : if i.iterKey != nil {
1911 0 : i.err = errors.New("switching from reverse to forward but iter is not at prev")
1912 0 : i.iterValidityState = IterExhausted
1913 0 : return i.iterValidityState
1914 0 : }
1915 : // We're positioned before the first key. Need to reposition to point to
1916 : // the first key.
1917 1 : i.iterFirstWithinBounds()
1918 1 : case iterPosCurReversePaused:
1919 1 : // Switching directions.
1920 1 : // The iterator must not be exhausted since it paused.
1921 1 : if i.iterKey == nil {
1922 0 : i.err = errors.New("switching paused from reverse to forward but iter is exhausted")
1923 0 : i.iterValidityState = IterExhausted
1924 0 : return i.iterValidityState
1925 0 : }
1926 1 : i.nextUserKey()
1927 1 : case iterPosPrev:
1928 1 : // The underlying iterator is pointed to the previous key (this can
1929 1 : // only happen when switching iteration directions). We set
1930 1 : // i.iterValidityState to IterExhausted here to force the calls to
1931 1 : // nextUserKey to save the current key i.iter is pointing at in order
1932 1 : // to determine when the next user-key is reached.
1933 1 : i.iterValidityState = IterExhausted
1934 1 : if i.iterKey == nil {
1935 1 : // We're positioned before the first key. Need to reposition to point to
1936 1 : // the first key.
1937 1 : i.iterFirstWithinBounds()
1938 1 : } else {
1939 1 : i.nextUserKey()
1940 1 : }
1941 1 : i.nextUserKey()
1942 1 : case iterPosNext:
1943 : // Already at the right place.
1944 : }
1945 1 : i.findNextEntry(limit)
1946 1 : i.maybeSampleRead()
1947 1 : return i.iterValidityState
1948 : }
1949 :
1950 : // Prev moves the iterator to the previous key/value pair. Returns true if the
1951 : // iterator is pointing at a valid entry and false otherwise.
1952 1 : func (i *Iterator) Prev() bool {
1953 1 : return i.PrevWithLimit(nil) == IterValid
1954 1 : }
1955 :
1956 : // PrevWithLimit moves the iterator to the previous key/value pair.
1957 : //
1958 : // If limit is provided, it serves as a best-effort inclusive limit. If the
1959 : // previous key is less than limit, the Iterator may pause and return
1960 : // IterAtLimit. Because limits are best-effort, PrevWithLimit may return a key
1961 : // beyond limit.
1962 : //
1963 : // If the Iterator is configured to iterate over range keys, PrevWithLimit
1964 : // guarantees it will surface any range keys with bounds overlapping the
1965 : // keyspace up to limit.
1966 1 : func (i *Iterator) PrevWithLimit(limit []byte) IterValidityState {
1967 1 : i.stats.ReverseStepCount[InterfaceCall]++
1968 1 : if i.err != nil {
1969 1 : return i.iterValidityState
1970 1 : }
1971 1 : if i.rangeKey != nil {
1972 1 : // NB: Check Valid() before clearing requiresReposition.
1973 1 : i.rangeKey.prevPosHadRangeKey = i.rangeKey.hasRangeKey && i.Valid()
1974 1 : // If we have a range key but did not expose it at the previous iterator
1975 1 : // position (because the iterator was not at a valid position), updated
1976 1 : // must be true. This ensures that after an iterator op sequence like:
1977 1 : // - Next() → (IterValid, RangeBounds() = [a,b))
1978 1 : // - NextWithLimit(...) → (IterAtLimit, RangeBounds() = -)
1979 1 : // - PrevWithLimit(...) → (IterValid, RangeBounds() = [a,b))
1980 1 : // the iterator returns RangeKeyChanged()=true.
1981 1 : //
1982 1 : // The remainder of this function will only update i.rangeKey.updated if
1983 1 : // the iterator moves into a new range key, or out of the current range
1984 1 : // key.
1985 1 : i.rangeKey.updated = i.rangeKey.hasRangeKey && !i.Valid() && i.opts.rangeKeys()
1986 1 : }
1987 1 : i.lastPositioningOp = unknownLastPositionOp
1988 1 : i.requiresReposition = false
1989 1 : if i.hasPrefix {
1990 1 : i.err = errReversePrefixIteration
1991 1 : i.iterValidityState = IterExhausted
1992 1 : return i.iterValidityState
1993 1 : }
1994 1 : switch i.pos {
1995 1 : case iterPosCurForward:
1996 : // Switching directions, and will handle this below.
1997 1 : case iterPosCurForwardPaused:
1998 : // Switching directions, and will handle this below.
1999 1 : case iterPosCurReverse:
2000 1 : i.prevUserKey()
2001 1 : case iterPosCurReversePaused:
2002 : // Already at the right place.
2003 1 : case iterPosNext:
2004 : // The underlying iterator is pointed to the next key (this can only happen
2005 : // when switching iteration directions). We will handle this below.
2006 1 : case iterPosPrev:
2007 : // Already at the right place.
2008 : }
2009 1 : if i.pos == iterPosCurForward || i.pos == iterPosNext || i.pos == iterPosCurForwardPaused {
2010 1 : // Switching direction.
2011 1 : stepAgain := i.pos == iterPosNext
2012 1 :
2013 1 : // Synthetic range key markers are a special case. Consider SeekGE(b)
2014 1 : // which finds a range key [a, c). To ensure the user observes the range
2015 1 : // key, the Iterator pauses at Key() = b. The iterator must advance the
2016 1 : // internal iterator to see if there's also a coincident point key at
2017 1 : // 'b', leaving the iterator at iterPosNext if there's not.
2018 1 : //
2019 1 : // This is a problem: Synthetic range key markers are only interleaved
2020 1 : // during the original seek. A subsequent Prev() of i.iter will not move
2021 1 : // back onto the synthetic range key marker. In this case where the
2022 1 : // previous iterator position was a synthetic range key start boundary,
2023 1 : // we must not step a second time.
2024 1 : if i.isEphemeralPosition() {
2025 1 : stepAgain = false
2026 1 : }
2027 :
2028 : // We set i.iterValidityState to IterExhausted here to force the calls
2029 : // to prevUserKey to save the current key i.iter is pointing at in
2030 : // order to determine when the prev user-key is reached.
2031 1 : i.iterValidityState = IterExhausted
2032 1 : if i.iterKey == nil {
2033 1 : // We're positioned after the last key. Need to reposition to point to
2034 1 : // the last key.
2035 1 : i.iterLastWithinBounds()
2036 1 : } else {
2037 1 : i.prevUserKey()
2038 1 : if i.err != nil {
2039 0 : return i.iterValidityState
2040 0 : }
2041 : }
2042 1 : if stepAgain {
2043 1 : i.prevUserKey()
2044 1 : if i.err != nil {
2045 0 : return i.iterValidityState
2046 0 : }
2047 : }
2048 : }
2049 1 : i.findPrevEntry(limit)
2050 1 : i.maybeSampleRead()
2051 1 : return i.iterValidityState
2052 : }
2053 :
2054 : // iterFirstWithinBounds moves the internal iterator to the first key,
2055 : // respecting bounds.
2056 1 : func (i *Iterator) iterFirstWithinBounds() {
2057 1 : i.stats.ForwardSeekCount[InternalIterCall]++
2058 1 : if lowerBound := i.opts.GetLowerBound(); lowerBound != nil {
2059 1 : i.iterKey, i.iterValue = i.iter.SeekGE(lowerBound, base.SeekGEFlagsNone)
2060 1 : } else {
2061 1 : i.iterKey, i.iterValue = i.iter.First()
2062 1 : }
2063 : }
2064 :
2065 : // iterLastWithinBounds moves the internal iterator to the last key, respecting
2066 : // bounds.
2067 1 : func (i *Iterator) iterLastWithinBounds() {
2068 1 : i.stats.ReverseSeekCount[InternalIterCall]++
2069 1 : if upperBound := i.opts.GetUpperBound(); upperBound != nil {
2070 1 : i.iterKey, i.iterValue = i.iter.SeekLT(upperBound, base.SeekLTFlagsNone)
2071 1 : } else {
2072 1 : i.iterKey, i.iterValue = i.iter.Last()
2073 1 : }
2074 : }
2075 :
2076 : // RangeKeyData describes a range key's data, set through RangeKeySet. The key
2077 : // boundaries of the range key is provided by Iterator.RangeBounds.
2078 : type RangeKeyData struct {
2079 : Suffix []byte
2080 : Value []byte
2081 : }
2082 :
2083 : // rangeKeyWithinLimit is called during limited reverse iteration when
2084 : // positioned over a key beyond the limit. If there exists a range key that lies
2085 : // within the limit, the iterator must not pause in order to ensure the user has
2086 : // an opportunity to observe the range key within limit.
2087 : //
2088 : // It would be valid to ignore the limit whenever there's a range key covering
2089 : // the key, but that would introduce nondeterminism. To preserve determinism for
2090 : // testing, the iterator ignores the limit only if the covering range key does
2091 : // cover the keyspace within the limit.
2092 : //
2093 : // This awkwardness exists because range keys are interleaved at their inclusive
2094 : // start positions. Note that limit is inclusive.
2095 1 : func (i *Iterator) rangeKeyWithinLimit(limit []byte) bool {
2096 1 : if i.rangeKey == nil || !i.opts.rangeKeys() {
2097 1 : return false
2098 1 : }
2099 1 : s := i.rangeKey.iiter.Span()
2100 1 : // If the range key ends beyond the limit, then the range key does not cover
2101 1 : // any portion of the keyspace within the limit and it is safe to pause.
2102 1 : return s != nil && i.cmp(s.End, limit) > 0
2103 : }
2104 :
2105 : // saveRangeKey saves the current range key to the underlying iterator's current
2106 : // range key state. If the range key has not changed, saveRangeKey is a no-op.
2107 : // If there is a new range key, saveRangeKey copies all of the key, value and
2108 : // suffixes into Iterator-managed buffers.
2109 1 : func (i *Iterator) saveRangeKey() {
2110 1 : if i.rangeKey == nil || i.opts.KeyTypes == IterKeyTypePointsOnly {
2111 1 : return
2112 1 : }
2113 :
2114 1 : s := i.rangeKey.iiter.Span()
2115 1 : if s == nil {
2116 1 : i.rangeKey.hasRangeKey = false
2117 1 : i.rangeKey.updated = i.rangeKey.prevPosHadRangeKey
2118 1 : return
2119 1 : } else if !i.rangeKey.stale {
2120 1 : // The range key `s` is identical to the one currently saved. No-op.
2121 1 : return
2122 1 : }
2123 :
2124 1 : if s.KeysOrder != keyspan.BySuffixAsc {
2125 0 : panic("pebble: range key span's keys unexpectedly not in ascending suffix order")
2126 : }
2127 :
2128 : // Although `i.rangeKey.stale` is true, the span s may still be identical
2129 : // to the currently saved span. This is possible when seeking the iterator,
2130 : // which may land back on the same range key. If we previously had a range
2131 : // key and the new one has an identical start key, then it must be the same
2132 : // range key and we can avoid copying and keep `i.rangeKey.updated=false`.
2133 : //
2134 : // TODO(jackson): These key comparisons could be avoidable during relative
2135 : // positioning operations continuing in the same direction, because these
2136 : // ops will never encounter the previous position's range key while
2137 : // stale=true. However, threading whether the current op is a seek or step
2138 : // maybe isn't worth it. This key comparison is only necessary once when we
2139 : // step onto a new range key, which should be relatively rare.
2140 1 : if i.rangeKey.prevPosHadRangeKey && i.equal(i.rangeKey.start, s.Start) &&
2141 1 : i.equal(i.rangeKey.end, s.End) {
2142 1 : i.rangeKey.updated = false
2143 1 : i.rangeKey.stale = false
2144 1 : i.rangeKey.hasRangeKey = true
2145 1 : return
2146 1 : }
2147 1 : i.stats.RangeKeyStats.Count += len(s.Keys)
2148 1 : i.rangeKey.buf.Reset()
2149 1 : i.rangeKey.hasRangeKey = true
2150 1 : i.rangeKey.updated = true
2151 1 : i.rangeKey.stale = false
2152 1 : i.rangeKey.buf, i.rangeKey.start = i.rangeKey.buf.Copy(s.Start)
2153 1 : i.rangeKey.buf, i.rangeKey.end = i.rangeKey.buf.Copy(s.End)
2154 1 : i.rangeKey.keys = i.rangeKey.keys[:0]
2155 1 : for j := 0; j < len(s.Keys); j++ {
2156 1 : if invariants.Enabled {
2157 1 : if s.Keys[j].Kind() != base.InternalKeyKindRangeKeySet {
2158 0 : panic("pebble: user iteration encountered non-RangeKeySet key kind")
2159 1 : } else if j > 0 && i.cmp(s.Keys[j].Suffix, s.Keys[j-1].Suffix) < 0 {
2160 0 : panic("pebble: user iteration encountered range keys not in suffix order")
2161 : }
2162 : }
2163 1 : var rkd RangeKeyData
2164 1 : i.rangeKey.buf, rkd.Suffix = i.rangeKey.buf.Copy(s.Keys[j].Suffix)
2165 1 : i.rangeKey.buf, rkd.Value = i.rangeKey.buf.Copy(s.Keys[j].Value)
2166 1 : i.rangeKey.keys = append(i.rangeKey.keys, rkd)
2167 : }
2168 : }
2169 :
2170 : // RangeKeyChanged indicates whether the most recent iterator positioning
2171 : // operation resulted in the iterator stepping into or out of a new range key.
2172 : // If true, previously returned range key bounds and data has been invalidated.
2173 : // If false, previously obtained range key bounds, suffix and value slices are
2174 : // still valid and may continue to be read.
2175 : //
2176 : // Invalid iterator positions are considered to not hold range keys, meaning
2177 : // that if an iterator steps from an IterExhausted or IterAtLimit position onto
2178 : // a position with a range key, RangeKeyChanged will yield true.
2179 1 : func (i *Iterator) RangeKeyChanged() bool {
2180 1 : return i.iterValidityState == IterValid && i.rangeKey != nil && i.rangeKey.updated
2181 1 : }
2182 :
2183 : // HasPointAndRange indicates whether there exists a point key, a range key or
2184 : // both at the current iterator position.
2185 1 : func (i *Iterator) HasPointAndRange() (hasPoint, hasRange bool) {
2186 1 : if i.iterValidityState != IterValid || i.requiresReposition {
2187 1 : return false, false
2188 1 : }
2189 1 : if i.opts.KeyTypes == IterKeyTypePointsOnly {
2190 1 : return true, false
2191 1 : }
2192 1 : return i.rangeKey == nil || !i.rangeKey.rangeKeyOnly, i.rangeKey != nil && i.rangeKey.hasRangeKey
2193 : }
2194 :
2195 : // RangeBounds returns the start (inclusive) and end (exclusive) bounds of the
2196 : // range key covering the current iterator position. RangeBounds returns nil
2197 : // bounds if there is no range key covering the current iterator position, or
2198 : // the iterator is not configured to surface range keys.
2199 : //
2200 : // If valid, the returned start bound is less than or equal to Key() and the
2201 : // returned end bound is greater than Key().
2202 1 : func (i *Iterator) RangeBounds() (start, end []byte) {
2203 1 : if i.rangeKey == nil || !i.opts.rangeKeys() || !i.rangeKey.hasRangeKey {
2204 0 : return nil, nil
2205 0 : }
2206 1 : return i.rangeKey.start, i.rangeKey.end
2207 : }
2208 :
2209 : // Key returns the key of the current key/value pair, or nil if done. The
2210 : // caller should not modify the contents of the returned slice, and its
2211 : // contents may change on the next call to Next.
2212 : //
2213 : // If positioned at an iterator position that only holds a range key, Key()
2214 : // always returns the start bound of the range key. Otherwise, it returns the
2215 : // point key's key.
2216 1 : func (i *Iterator) Key() []byte {
2217 1 : return i.key
2218 1 : }
2219 :
2220 : // Value returns the value of the current key/value pair, or nil if done. The
2221 : // caller should not modify the contents of the returned slice, and its
2222 : // contents may change on the next call to Next.
2223 : //
2224 : // Only valid if HasPointAndRange() returns true for hasPoint.
2225 : // Deprecated: use ValueAndErr instead.
2226 1 : func (i *Iterator) Value() []byte {
2227 1 : val, _ := i.ValueAndErr()
2228 1 : return val
2229 1 : }
2230 :
2231 : // ValueAndErr returns the value, and any error encountered in extracting the value.
2232 : // REQUIRES: i.Error()==nil and HasPointAndRange() returns true for hasPoint.
2233 : //
2234 : // The caller should not modify the contents of the returned slice, and its
2235 : // contents may change on the next call to Next.
2236 1 : func (i *Iterator) ValueAndErr() ([]byte, error) {
2237 1 : val, callerOwned, err := i.value.Value(i.lazyValueBuf)
2238 1 : if err != nil {
2239 0 : i.err = err
2240 0 : i.iterValidityState = IterExhausted
2241 0 : }
2242 1 : if callerOwned {
2243 1 : i.lazyValueBuf = val[:0]
2244 1 : }
2245 1 : return val, err
2246 : }
2247 :
2248 : // LazyValue returns the LazyValue. Only for advanced use cases.
2249 : // REQUIRES: i.Error()==nil and HasPointAndRange() returns true for hasPoint.
2250 0 : func (i *Iterator) LazyValue() LazyValue {
2251 0 : return i.value
2252 0 : }
2253 :
2254 : // RangeKeys returns the range key values and their suffixes covering the
2255 : // current iterator position. The range bounds may be retrieved separately
2256 : // through Iterator.RangeBounds().
2257 1 : func (i *Iterator) RangeKeys() []RangeKeyData {
2258 1 : if i.rangeKey == nil || !i.opts.rangeKeys() || !i.rangeKey.hasRangeKey {
2259 0 : return nil
2260 0 : }
2261 1 : return i.rangeKey.keys
2262 : }
2263 :
2264 : // Valid returns true if the iterator is positioned at a valid key/value pair
2265 : // and false otherwise.
2266 1 : func (i *Iterator) Valid() bool {
2267 1 : valid := i.iterValidityState == IterValid && !i.requiresReposition
2268 1 : if invariants.Enabled {
2269 1 : if err := i.Error(); valid && err != nil {
2270 0 : panic(errors.AssertionFailedf("pebble: iterator is valid with non-nil Error: %+v", err))
2271 : }
2272 : }
2273 1 : return valid
2274 : }
2275 :
2276 : // Error returns any accumulated error.
2277 1 : func (i *Iterator) Error() error {
2278 1 : if i.err != nil {
2279 1 : return i.err
2280 1 : }
2281 1 : if i.iter != nil {
2282 1 : return i.iter.Error()
2283 1 : }
2284 0 : return nil
2285 : }
2286 :
2287 : const maxKeyBufCacheSize = 4 << 10 // 4 KB
2288 :
2289 : // Close closes the iterator and returns any accumulated error. Exhausting
2290 : // all the key/value pairs in a table is not considered to be an error.
2291 : // It is not valid to call any method, including Close, after the iterator
2292 : // has been closed.
2293 1 : func (i *Iterator) Close() error {
2294 1 : // Close the child iterator before releasing the readState because when the
2295 1 : // readState is released sstables referenced by the readState may be deleted
2296 1 : // which will fail on Windows if the sstables are still open by the child
2297 1 : // iterator.
2298 1 : if i.iter != nil {
2299 1 : i.err = firstError(i.err, i.iter.Close())
2300 1 :
2301 1 : // Closing i.iter did not necessarily close the point and range key
2302 1 : // iterators. Calls to SetOptions may have 'disconnected' either one
2303 1 : // from i.iter if iteration key types were changed. Both point and range
2304 1 : // key iterators are preserved in case the iterator needs to switch key
2305 1 : // types again. We explicitly close both of these iterators here.
2306 1 : //
2307 1 : // NB: If the iterators were still connected to i.iter, they may be
2308 1 : // closed, but calling Close on a closed internal iterator or fragment
2309 1 : // iterator is allowed.
2310 1 : if i.pointIter != nil {
2311 1 : i.err = firstError(i.err, i.pointIter.Close())
2312 1 : }
2313 1 : if i.rangeKey != nil && i.rangeKey.rangeKeyIter != nil {
2314 1 : i.err = firstError(i.err, i.rangeKey.rangeKeyIter.Close())
2315 1 : }
2316 : }
2317 1 : err := i.err
2318 1 :
2319 1 : if i.readState != nil {
2320 1 : if i.readSampling.pendingCompactions.size > 0 {
2321 1 : // Copy pending read compactions using db.mu.Lock()
2322 1 : i.readState.db.mu.Lock()
2323 1 : i.readState.db.mu.compact.readCompactions.combine(&i.readSampling.pendingCompactions, i.cmp)
2324 1 : reschedule := i.readState.db.mu.compact.rescheduleReadCompaction
2325 1 : i.readState.db.mu.compact.rescheduleReadCompaction = false
2326 1 : concurrentCompactions := i.readState.db.mu.compact.compactingCount
2327 1 : i.readState.db.mu.Unlock()
2328 1 :
2329 1 : if reschedule && concurrentCompactions == 0 {
2330 0 : // In a read heavy workload, flushes may not happen frequently enough to
2331 0 : // schedule compactions.
2332 0 : i.readState.db.compactionSchedulers.Add(1)
2333 0 : go i.readState.db.maybeScheduleCompactionAsync()
2334 0 : }
2335 : }
2336 :
2337 1 : i.readState.unref()
2338 1 : i.readState = nil
2339 : }
2340 :
2341 1 : if i.version != nil {
2342 1 : i.version.Unref()
2343 1 : }
2344 :
2345 1 : for _, readers := range i.externalReaders {
2346 1 : for _, r := range readers {
2347 1 : err = firstError(err, r.Close())
2348 1 : }
2349 : }
2350 :
2351 : // Close the closer for the current value if one was open.
2352 1 : if i.valueCloser != nil {
2353 1 : err = firstError(err, i.valueCloser.Close())
2354 1 : i.valueCloser = nil
2355 1 : }
2356 :
2357 1 : if i.rangeKey != nil {
2358 1 :
2359 1 : i.rangeKey.rangeKeyBuffers.PrepareForReuse()
2360 1 : *i.rangeKey = iteratorRangeKeyState{
2361 1 : rangeKeyBuffers: i.rangeKey.rangeKeyBuffers,
2362 1 : }
2363 1 : iterRangeKeyStateAllocPool.Put(i.rangeKey)
2364 1 : i.rangeKey = nil
2365 1 : }
2366 1 : if alloc := i.alloc; alloc != nil {
2367 1 : // Avoid caching the key buf if it is overly large. The constant is fairly
2368 1 : // arbitrary.
2369 1 : if cap(i.keyBuf) >= maxKeyBufCacheSize {
2370 0 : alloc.keyBuf = nil
2371 1 : } else {
2372 1 : alloc.keyBuf = i.keyBuf
2373 1 : }
2374 1 : if cap(i.prefixOrFullSeekKey) >= maxKeyBufCacheSize {
2375 0 : alloc.prefixOrFullSeekKey = nil
2376 1 : } else {
2377 1 : alloc.prefixOrFullSeekKey = i.prefixOrFullSeekKey
2378 1 : }
2379 1 : for j := range i.boundsBuf {
2380 1 : if cap(i.boundsBuf[j]) >= maxKeyBufCacheSize {
2381 0 : alloc.boundsBuf[j] = nil
2382 1 : } else {
2383 1 : alloc.boundsBuf[j] = i.boundsBuf[j]
2384 1 : }
2385 : }
2386 1 : *alloc = iterAlloc{
2387 1 : keyBuf: alloc.keyBuf,
2388 1 : boundsBuf: alloc.boundsBuf,
2389 1 : prefixOrFullSeekKey: alloc.prefixOrFullSeekKey,
2390 1 : }
2391 1 : iterAllocPool.Put(alloc)
2392 1 : } else if alloc := i.getIterAlloc; alloc != nil {
2393 1 : if cap(i.keyBuf) >= maxKeyBufCacheSize {
2394 0 : alloc.keyBuf = nil
2395 1 : } else {
2396 1 : alloc.keyBuf = i.keyBuf
2397 1 : }
2398 1 : *alloc = getIterAlloc{
2399 1 : keyBuf: alloc.keyBuf,
2400 1 : }
2401 1 : getIterAllocPool.Put(alloc)
2402 : }
2403 1 : return err
2404 : }
2405 :
2406 : // SetBounds sets the lower and upper bounds for the iterator. Once SetBounds
2407 : // returns, the caller is free to mutate the provided slices.
2408 : //
2409 : // The iterator will always be invalidated and must be repositioned with a call
2410 : // to SeekGE, SeekPrefixGE, SeekLT, First, or Last.
2411 1 : func (i *Iterator) SetBounds(lower, upper []byte) {
2412 1 : // Ensure that the Iterator appears exhausted, regardless of whether we
2413 1 : // actually have to invalidate the internal iterator. Optimizations that
2414 1 : // avoid exhaustion are an internal implementation detail that shouldn't
2415 1 : // leak through the interface. The caller should still call an absolute
2416 1 : // positioning method to reposition the iterator.
2417 1 : i.requiresReposition = true
2418 1 :
2419 1 : if ((i.opts.LowerBound == nil) == (lower == nil)) &&
2420 1 : ((i.opts.UpperBound == nil) == (upper == nil)) &&
2421 1 : i.equal(i.opts.LowerBound, lower) &&
2422 1 : i.equal(i.opts.UpperBound, upper) {
2423 1 : // Unchanged, noop.
2424 1 : return
2425 1 : }
2426 :
2427 : // Copy the user-provided bounds into an Iterator-owned buffer, and set them
2428 : // on i.opts.{Lower,Upper}Bound.
2429 1 : i.processBounds(lower, upper)
2430 1 :
2431 1 : i.iter.SetBounds(i.opts.LowerBound, i.opts.UpperBound)
2432 1 : // If the iterator has an open point iterator that's not currently being
2433 1 : // used, propagate the new bounds to it.
2434 1 : if i.pointIter != nil && !i.opts.pointKeys() {
2435 1 : i.pointIter.SetBounds(i.opts.LowerBound, i.opts.UpperBound)
2436 1 : }
2437 : // If the iterator has a range key iterator, propagate bounds to it. The
2438 : // top-level SetBounds on the interleaving iterator (i.iter) won't propagate
2439 : // bounds to the range key iterator stack, because the FragmentIterator
2440 : // interface doesn't define a SetBounds method. We need to directly inform
2441 : // the iterConfig stack.
2442 1 : if i.rangeKey != nil {
2443 1 : i.rangeKey.iterConfig.SetBounds(i.opts.LowerBound, i.opts.UpperBound)
2444 1 : }
2445 :
2446 : // Even though this is not a positioning operation, the alteration of the
2447 : // bounds means we cannot optimize Seeks by using Next.
2448 1 : i.invalidate()
2449 : }
2450 :
2451 : // SetContext replaces the context provided at iterator creation, or the last
2452 : // one provided by SetContext. Even though iterators are expected to be
2453 : // short-lived, there are some cases where either (a) iterators are used far
2454 : // from the code that created them, (b) iterators are reused (while being
2455 : // short-lived) for processing different requests. For such scenarios, we
2456 : // allow the caller to replace the context.
2457 0 : func (i *Iterator) SetContext(ctx context.Context) {
2458 0 : i.ctx = ctx
2459 0 : i.iter.SetContext(ctx)
2460 0 : // If the iterator has an open point iterator that's not currently being
2461 0 : // used, propagate the new context to it.
2462 0 : if i.pointIter != nil && !i.opts.pointKeys() {
2463 0 : i.pointIter.SetContext(i.ctx)
2464 0 : }
2465 : }
2466 :
2467 : // Initialization and changing of the bounds must call processBounds.
2468 : // processBounds saves the bounds and computes derived state from those
2469 : // bounds.
2470 1 : func (i *Iterator) processBounds(lower, upper []byte) {
2471 1 : // Copy the user-provided bounds into an Iterator-owned buffer. We can't
2472 1 : // overwrite the current bounds, because some internal iterators compare old
2473 1 : // and new bounds for optimizations.
2474 1 :
2475 1 : buf := i.boundsBuf[i.boundsBufIdx][:0]
2476 1 : if lower != nil {
2477 1 : buf = append(buf, lower...)
2478 1 : i.opts.LowerBound = buf
2479 1 : } else {
2480 1 : i.opts.LowerBound = nil
2481 1 : }
2482 1 : i.nextPrefixNotPermittedByUpperBound = false
2483 1 : if upper != nil {
2484 1 : buf = append(buf, upper...)
2485 1 : i.opts.UpperBound = buf[len(buf)-len(upper):]
2486 1 : if i.comparer.Split(i.opts.UpperBound) != len(i.opts.UpperBound) {
2487 1 : // Setting an upper bound that is a versioned MVCC key. This means
2488 1 : // that a key can have some MVCC versions before the upper bound and
2489 1 : // some after. This causes significant complications for NextPrefix,
2490 1 : // so we bar the user of NextPrefix.
2491 1 : i.nextPrefixNotPermittedByUpperBound = true
2492 1 : }
2493 1 : } else {
2494 1 : i.opts.UpperBound = nil
2495 1 : }
2496 1 : i.boundsBuf[i.boundsBufIdx] = buf
2497 1 : i.boundsBufIdx = 1 - i.boundsBufIdx
2498 : }
2499 :
2500 : // SetOptions sets new iterator options for the iterator. Note that the lower
2501 : // and upper bounds applied here will supersede any bounds set by previous calls
2502 : // to SetBounds.
2503 : //
2504 : // Note that the slices provided in this SetOptions must not be changed by the
2505 : // caller until the iterator is closed, or a subsequent SetBounds or SetOptions
2506 : // has returned. This is because comparisons between the existing and new bounds
2507 : // are sometimes used to optimize seeking. See the extended commentary on
2508 : // SetBounds.
2509 : //
2510 : // If the iterator was created over an indexed mutable batch, the iterator's
2511 : // view of the mutable batch is refreshed.
2512 : //
2513 : // The iterator will always be invalidated and must be repositioned with a call
2514 : // to SeekGE, SeekPrefixGE, SeekLT, First, or Last.
2515 : //
2516 : // If only lower and upper bounds need to be modified, prefer SetBounds.
2517 1 : func (i *Iterator) SetOptions(o *IterOptions) {
2518 1 : if i.externalReaders != nil {
2519 1 : if err := validateExternalIterOpts(o); err != nil {
2520 0 : panic(err)
2521 : }
2522 : }
2523 :
2524 : // Ensure that the Iterator appears exhausted, regardless of whether we
2525 : // actually have to invalidate the internal iterator. Optimizations that
2526 : // avoid exhaustion are an internal implementation detail that shouldn't
2527 : // leak through the interface. The caller should still call an absolute
2528 : // positioning method to reposition the iterator.
2529 1 : i.requiresReposition = true
2530 1 :
2531 1 : // Check if global state requires we close all internal iterators.
2532 1 : //
2533 1 : // If the Iterator is in an error state, invalidate the existing iterators
2534 1 : // so that we reconstruct an iterator state from scratch.
2535 1 : //
2536 1 : // If OnlyReadGuaranteedDurable changed, the iterator stacks are incorrect,
2537 1 : // improperly including or excluding memtables. Invalidate them so that
2538 1 : // finishInitializingIter will reconstruct them.
2539 1 : //
2540 1 : // If either the original options or the new options specify a table filter,
2541 1 : // we need to reconstruct the iterator stacks. If they both supply a table
2542 1 : // filter, we can't be certain that it's the same filter since we have no
2543 1 : // mechanism to compare the filter closures.
2544 1 : closeBoth := i.err != nil ||
2545 1 : o.OnlyReadGuaranteedDurable != i.opts.OnlyReadGuaranteedDurable ||
2546 1 : o.TableFilter != nil || i.opts.TableFilter != nil
2547 1 :
2548 1 : // If either options specify block property filters for an iterator stack,
2549 1 : // reconstruct it.
2550 1 : if i.pointIter != nil && (closeBoth || len(o.PointKeyFilters) > 0 || len(i.opts.PointKeyFilters) > 0 ||
2551 1 : o.RangeKeyMasking.Filter != nil || i.opts.RangeKeyMasking.Filter != nil || o.SkipPoint != nil ||
2552 1 : i.opts.SkipPoint != nil) {
2553 1 : i.err = firstError(i.err, i.pointIter.Close())
2554 1 : i.pointIter = nil
2555 1 : }
2556 1 : if i.rangeKey != nil {
2557 1 : if closeBoth || len(o.RangeKeyFilters) > 0 || len(i.opts.RangeKeyFilters) > 0 {
2558 1 : i.err = firstError(i.err, i.rangeKey.rangeKeyIter.Close())
2559 1 : i.rangeKey = nil
2560 1 : } else {
2561 1 : // If there's still a range key iterator stack, invalidate the
2562 1 : // iterator. This ensures RangeKeyChanged() returns true if a
2563 1 : // subsequent positioning operation discovers a range key. It also
2564 1 : // prevents seek no-op optimizations.
2565 1 : i.invalidate()
2566 1 : }
2567 : }
2568 :
2569 : // If the iterator is backed by a batch that's been mutated, refresh its
2570 : // existing point and range-key iterators, and invalidate the iterator to
2571 : // prevent seek-using-next optimizations. If we don't yet have a point-key
2572 : // iterator or range-key iterator but we require one, it'll be created in
2573 : // the slow path that reconstructs the iterator in finishInitializingIter.
2574 1 : if i.batch != nil {
2575 1 : nextBatchSeqNum := (uint64(len(i.batch.data)) | base.InternalKeySeqNumBatch)
2576 1 : if nextBatchSeqNum != i.batchSeqNum {
2577 1 : i.batchSeqNum = nextBatchSeqNum
2578 1 : if i.merging != nil {
2579 1 : i.merging.batchSnapshot = nextBatchSeqNum
2580 1 : }
2581 : // Prevent a no-op seek optimization on the next seek. We won't be
2582 : // able to reuse the top-level Iterator state, because it may be
2583 : // incorrect after the inclusion of new batch mutations.
2584 1 : i.batchJustRefreshed = true
2585 1 : if i.pointIter != nil && i.batch.countRangeDels > 0 {
2586 1 : if i.batchRangeDelIter.Count() == 0 {
2587 1 : // When we constructed this iterator, there were no
2588 1 : // rangedels in the batch. Iterator construction will
2589 1 : // have excluded the batch rangedel iterator from the
2590 1 : // point iterator stack. We need to reconstruct the
2591 1 : // point iterator to add i.batchRangeDelIter into the
2592 1 : // iterator stack.
2593 1 : i.err = firstError(i.err, i.pointIter.Close())
2594 1 : i.pointIter = nil
2595 1 : } else {
2596 1 : // There are range deletions in the batch and we already
2597 1 : // have a batch rangedel iterator. We can update the
2598 1 : // batch rangedel iterator in place.
2599 1 : //
2600 1 : // NB: There may or may not be new range deletions. We
2601 1 : // can't tell based on i.batchRangeDelIter.Count(),
2602 1 : // which is the count of fragmented range deletions, NOT
2603 1 : // the number of range deletions written to the batch
2604 1 : // [i.batch.countRangeDels].
2605 1 : i.batch.initRangeDelIter(&i.opts, &i.batchRangeDelIter, nextBatchSeqNum)
2606 1 : }
2607 : }
2608 1 : if i.rangeKey != nil && i.batch.countRangeKeys > 0 {
2609 1 : if i.batchRangeKeyIter.Count() == 0 {
2610 1 : // When we constructed this iterator, there were no range
2611 1 : // keys in the batch. Iterator construction will have
2612 1 : // excluded the batch rangekey iterator from the range key
2613 1 : // iterator stack. We need to reconstruct the range key
2614 1 : // iterator to add i.batchRangeKeyIter into the iterator
2615 1 : // stack.
2616 1 : i.err = firstError(i.err, i.rangeKey.rangeKeyIter.Close())
2617 1 : i.rangeKey = nil
2618 1 : } else {
2619 1 : // There are range keys in the batch and we already
2620 1 : // have a batch rangekey iterator. We can update the batch
2621 1 : // rangekey iterator in place.
2622 1 : //
2623 1 : // NB: There may or may not be new range keys. We can't
2624 1 : // tell based on i.batchRangeKeyIter.Count(), which is the
2625 1 : // count of fragmented range keys, NOT the number of
2626 1 : // range keys written to the batch [i.batch.countRangeKeys].
2627 1 : i.batch.initRangeKeyIter(&i.opts, &i.batchRangeKeyIter, nextBatchSeqNum)
2628 1 : i.invalidate()
2629 1 : }
2630 : }
2631 : }
2632 : }
2633 :
2634 : // Reset combinedIterState.initialized in case the iterator key types
2635 : // changed. If there's already a range key iterator stack, the combined
2636 : // iterator is already initialized. Additionally, if the iterator is not
2637 : // configured to include range keys, mark it as initialized to signal that
2638 : // lower level iterators should not trigger a switch to combined iteration.
2639 1 : i.lazyCombinedIter.combinedIterState = combinedIterState{
2640 1 : initialized: i.rangeKey != nil || !i.opts.rangeKeys(),
2641 1 : }
2642 1 :
2643 1 : boundsEqual := ((i.opts.LowerBound == nil) == (o.LowerBound == nil)) &&
2644 1 : ((i.opts.UpperBound == nil) == (o.UpperBound == nil)) &&
2645 1 : i.equal(i.opts.LowerBound, o.LowerBound) &&
2646 1 : i.equal(i.opts.UpperBound, o.UpperBound)
2647 1 :
2648 1 : if boundsEqual && o.KeyTypes == i.opts.KeyTypes &&
2649 1 : (i.pointIter != nil || !i.opts.pointKeys()) &&
2650 1 : (i.rangeKey != nil || !i.opts.rangeKeys() || i.opts.KeyTypes == IterKeyTypePointsAndRanges) &&
2651 1 : i.equal(o.RangeKeyMasking.Suffix, i.opts.RangeKeyMasking.Suffix) &&
2652 1 : o.UseL6Filters == i.opts.UseL6Filters {
2653 1 : // The options are identical, so we can likely use the fast path. In
2654 1 : // addition to all the above constraints, we cannot use the fast path if
2655 1 : // configured to perform lazy combined iteration but an indexed batch
2656 1 : // used by the iterator now contains range keys. Lazy combined iteration
2657 1 : // is not compatible with batch range keys because we always need to
2658 1 : // merge the batch's range keys into iteration.
2659 1 : if i.rangeKey != nil || !i.opts.rangeKeys() || i.batch == nil || i.batch.countRangeKeys == 0 {
2660 1 : // Fast path. This preserves the Seek-using-Next optimizations as
2661 1 : // long as the iterator wasn't already invalidated up above.
2662 1 : return
2663 1 : }
2664 : }
2665 : // Slow path.
2666 :
2667 : // The options changed. Save the new ones to i.opts.
2668 1 : if boundsEqual {
2669 1 : // Copying the options into i.opts will overwrite LowerBound and
2670 1 : // UpperBound fields with the user-provided slices. We need to hold on
2671 1 : // to the Pebble-owned slices, so save them and re-set them after the
2672 1 : // copy.
2673 1 : lower, upper := i.opts.LowerBound, i.opts.UpperBound
2674 1 : i.opts = *o
2675 1 : i.opts.LowerBound, i.opts.UpperBound = lower, upper
2676 1 : } else {
2677 1 : i.opts = *o
2678 1 : i.processBounds(o.LowerBound, o.UpperBound)
2679 1 : // Propagate the changed bounds to the existing point iterator.
2680 1 : // NB: We propagate i.opts.{Lower,Upper}Bound, not o.{Lower,Upper}Bound
2681 1 : // because i.opts now point to buffers owned by Pebble.
2682 1 : if i.pointIter != nil {
2683 1 : i.pointIter.SetBounds(i.opts.LowerBound, i.opts.UpperBound)
2684 1 : }
2685 1 : if i.rangeKey != nil {
2686 1 : i.rangeKey.iterConfig.SetBounds(i.opts.LowerBound, i.opts.UpperBound)
2687 1 : }
2688 : }
2689 :
2690 : // Even though this is not a positioning operation, the invalidation of the
2691 : // iterator stack means we cannot optimize Seeks by using Next.
2692 1 : i.invalidate()
2693 1 :
2694 1 : // Iterators created through NewExternalIter have a different iterator
2695 1 : // initialization process.
2696 1 : if i.externalReaders != nil {
2697 1 : finishInitializingExternal(i.ctx, i)
2698 1 : return
2699 1 : }
2700 1 : finishInitializingIter(i.ctx, i.alloc)
2701 : }
2702 :
2703 1 : func (i *Iterator) invalidate() {
2704 1 : i.lastPositioningOp = unknownLastPositionOp
2705 1 : i.hasPrefix = false
2706 1 : i.iterKey = nil
2707 1 : i.iterValue = LazyValue{}
2708 1 : i.err = nil
2709 1 : // This switch statement isn't necessary for correctness since callers
2710 1 : // should call a repositioning method. We could have arbitrarily set i.pos
2711 1 : // to one of the values. But it results in more intuitive behavior in
2712 1 : // tests, which do not always reposition.
2713 1 : switch i.pos {
2714 1 : case iterPosCurForward, iterPosNext, iterPosCurForwardPaused:
2715 1 : i.pos = iterPosCurForward
2716 1 : case iterPosCurReverse, iterPosPrev, iterPosCurReversePaused:
2717 1 : i.pos = iterPosCurReverse
2718 : }
2719 1 : i.iterValidityState = IterExhausted
2720 1 : if i.rangeKey != nil {
2721 1 : i.rangeKey.iiter.Invalidate()
2722 1 : i.rangeKey.prevPosHadRangeKey = false
2723 1 : }
2724 : }
2725 :
2726 : // Metrics returns per-iterator metrics.
2727 0 : func (i *Iterator) Metrics() IteratorMetrics {
2728 0 : m := IteratorMetrics{
2729 0 : ReadAmp: 1,
2730 0 : }
2731 0 : if mi, ok := i.iter.(*mergingIter); ok {
2732 0 : m.ReadAmp = len(mi.levels)
2733 0 : }
2734 0 : return m
2735 : }
2736 :
2737 : // ResetStats resets the stats to 0.
2738 0 : func (i *Iterator) ResetStats() {
2739 0 : i.stats = IteratorStats{}
2740 0 : }
2741 :
2742 : // Stats returns the current stats.
2743 1 : func (i *Iterator) Stats() IteratorStats {
2744 1 : return i.stats
2745 1 : }
2746 :
2747 : // CloneOptions configures an iterator constructed through Iterator.Clone.
2748 : type CloneOptions struct {
2749 : // IterOptions, if non-nil, define the iterator options to configure a
2750 : // cloned iterator. If nil, the clone adopts the same IterOptions as the
2751 : // iterator being cloned.
2752 : IterOptions *IterOptions
2753 : // RefreshBatchView may be set to true when cloning an Iterator over an
2754 : // indexed batch. When false, the clone adopts the same (possibly stale)
2755 : // view of the indexed batch as the cloned Iterator. When true, the clone is
2756 : // constructed with a refreshed view of the batch, observing all of the
2757 : // batch's mutations at the time of the Clone. If the cloned iterator was
2758 : // not constructed to read over an indexed batch, RefreshVatchView has no
2759 : // effect.
2760 : RefreshBatchView bool
2761 : }
2762 :
2763 : // Clone creates a new Iterator over the same underlying data, i.e., over the
2764 : // same {batch, memtables, sstables}). The resulting iterator is not positioned.
2765 : // It starts with the same IterOptions, unless opts.IterOptions is set.
2766 : //
2767 : // When called on an Iterator over an indexed batch, the clone's visibility of
2768 : // the indexed batch is determined by CloneOptions.RefreshBatchView. If false,
2769 : // the clone inherits the iterator's current (possibly stale) view of the batch,
2770 : // and callers may call SetOptions to subsequently refresh the clone's view to
2771 : // include all batch mutations. If true, the clone is constructed with a
2772 : // complete view of the indexed batch's mutations at the time of the Clone.
2773 : //
2774 : // Callers can use Clone if they need multiple iterators that need to see
2775 : // exactly the same underlying state of the DB. This should not be used to
2776 : // extend the lifetime of the data backing the original Iterator since that
2777 : // will cause an increase in memory and disk usage (use NewSnapshot for that
2778 : // purpose).
2779 1 : func (i *Iterator) Clone(opts CloneOptions) (*Iterator, error) {
2780 1 : return i.CloneWithContext(context.Background(), opts)
2781 1 : }
2782 :
2783 : // CloneWithContext is like Clone, and additionally accepts a context for
2784 : // tracing.
2785 1 : func (i *Iterator) CloneWithContext(ctx context.Context, opts CloneOptions) (*Iterator, error) {
2786 1 : if opts.IterOptions == nil {
2787 1 : opts.IterOptions = &i.opts
2788 1 : }
2789 1 : if i.batchOnlyIter {
2790 1 : return nil, errors.Errorf("cannot Clone a batch-only Iterator")
2791 1 : }
2792 1 : readState := i.readState
2793 1 : vers := i.version
2794 1 : if readState == nil && vers == nil {
2795 1 : return nil, errors.Errorf("cannot Clone a closed Iterator")
2796 1 : }
2797 : // i is already holding a ref, so there is no race with unref here.
2798 : //
2799 : // TODO(bilal): If the underlying iterator was created on a snapshot, we could
2800 : // grab a reference to the current readState instead of reffing the original
2801 : // readState. This allows us to release references to some zombie sstables
2802 : // and memtables.
2803 1 : if readState != nil {
2804 1 : readState.ref()
2805 1 : }
2806 1 : if vers != nil {
2807 1 : vers.Ref()
2808 1 : }
2809 : // Bundle various structures under a single umbrella in order to allocate
2810 : // them together.
2811 1 : buf := iterAllocPool.Get().(*iterAlloc)
2812 1 : dbi := &buf.dbi
2813 1 : *dbi = Iterator{
2814 1 : ctx: ctx,
2815 1 : opts: *opts.IterOptions,
2816 1 : alloc: buf,
2817 1 : merge: i.merge,
2818 1 : comparer: i.comparer,
2819 1 : readState: readState,
2820 1 : version: vers,
2821 1 : keyBuf: buf.keyBuf,
2822 1 : prefixOrFullSeekKey: buf.prefixOrFullSeekKey,
2823 1 : boundsBuf: buf.boundsBuf,
2824 1 : batch: i.batch,
2825 1 : batchSeqNum: i.batchSeqNum,
2826 1 : newIters: i.newIters,
2827 1 : newIterRangeKey: i.newIterRangeKey,
2828 1 : seqNum: i.seqNum,
2829 1 : }
2830 1 : dbi.processBounds(dbi.opts.LowerBound, dbi.opts.UpperBound)
2831 1 :
2832 1 : // If the caller requested the clone have a current view of the indexed
2833 1 : // batch, set the clone's batch sequence number appropriately.
2834 1 : if i.batch != nil && opts.RefreshBatchView {
2835 1 : dbi.batchSeqNum = (uint64(len(i.batch.data)) | base.InternalKeySeqNumBatch)
2836 1 : }
2837 :
2838 1 : return finishInitializingIter(ctx, buf), nil
2839 : }
2840 :
2841 : // Merge adds all of the argument's statistics to the receiver. It may be used
2842 : // to accumulate stats across multiple iterators.
2843 1 : func (stats *IteratorStats) Merge(o IteratorStats) {
2844 1 : for i := InterfaceCall; i < NumStatsKind; i++ {
2845 1 : stats.ForwardSeekCount[i] += o.ForwardSeekCount[i]
2846 1 : stats.ReverseSeekCount[i] += o.ReverseSeekCount[i]
2847 1 : stats.ForwardStepCount[i] += o.ForwardStepCount[i]
2848 1 : stats.ReverseStepCount[i] += o.ReverseStepCount[i]
2849 1 : }
2850 1 : stats.InternalStats.Merge(o.InternalStats)
2851 1 : stats.RangeKeyStats.Merge(o.RangeKeyStats)
2852 : }
2853 :
2854 1 : func (stats *IteratorStats) String() string {
2855 1 : return redact.StringWithoutMarkers(stats)
2856 1 : }
2857 :
2858 : // SafeFormat implements the redact.SafeFormatter interface.
2859 1 : func (stats *IteratorStats) SafeFormat(s redact.SafePrinter, verb rune) {
2860 1 : for i := range stats.ForwardStepCount {
2861 1 : switch IteratorStatsKind(i) {
2862 1 : case InterfaceCall:
2863 1 : s.SafeString("(interface (dir, seek, step): ")
2864 1 : case InternalIterCall:
2865 1 : s.SafeString(", (internal (dir, seek, step): ")
2866 : }
2867 1 : s.Printf("(fwd, %d, %d), (rev, %d, %d))",
2868 1 : redact.Safe(stats.ForwardSeekCount[i]), redact.Safe(stats.ForwardStepCount[i]),
2869 1 : redact.Safe(stats.ReverseSeekCount[i]), redact.Safe(stats.ReverseStepCount[i]))
2870 : }
2871 1 : if stats.InternalStats != (InternalIteratorStats{}) {
2872 1 : s.SafeString(",\n(internal-stats: ")
2873 1 : s.Printf("(block-bytes: (total %s, cached %s, read-time %s)), "+
2874 1 : "(points: (count %s, key-bytes %s, value-bytes %s, tombstoned %s))",
2875 1 : humanize.Bytes.Uint64(stats.InternalStats.BlockBytes),
2876 1 : humanize.Bytes.Uint64(stats.InternalStats.BlockBytesInCache),
2877 1 : humanize.FormattedString(stats.InternalStats.BlockReadDuration.String()),
2878 1 : humanize.Count.Uint64(stats.InternalStats.PointCount),
2879 1 : humanize.Bytes.Uint64(stats.InternalStats.KeyBytes),
2880 1 : humanize.Bytes.Uint64(stats.InternalStats.ValueBytes),
2881 1 : humanize.Count.Uint64(stats.InternalStats.PointsCoveredByRangeTombstones),
2882 1 : )
2883 1 : if stats.InternalStats.SeparatedPointValue.Count != 0 {
2884 1 : s.Printf(", (separated: (count %s, bytes %s, fetched %s)))",
2885 1 : humanize.Count.Uint64(stats.InternalStats.SeparatedPointValue.Count),
2886 1 : humanize.Bytes.Uint64(stats.InternalStats.SeparatedPointValue.ValueBytes),
2887 1 : humanize.Bytes.Uint64(stats.InternalStats.SeparatedPointValue.ValueBytesFetched))
2888 1 : } else {
2889 1 : s.Printf(")")
2890 1 : }
2891 : }
2892 1 : if stats.RangeKeyStats != (RangeKeyIteratorStats{}) {
2893 1 : s.SafeString(",\n(range-key-stats: ")
2894 1 : s.Printf("(count %d), (contained points: (count %d, skipped %d)))",
2895 1 : stats.RangeKeyStats.Count,
2896 1 : stats.RangeKeyStats.ContainedPoints,
2897 1 : stats.RangeKeyStats.SkippedPoints)
2898 1 : }
2899 : }
2900 :
2901 : // CanDeterministicallySingleDelete takes a valid iterator and examines internal
2902 : // state to determine if a SingleDelete deleting Iterator.Key() would
2903 : // deterministically delete the key. CanDeterministicallySingleDelete requires
2904 : // the iterator to be oriented in the forward direction (eg, the last
2905 : // positioning operation must've been a First, a Seek[Prefix]GE, or a
2906 : // Next[Prefix][WithLimit]).
2907 : //
2908 : // This function does not change the external position of the iterator, and all
2909 : // positioning methods should behave the same as if it was never called. This
2910 : // function will only return a meaningful result the first time it's invoked at
2911 : // an iterator position. This function invalidates the iterator Value's memory,
2912 : // and the caller must not rely on the memory safety of the previous Iterator
2913 : // position.
2914 : //
2915 : // If CanDeterministicallySingleDelete returns true AND the key at the iterator
2916 : // position is not modified between the creation of the Iterator and the commit
2917 : // of a batch containing a SingleDelete over the key, then the caller can be
2918 : // assured that SingleDelete is equivalent to Delete on the local engine, but it
2919 : // may not be true on another engine that received the same writes and with
2920 : // logically equivalent state since this engine may have collapsed multiple SETs
2921 : // into one.
2922 1 : func CanDeterministicallySingleDelete(it *Iterator) (bool, error) {
2923 1 : // This function may only be called once per external iterator position. We
2924 1 : // can validate this by checking the last positioning operation.
2925 1 : if it.lastPositioningOp == internalNextOp {
2926 1 : return false, errors.New("pebble: CanDeterministicallySingleDelete called twice")
2927 1 : }
2928 1 : validity, kind := it.internalNext()
2929 1 : var shadowedBySingleDelete bool
2930 1 : for validity == internalNextValid {
2931 1 : switch kind {
2932 1 : case InternalKeyKindDelete, InternalKeyKindDeleteSized:
2933 1 : // A DEL or DELSIZED tombstone is okay. An internal key
2934 1 : // sequence like SINGLEDEL; SET; DEL; SET can be handled
2935 1 : // deterministically. If there are SETs further down, we
2936 1 : // don't care about them.
2937 1 : return true, nil
2938 1 : case InternalKeyKindSingleDelete:
2939 1 : // A SingleDelete is okay as long as when that SingleDelete was
2940 1 : // written, it was written deterministically (eg, with its own
2941 1 : // CanDeterministicallySingleDelete check). Validate that it was
2942 1 : // written deterministically. We'll allow one set to appear after
2943 1 : // the SingleDelete.
2944 1 : shadowedBySingleDelete = true
2945 1 : validity, kind = it.internalNext()
2946 1 : continue
2947 1 : case InternalKeyKindSet, InternalKeyKindSetWithDelete, InternalKeyKindMerge:
2948 1 : // If we observed a single delete, it's allowed to delete 1 key.
2949 1 : // We'll keep looping to validate that the internal keys beneath the
2950 1 : // already-written single delete are copacetic.
2951 1 : if shadowedBySingleDelete {
2952 1 : shadowedBySingleDelete = false
2953 1 : validity, kind = it.internalNext()
2954 1 : continue
2955 : }
2956 : // We encountered a shadowed SET, SETWITHDEL, MERGE. A SINGLEDEL
2957 : // that deleted the KV at the original iterator position could
2958 : // result in this key becoming visible.
2959 1 : return false, nil
2960 0 : case InternalKeyKindRangeDelete:
2961 0 : // RangeDeletes are handled by the merging iterator and should never
2962 0 : // be observed by the top-level Iterator.
2963 0 : panic(errors.AssertionFailedf("pebble: unexpected range delete"))
2964 0 : case InternalKeyKindRangeKeySet, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeyDelete:
2965 0 : // Range keys are interleaved at the maximal sequence number and
2966 0 : // should never be observed within a user key.
2967 0 : panic(errors.AssertionFailedf("pebble: unexpected range key"))
2968 0 : default:
2969 0 : panic(errors.AssertionFailedf("pebble: unexpected key kind: %s", errors.Safe(kind)))
2970 : }
2971 : }
2972 1 : if validity == internalNextError {
2973 1 : return false, it.Error()
2974 1 : }
2975 1 : return true, nil
2976 : }
2977 :
2978 : // internalNextValidity enumerates the potential outcomes of a call to
2979 : // internalNext.
2980 : type internalNextValidity int8
2981 :
2982 : const (
2983 : // internalNextError is returned by internalNext when an error occurred and
2984 : // the caller is responsible for checking iter.Error().
2985 : internalNextError internalNextValidity = iota
2986 : // internalNextExhausted is returned by internalNext when the next internal
2987 : // key is an internal key with a different user key than Iterator.Key().
2988 : internalNextExhausted
2989 : // internalNextValid is returned by internalNext when the internal next
2990 : // found a shadowed internal key with a user key equal to Iterator.Key().
2991 : internalNextValid
2992 : )
2993 :
2994 : // internalNext advances internal Iterator state forward to expose the
2995 : // InternalKeyKind of the next internal key with a user key equal to Key().
2996 : //
2997 : // internalNext is a highly specialized operation and is unlikely to be
2998 : // generally useful. See Iterator.Next for how to reposition the iterator to the
2999 : // next key. internalNext requires the Iterator to be at a valid position in the
3000 : // forward direction (the last positioning operation must've been a First, a
3001 : // Seek[Prefix]GE, or a Next[Prefix][WithLimit] and Valid() must return true).
3002 : //
3003 : // internalNext, unlike all other Iterator methods, exposes internal LSM state.
3004 : // internalNext advances the Iterator's internal iterator to the next shadowed
3005 : // key with a user key equal to Key(). When a key is overwritten or deleted, its
3006 : // removal from the LSM occurs lazily as a part of compactions. internalNext
3007 : // allows the caller to see whether an obsolete internal key exists with the
3008 : // current Key(), and what it's key kind is. Note that the existence of an
3009 : // internal key is nondeterministic and dependent on internal LSM state. These
3010 : // semantics are unlikely to be applicable to almost all use cases.
3011 : //
3012 : // If internalNext finds a key that shares the same user key as Key(), it
3013 : // returns internalNextValid and the internal key's kind. If internalNext
3014 : // encounters an error, it returns internalNextError and the caller is expected
3015 : // to call Iterator.Error() to retrieve it. In all other circumstances,
3016 : // internalNext returns internalNextExhausted, indicating that there are no more
3017 : // additional internal keys with the user key Key().
3018 : //
3019 : // internalNext does not change the external position of the iterator, and a
3020 : // Next operation should behave the same as if internalNext was never called.
3021 : // internalNext does invalidate the iterator Value's memory, and the caller must
3022 : // not rely on the memory safety of the previous Iterator position.
3023 1 : func (i *Iterator) internalNext() (internalNextValidity, base.InternalKeyKind) {
3024 1 : i.stats.ForwardStepCount[InterfaceCall]++
3025 1 : if i.err != nil {
3026 1 : return internalNextError, base.InternalKeyKindInvalid
3027 1 : } else if i.iterValidityState != IterValid {
3028 1 : return internalNextExhausted, base.InternalKeyKindInvalid
3029 1 : }
3030 1 : i.lastPositioningOp = internalNextOp
3031 1 :
3032 1 : switch i.pos {
3033 1 : case iterPosCurForward:
3034 1 : i.iterKey, i.iterValue = i.iter.Next()
3035 1 : if i.iterKey == nil {
3036 1 : // We check i.iter.Error() here and return an internalNextError enum
3037 1 : // variant so that the caller does not need to check i.iter.Error()
3038 1 : // in the common case that the next internal key has a new user key.
3039 1 : if i.err = i.iter.Error(); i.err != nil {
3040 0 : return internalNextError, base.InternalKeyKindInvalid
3041 0 : }
3042 1 : i.pos = iterPosNext
3043 1 : return internalNextExhausted, base.InternalKeyKindInvalid
3044 1 : } else if i.comparer.Equal(i.iterKey.UserKey, i.key) {
3045 1 : return internalNextValid, i.iterKey.Kind()
3046 1 : }
3047 1 : i.pos = iterPosNext
3048 1 : return internalNextExhausted, base.InternalKeyKindInvalid
3049 1 : case iterPosCurReverse, iterPosCurReversePaused, iterPosPrev:
3050 1 : i.err = errors.New("switching from reverse to forward via internalNext is prohibited")
3051 1 : i.iterValidityState = IterExhausted
3052 1 : return internalNextError, base.InternalKeyKindInvalid
3053 1 : case iterPosNext, iterPosCurForwardPaused:
3054 1 : // The previous method already moved onto the next user key. This is
3055 1 : // only possible if
3056 1 : // - the last positioning method was a call to internalNext, and we
3057 1 : // advanced to a new user key.
3058 1 : // - the previous non-internalNext iterator operation encountered a
3059 1 : // range key or merge, forcing an internal Next that found a new
3060 1 : // user key that's not equal to i.Iterator.Key().
3061 1 : return internalNextExhausted, base.InternalKeyKindInvalid
3062 0 : default:
3063 0 : panic("unreachable")
3064 : }
3065 : }
|