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

Generated by: LCOV version 1.14