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