LCOV - code coverage report
Current view: top level - pebble - iterator.go (source / functions) Coverage Total Hit
Test: 2025-07-28 08:19Z bb252436 - meta test only.lcov Lines: 77.7 % 1929 1499
Test Date: 2025-07-28 08:20:54 Functions: - 0 0

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

Generated by: LCOV version 2.0-1