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

Generated by: LCOV version 1.14