LCOV - code coverage report
Current view: top level - pebble - merging_iter.go (source / functions) Hit Total Coverage
Test: 2023-09-11 08:17Z 1efa535d - meta test only.lcov Lines: 656 713 92.0 %
Date: 2023-09-11 08:18:45 Functions: 0 0 -

          Line data    Source code
       1             : // Copyright 2018 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             :         "fmt"
      10             :         "runtime/debug"
      11             :         "unsafe"
      12             : 
      13             :         "github.com/cockroachdb/errors"
      14             :         "github.com/cockroachdb/pebble/internal/base"
      15             :         "github.com/cockroachdb/pebble/internal/invariants"
      16             :         "github.com/cockroachdb/pebble/internal/keyspan"
      17             : )
      18             : 
      19             : type mergingIterLevel struct {
      20             :         index int
      21             :         iter  internalIterator
      22             :         // rangeDelIter is set to the range-deletion iterator for the level. When
      23             :         // configured with a levelIter, this pointer changes as sstable boundaries
      24             :         // are crossed. See levelIter.initRangeDel and the Range Deletions comment
      25             :         // below.
      26             :         rangeDelIter keyspan.FragmentIterator
      27             :         // iterKey and iterValue cache the current key and value iter are pointed at.
      28             :         iterKey   *InternalKey
      29             :         iterValue base.LazyValue
      30             : 
      31             :         // levelIterBoundaryContext's fields are set when using levelIter, in order
      32             :         // to surface sstable boundary keys and file-level context. See levelIter
      33             :         // comment and the Range Deletions comment below.
      34             :         levelIterBoundaryContext
      35             : 
      36             :         // tombstone caches the tombstone rangeDelIter is currently pointed at. If
      37             :         // tombstone is nil, there are no further tombstones within the
      38             :         // current sstable in the current iterator direction. The cached tombstone is
      39             :         // only valid for the levels in the range [0,heap[0].index]. This avoids
      40             :         // positioning tombstones at lower levels which cannot possibly shadow the
      41             :         // current key.
      42             :         tombstone *keyspan.Span
      43             : }
      44             : 
      45             : type levelIterBoundaryContext struct {
      46             :         // smallestUserKey and largestUserKey are populated with the smallest and
      47             :         // largest boundaries of the current file.
      48             :         smallestUserKey, largestUserKey []byte
      49             :         // isLargestUserKeyExclusive is set to true when a file's largest boundary
      50             :         // is an exclusive key, (eg, a range deletion sentinel). If true, the file
      51             :         // does not contain any keys with the provided user key, and the
      52             :         // largestUserKey bound is exclusive.
      53             :         isLargestUserKeyExclusive bool
      54             :         // isSyntheticIterBoundsKey is set to true iff the key returned by the level
      55             :         // iterator is a synthetic key derived from the iterator bounds. This is used
      56             :         // to prevent the mergingIter from being stuck at such a synthetic key if it
      57             :         // becomes the top element of the heap. When used with a user-facing Iterator,
      58             :         // the only range deletions exposed by this mergingIter should be those with
      59             :         // `isSyntheticIterBoundsKey || isIgnorableBoundaryKey`.
      60             :         isSyntheticIterBoundsKey bool
      61             :         // isIgnorableBoundaryKey is set to true iff the key returned by the level
      62             :         // iterator is a file boundary key that should be ignored when returning to
      63             :         // the parent iterator. File boundary keys are used by the level iter to
      64             :         // keep a levelIter file's range deletion iterator open as long as other
      65             :         // levels within the merging iterator require it. When used with a user-facing
      66             :         // Iterator, the only range deletions exposed by this mergingIter should be
      67             :         // those with `isSyntheticIterBoundsKey || isIgnorableBoundaryKey`.
      68             :         isIgnorableBoundaryKey bool
      69             : }
      70             : 
      71             : // mergingIter provides a merged view of multiple iterators from different
      72             : // levels of the LSM.
      73             : //
      74             : // The core of a mergingIter is a heap of internalIterators (see
      75             : // mergingIterHeap). The heap can operate as either a min-heap, used during
      76             : // forward iteration (First, SeekGE, Next) or a max-heap, used during reverse
      77             : // iteration (Last, SeekLT, Prev). The heap is initialized in calls to First,
      78             : // Last, SeekGE, and SeekLT. A call to Next or Prev takes the current top
      79             : // element on the heap, advances its iterator, and then "fixes" the heap
      80             : // property. When one of the child iterators is exhausted during Next/Prev
      81             : // iteration, it is removed from the heap.
      82             : //
      83             : // # Range Deletions
      84             : //
      85             : // A mergingIter can optionally be configured with a slice of range deletion
      86             : // iterators. The range deletion iterator slice must exactly parallel the point
      87             : // iterators and the range deletion iterator must correspond to the same level
      88             : // in the LSM as the point iterator. Note that each memtable and each table in
      89             : // L0 is a different "level" from the mergingIter perspective. So level 0 below
      90             : // does not correspond to L0 in the LSM.
      91             : //
      92             : // A range deletion iterator iterates over fragmented range tombstones. Range
      93             : // tombstones are fragmented by splitting them at any overlapping points. This
      94             : // fragmentation guarantees that within an sstable tombstones will either be
      95             : // distinct or will have identical start and end user keys. While range
      96             : // tombstones are fragmented within an sstable, the start and end keys are not truncated
      97             : // to sstable boundaries. This is necessary because the tombstone end key is
      98             : // exclusive and does not have a sequence number. Consider an sstable
      99             : // containing the range tombstone [a,c)#9 and the key "b#8". The tombstone must
     100             : // delete "b#8", yet older versions of "b" might spill over to the next
     101             : // sstable. So the boundary key for this sstable must be "b#8". Adjusting the
     102             : // end key of tombstones to be optionally inclusive or contain a sequence
     103             : // number would be possible solutions (such solutions have potentially serious
     104             : // issues: tombstones have exclusive end keys since an inclusive deletion end can
     105             : // be converted to an exclusive one while the reverse transformation is not possible;
     106             : // the semantics of a sequence number for the end key of a range tombstone are murky).
     107             : //
     108             : // The approach taken here performs an
     109             : // implicit truncation of the tombstone to the sstable boundaries.
     110             : //
     111             : // During initialization of a mergingIter, the range deletion iterators for
     112             : // batches, memtables, and L0 tables are populated up front. Note that Batches
     113             : // and memtables index unfragmented tombstones.  Batch.newRangeDelIter() and
     114             : // memTable.newRangeDelIter() fragment and cache the tombstones on demand. The
     115             : // L1-L6 range deletion iterators are populated by levelIter. When configured
     116             : // to load range deletion iterators, whenever a levelIter loads a table it
     117             : // loads both the point iterator and the range deletion
     118             : // iterator. levelIter.rangeDelIter is configured to point to the right entry
     119             : // in mergingIter.levels. The effect of this setup is that
     120             : // mergingIter.levels[i].rangeDelIter always contains the fragmented range
     121             : // tombstone for the current table in level i that the levelIter has open.
     122             : //
     123             : // Another crucial mechanism of levelIter is that it materializes fake point
     124             : // entries for the table boundaries if the boundary is range deletion
     125             : // key. Consider a table that contains only a range tombstone [a-e)#10. The
     126             : // sstable boundaries for this table will be a#10,15 and
     127             : // e#72057594037927935,15. During forward iteration levelIter will return
     128             : // e#72057594037927935,15 as a key. During reverse iteration levelIter will
     129             : // return a#10,15 as a key. These sentinel keys act as bookends to point
     130             : // iteration and allow mergingIter to keep a table and its associated range
     131             : // tombstones loaded as long as there are keys at lower levels that are within
     132             : // the bounds of the table.
     133             : //
     134             : // The final piece to the range deletion puzzle is the LSM invariant that for a
     135             : // given key K newer versions of K can only exist earlier in the level, or at
     136             : // higher levels of the tree. For example, if K#4 exists in L3, k#5 can only
     137             : // exist earlier in the L3 or in L0, L1, L2 or a memtable. Get very explicitly
     138             : // uses this invariant to find the value for a key by walking the LSM level by
     139             : // level. For range deletions, this invariant means that a range deletion at
     140             : // level N will necessarily shadow any keys within its bounds in level Y where
     141             : // Y > N. One wrinkle to this statement is that it only applies to keys that
     142             : // lie within the sstable bounds as well, but we get that guarantee due to the
     143             : // way the range deletion iterator and point iterator are bound together by a
     144             : // levelIter.
     145             : //
     146             : // Tying the above all together, we get a picture where each level (index in
     147             : // mergingIter.levels) is composed of both point operations (pX) and range
     148             : // deletions (rX). The range deletions for level X shadow both the point
     149             : // operations and range deletions for level Y where Y > X allowing mergingIter
     150             : // to skip processing entries in that shadow. For example, consider the
     151             : // scenario:
     152             : //
     153             : //      r0: a---e
     154             : //      r1:    d---h
     155             : //      r2:       g---k
     156             : //      r3:          j---n
     157             : //      r4:             m---q
     158             : //
     159             : // This is showing 5 levels of range deletions. Consider what happens upon
     160             : // SeekGE("b"). We first seek the point iterator for level 0 (the point values
     161             : // are not shown above) and we then seek the range deletion iterator. That
     162             : // returns the tombstone [a,e). This tombstone tells us that all keys in the
     163             : // range [a,e) in lower levels are deleted so we can skip them. So we can
     164             : // adjust the seek key to "e", the tombstone end key. For level 1 we seek to
     165             : // "e" and find the range tombstone [d,h) and similar logic holds. By the time
     166             : // we get to level 4 we're seeking to "n".
     167             : //
     168             : // One consequence of not truncating tombstone end keys to sstable boundaries
     169             : // is the seeking process described above cannot always seek to the tombstone
     170             : // end key in the older level. For example, imagine in the above example r3 is
     171             : // a partitioned level (i.e., L1+ in our LSM), and the sstable containing [j,
     172             : // n) has "k" as its upper boundary. In this situation, compactions involving
     173             : // keys at or after "k" can output those keys to r4+, even if they're newer
     174             : // than our tombstone [j, n). So instead of seeking to "n" in r4 we can only
     175             : // seek to "k".  To achieve this, the instance variable `largestUserKey.`
     176             : // maintains the upper bounds of the current sstables in the partitioned
     177             : // levels. In this example, `levels[3].largestUserKey` holds "k", telling us to
     178             : // limit the seek triggered by a tombstone in r3 to "k".
     179             : //
     180             : // During actual iteration levels can contain both point operations and range
     181             : // deletions. Within a level, when a range deletion contains a point operation
     182             : // the sequence numbers must be checked to determine if the point operation is
     183             : // newer or older than the range deletion tombstone. The mergingIter maintains
     184             : // the invariant that the range deletion iterators for all levels newer that
     185             : // the current iteration key (L < m.heap.items[0].index) are positioned at the
     186             : // next (or previous during reverse iteration) range deletion tombstone. We
     187             : // know those levels don't contain a range deletion tombstone that covers the
     188             : // current key because if they did the current key would be deleted. The range
     189             : // deletion iterator for the current key's level is positioned at a range
     190             : // tombstone covering or past the current key. The position of all of other
     191             : // range deletion iterators is unspecified. Whenever a key from those levels
     192             : // becomes the current key, their range deletion iterators need to be
     193             : // positioned. This lazy positioning avoids seeking the range deletion
     194             : // iterators for keys that are never considered. (A similar bit of lazy
     195             : // evaluation can be done for the point iterators, but is still TBD).
     196             : //
     197             : // For a full example, consider the following setup:
     198             : //
     199             : //      p0:               o
     200             : //      r0:             m---q
     201             : //
     202             : //      p1:              n p
     203             : //      r1:       g---k
     204             : //
     205             : //      p2:  b d    i
     206             : //      r2: a---e           q----v
     207             : //
     208             : //      p3:     e
     209             : //      r3:
     210             : //
     211             : // If we start iterating from the beginning, the first key we encounter is "b"
     212             : // in p2. When the mergingIter is pointing at a valid entry, the range deletion
     213             : // iterators for all of the levels < m.heap.items[0].index are positioned at
     214             : // the next range tombstone past the current key. So r0 will point at [m,q) and
     215             : // r1 at [g,k). When the key "b" is encountered, we check to see if the current
     216             : // tombstone for r0 or r1 contains it, and whether the tombstone for r2, [a,e),
     217             : // contains and is newer than "b".
     218             : //
     219             : // Advancing the iterator finds the next key at "d". This is in the same level
     220             : // as the previous key "b" so we don't have to reposition any of the range
     221             : // deletion iterators, but merely check whether "d" is now contained by any of
     222             : // the range tombstones at higher levels or has stepped past the range
     223             : // tombstone in its own level or higher levels. In this case, there is nothing to be done.
     224             : //
     225             : // Advancing the iterator again finds "e". Since "e" comes from p3, we have to
     226             : // position the r3 range deletion iterator, which is empty. "e" is past the r2
     227             : // tombstone of [a,e) so we need to advance the r2 range deletion iterator to
     228             : // [q,v).
     229             : //
     230             : // The next key is "i". Because this key is in p2, a level above "e", we don't
     231             : // have to reposition any range deletion iterators and instead see that "i" is
     232             : // covered by the range tombstone [g,k). The iterator is immediately advanced
     233             : // to "n" which is covered by the range tombstone [m,q) causing the iterator to
     234             : // advance to "o" which is visible.
     235             : //
     236             : // TODO(peter,rangedel): For testing, advance the iterator through various
     237             : // scenarios and have each step display the current state (i.e. the current
     238             : // heap and range-del iterator positioning).
     239             : type mergingIter struct {
     240             :         logger        Logger
     241             :         split         Split
     242             :         dir           int
     243             :         snapshot      uint64
     244             :         batchSnapshot uint64
     245             :         levels        []mergingIterLevel
     246             :         heap          mergingIterHeap
     247             :         err           error
     248             :         prefix        []byte
     249             :         lower         []byte
     250             :         upper         []byte
     251             :         stats         *InternalIteratorStats
     252             : 
     253             :         // levelsPositioned, if non-nil, is a slice of the same length as levels.
     254             :         // It's used by NextPrefix to record which levels have already been
     255             :         // repositioned. It's created lazily by the first call to NextPrefix.
     256             :         levelsPositioned []bool
     257             : 
     258             :         combinedIterState *combinedIterState
     259             : 
     260             :         // Used in some tests to disable the random disabling of seek optimizations.
     261             :         forceEnableSeekOpt bool
     262             : }
     263             : 
     264             : // mergingIter implements the base.InternalIterator interface.
     265             : var _ base.InternalIterator = (*mergingIter)(nil)
     266             : 
     267             : // newMergingIter returns an iterator that merges its input. Walking the
     268             : // resultant iterator will return all key/value pairs of all input iterators
     269             : // in strictly increasing key order, as defined by cmp. It is permissible to
     270             : // pass a nil split parameter if the caller is never going to call
     271             : // SeekPrefixGE.
     272             : //
     273             : // The input's key ranges may overlap, but there are assumed to be no duplicate
     274             : // keys: if iters[i] contains a key k then iters[j] will not contain that key k.
     275             : //
     276             : // None of the iters may be nil.
     277             : func newMergingIter(
     278             :         logger Logger,
     279             :         stats *base.InternalIteratorStats,
     280             :         cmp Compare,
     281             :         split Split,
     282             :         iters ...internalIterator,
     283           1 : ) *mergingIter {
     284           1 :         m := &mergingIter{}
     285           1 :         levels := make([]mergingIterLevel, len(iters))
     286           1 :         for i := range levels {
     287           1 :                 levels[i].iter = iters[i]
     288           1 :         }
     289           1 :         m.init(&IterOptions{logger: logger}, stats, cmp, split, levels...)
     290           1 :         return m
     291             : }
     292             : 
     293             : func (m *mergingIter) init(
     294             :         opts *IterOptions,
     295             :         stats *base.InternalIteratorStats,
     296             :         cmp Compare,
     297             :         split Split,
     298             :         levels ...mergingIterLevel,
     299           1 : ) {
     300           1 :         m.err = nil // clear cached iteration error
     301           1 :         m.logger = opts.getLogger()
     302           1 :         if opts != nil {
     303           1 :                 m.lower = opts.LowerBound
     304           1 :                 m.upper = opts.UpperBound
     305           1 :         }
     306           1 :         m.snapshot = InternalKeySeqNumMax
     307           1 :         m.batchSnapshot = InternalKeySeqNumMax
     308           1 :         m.levels = levels
     309           1 :         m.heap.cmp = cmp
     310           1 :         m.split = split
     311           1 :         m.stats = stats
     312           1 :         if cap(m.heap.items) < len(levels) {
     313           1 :                 m.heap.items = make([]*mergingIterLevel, 0, len(levels))
     314           1 :         } else {
     315           1 :                 m.heap.items = m.heap.items[:0]
     316           1 :         }
     317           1 :         for l := range m.levels {
     318           1 :                 m.levels[l].index = l
     319           1 :         }
     320             : }
     321             : 
     322           1 : func (m *mergingIter) initHeap() {
     323           1 :         m.heap.items = m.heap.items[:0]
     324           1 :         for i := range m.levels {
     325           1 :                 if l := &m.levels[i]; l.iterKey != nil {
     326           1 :                         m.heap.items = append(m.heap.items, l)
     327           1 :                 } else {
     328           1 :                         m.err = firstError(m.err, l.iter.Error())
     329           1 :                         if m.err != nil {
     330           0 :                                 return
     331           0 :                         }
     332             :                 }
     333             :         }
     334           1 :         m.heap.init()
     335             : }
     336             : 
     337           1 : func (m *mergingIter) initMinHeap() {
     338           1 :         m.dir = 1
     339           1 :         m.heap.reverse = false
     340           1 :         m.initHeap()
     341           1 :         m.initMinRangeDelIters(-1)
     342           1 : }
     343             : 
     344             : // The level of the previous top element was oldTopLevel. Note that all range delete
     345             : // iterators < oldTopLevel are positioned past the key of the previous top element and
     346             : // the range delete iterator == oldTopLevel is positioned at or past the key of the
     347             : // previous top element. We need to position the range delete iterators from oldTopLevel + 1
     348             : // to the level of the current top element.
     349           1 : func (m *mergingIter) initMinRangeDelIters(oldTopLevel int) {
     350           1 :         if m.heap.len() == 0 {
     351           1 :                 return
     352           1 :         }
     353             : 
     354             :         // Position the range-del iterators at levels <= m.heap.items[0].index.
     355           1 :         item := m.heap.items[0]
     356           1 :         for level := oldTopLevel + 1; level <= item.index; level++ {
     357           1 :                 l := &m.levels[level]
     358           1 :                 if l.rangeDelIter == nil {
     359           1 :                         continue
     360             :                 }
     361           1 :                 l.tombstone = l.rangeDelIter.SeekGE(item.iterKey.UserKey)
     362             :         }
     363             : }
     364             : 
     365           1 : func (m *mergingIter) initMaxHeap() {
     366           1 :         m.dir = -1
     367           1 :         m.heap.reverse = true
     368           1 :         m.initHeap()
     369           1 :         m.initMaxRangeDelIters(-1)
     370           1 : }
     371             : 
     372             : // The level of the previous top element was oldTopLevel. Note that all range delete
     373             : // iterators < oldTopLevel are positioned before the key of the previous top element and
     374             : // the range delete iterator == oldTopLevel is positioned at or before the key of the
     375             : // previous top element. We need to position the range delete iterators from oldTopLevel + 1
     376             : // to the level of the current top element.
     377           1 : func (m *mergingIter) initMaxRangeDelIters(oldTopLevel int) {
     378           1 :         if m.heap.len() == 0 {
     379           1 :                 return
     380           1 :         }
     381             :         // Position the range-del iterators at levels <= m.heap.items[0].index.
     382           1 :         item := m.heap.items[0]
     383           1 :         for level := oldTopLevel + 1; level <= item.index; level++ {
     384           1 :                 l := &m.levels[level]
     385           1 :                 if l.rangeDelIter == nil {
     386           1 :                         continue
     387             :                 }
     388           1 :                 l.tombstone = keyspan.SeekLE(m.heap.cmp, l.rangeDelIter, item.iterKey.UserKey)
     389             :         }
     390             : }
     391             : 
     392           1 : func (m *mergingIter) switchToMinHeap() {
     393           1 :         if m.heap.len() == 0 {
     394           1 :                 if m.lower != nil {
     395           1 :                         m.SeekGE(m.lower, base.SeekGEFlagsNone)
     396           1 :                 } else {
     397           1 :                         m.First()
     398           1 :                 }
     399           1 :                 return
     400             :         }
     401             : 
     402             :         // We're switching from using a max heap to a min heap. We need to advance
     403             :         // any iterator that is less than or equal to the current key. Consider the
     404             :         // scenario where we have 2 iterators being merged (user-key:seq-num):
     405             :         //
     406             :         // i1:     *a:2     b:2
     407             :         // i2: a:1      b:1
     408             :         //
     409             :         // The current key is a:2 and i2 is pointed at a:1. When we switch to forward
     410             :         // iteration, we want to return a key that is greater than a:2.
     411             : 
     412           1 :         key := m.heap.items[0].iterKey
     413           1 :         cur := m.heap.items[0]
     414           1 : 
     415           1 :         for i := range m.levels {
     416           1 :                 l := &m.levels[i]
     417           1 :                 if l == cur {
     418           1 :                         continue
     419             :                 }
     420             : 
     421             :                 // If the iterator is exhausted, it may be out of bounds if range
     422             :                 // deletions modified our search key as we descended. we need to
     423             :                 // reposition it within the search bounds. If the current key is a
     424             :                 // range tombstone, the iterator might still be exhausted but at a
     425             :                 // sstable boundary sentinel. It would be okay to reposition an
     426             :                 // interator like this only through successive Next calls, except that
     427             :                 // it would violate the levelIter's invariants by causing it to return
     428             :                 // a key before the lower bound.
     429             :                 //
     430             :                 //           bounds = [ f, _ )
     431             :                 // L0:   [ b ]          [ f*                   z ]
     432             :                 // L1: [ a           |----|        k        y ]
     433             :                 // L2:    [  c  (d) ] [ e      g     m ]
     434             :                 // L3:             [                    x ]
     435             :                 //
     436             :                 // * - current key   [] - table bounds () - heap item
     437             :                 //
     438             :                 // In the above diagram, the L2 iterator is positioned at a sstable
     439             :                 // boundary (d) outside the lower bound (f). It arrived here from a
     440             :                 // seek whose seek-key was modified by a range tombstone. If we called
     441             :                 // Next on the L2 iterator, it would return e, violating its lower
     442             :                 // bound.  Instead, we seek it to >= f and Next from there.
     443             : 
     444           1 :                 if l.iterKey == nil || (m.lower != nil && l.isSyntheticIterBoundsKey &&
     445           1 :                         l.iterKey.IsExclusiveSentinel() &&
     446           1 :                         m.heap.cmp(l.iterKey.UserKey, m.lower) <= 0) {
     447           1 :                         if m.lower != nil {
     448           1 :                                 l.iterKey, l.iterValue = l.iter.SeekGE(m.lower, base.SeekGEFlagsNone)
     449           1 :                         } else {
     450           1 :                                 l.iterKey, l.iterValue = l.iter.First()
     451           1 :                         }
     452             :                 }
     453           1 :                 for ; l.iterKey != nil; l.iterKey, l.iterValue = l.iter.Next() {
     454           1 :                         if base.InternalCompare(m.heap.cmp, *key, *l.iterKey) < 0 {
     455           1 :                                 // key < iter-key
     456           1 :                                 break
     457             :                         }
     458             :                         // key >= iter-key
     459             :                 }
     460             :         }
     461             : 
     462             :         // Special handling for the current iterator because we were using its key
     463             :         // above. The iterator cur.iter may still be exhausted at a sstable boundary
     464             :         // sentinel. Similar to the logic applied to the other levels, in these
     465             :         // cases we seek the iterator to the first key in order to avoid violating
     466             :         // levelIter's invariants. See the example in the for loop above.
     467           1 :         if m.lower != nil && cur.isSyntheticIterBoundsKey && cur.iterKey.IsExclusiveSentinel() &&
     468           1 :                 m.heap.cmp(cur.iterKey.UserKey, m.lower) <= 0 {
     469           1 :                 cur.iterKey, cur.iterValue = cur.iter.SeekGE(m.lower, base.SeekGEFlagsNone)
     470           1 :         } else {
     471           1 :                 cur.iterKey, cur.iterValue = cur.iter.Next()
     472           1 :         }
     473           1 :         m.initMinHeap()
     474             : }
     475             : 
     476           1 : func (m *mergingIter) switchToMaxHeap() {
     477           1 :         if m.heap.len() == 0 {
     478           1 :                 if m.upper != nil {
     479           1 :                         m.SeekLT(m.upper, base.SeekLTFlagsNone)
     480           1 :                 } else {
     481           1 :                         m.Last()
     482           1 :                 }
     483           1 :                 return
     484             :         }
     485             : 
     486             :         // We're switching from using a min heap to a max heap. We need to backup any
     487             :         // iterator that is greater than or equal to the current key. Consider the
     488             :         // scenario where we have 2 iterators being merged (user-key:seq-num):
     489             :         //
     490             :         // i1: a:2     *b:2
     491             :         // i2:     a:1      b:1
     492             :         //
     493             :         // The current key is b:2 and i2 is pointing at b:1. When we switch to
     494             :         // reverse iteration, we want to return a key that is less than b:2.
     495           1 :         key := m.heap.items[0].iterKey
     496           1 :         cur := m.heap.items[0]
     497           1 : 
     498           1 :         for i := range m.levels {
     499           1 :                 l := &m.levels[i]
     500           1 :                 if l == cur {
     501           1 :                         continue
     502             :                 }
     503             : 
     504             :                 // If the iterator is exhausted, it may be out of bounds if range
     505             :                 // deletions modified our search key as we descended. we need to
     506             :                 // reposition it within the search bounds. If the current key is a
     507             :                 // range tombstone, the iterator might still be exhausted but at a
     508             :                 // sstable boundary sentinel. It would be okay to reposition an
     509             :                 // interator like this only through successive Prev calls, except that
     510             :                 // it would violate the levelIter's invariants by causing it to return
     511             :                 // a key beyond the upper bound.
     512             :                 //
     513             :                 //           bounds = [ _, g )
     514             :                 // L0:   [ b ]          [ f*                   z ]
     515             :                 // L1: [ a                |-------| k       y ]
     516             :                 // L2:    [  c   d  ]        h [(i)    m ]
     517             :                 // L3:             [  e                  x ]
     518             :                 //
     519             :                 // * - current key   [] - table bounds () - heap item
     520             :                 //
     521             :                 // In the above diagram, the L2 iterator is positioned at a sstable
     522             :                 // boundary (i) outside the upper bound (g). It arrived here from a
     523             :                 // seek whose seek-key was modified by a range tombstone. If we called
     524             :                 // Prev on the L2 iterator, it would return h, violating its upper
     525             :                 // bound.  Instead, we seek it to < g, and Prev from there.
     526             : 
     527           1 :                 if l.iterKey == nil || (m.upper != nil && l.isSyntheticIterBoundsKey &&
     528           1 :                         l.iterKey.IsExclusiveSentinel() && m.heap.cmp(l.iterKey.UserKey, m.upper) >= 0) {
     529           1 :                         if m.upper != nil {
     530           1 :                                 l.iterKey, l.iterValue = l.iter.SeekLT(m.upper, base.SeekLTFlagsNone)
     531           1 :                         } else {
     532           1 :                                 l.iterKey, l.iterValue = l.iter.Last()
     533           1 :                         }
     534             :                 }
     535           1 :                 for ; l.iterKey != nil; l.iterKey, l.iterValue = l.iter.Prev() {
     536           1 :                         if base.InternalCompare(m.heap.cmp, *key, *l.iterKey) > 0 {
     537           1 :                                 // key > iter-key
     538           1 :                                 break
     539             :                         }
     540             :                         // key <= iter-key
     541             :                 }
     542             :         }
     543             : 
     544             :         // Special handling for the current iterator because we were using its key
     545             :         // above. The iterator cur.iter may still be exhausted at a sstable boundary
     546             :         // sentinel. Similar to the logic applied to the other levels, in these
     547             :         // cases we seek the iterator to  in order to avoid violating levelIter's
     548             :         // invariants by Prev-ing through files.  See the example in the for loop
     549             :         // above.
     550           1 :         if m.upper != nil && cur.isSyntheticIterBoundsKey && cur.iterKey.IsExclusiveSentinel() &&
     551           1 :                 m.heap.cmp(cur.iterKey.UserKey, m.upper) >= 0 {
     552           1 :                 cur.iterKey, cur.iterValue = cur.iter.SeekLT(m.upper, base.SeekLTFlagsNone)
     553           1 :         } else {
     554           1 :                 cur.iterKey, cur.iterValue = cur.iter.Prev()
     555           1 :         }
     556           1 :         m.initMaxHeap()
     557             : }
     558             : 
     559             : // maybeNextEntryWithinPrefix steps to the next entry, as long as the iteration
     560             : // prefix has not already been exceeded. If it has, it exhausts the iterator by
     561             : // resetting the heap to empty.
     562           1 : func (m *mergingIter) maybeNextEntryWithinPrefix(l *mergingIterLevel) {
     563           1 :         if s := m.split(l.iterKey.UserKey); !bytes.Equal(m.prefix, l.iterKey.UserKey[:s]) {
     564           1 :                 // The item at the root of the heap already exceeds the iteration
     565           1 :                 // prefix. We should not advance any more. Clear the heap to reflect
     566           1 :                 // that the iterator is now exhausted (within this prefix, at
     567           1 :                 // least).
     568           1 :                 m.heap.items = m.heap.items[:0]
     569           1 :                 return
     570           1 :         }
     571           1 :         m.nextEntry(l, nil /* succKey */)
     572             : }
     573             : 
     574             : // nextEntry unconditionally steps to the next entry. item is the current top
     575             : // item in the heap.
     576             : //
     577             : // nextEntry should be called directly when not in prefix-iteration mode, or by
     578             : // Next.  During prefix iteration mode, all other callers should use
     579             : // maybeNextEntryWithinPrefix which will avoid advancing the iterator if the
     580             : // current iteration prefix has been exhausted. See the comment within
     581             : // nextEntry's body for an explanation of why other callers should call
     582             : // maybeNextEntryWithinPrefix, which will ensure the documented invariant is
     583             : // preserved.
     584           1 : func (m *mergingIter) nextEntry(l *mergingIterLevel, succKey []byte) {
     585           1 :         // INVARIANT: If in prefix iteration mode, item.iterKey must have a prefix equal
     586           1 :         // to m.prefix. This invariant is important for ensuring TrySeekUsingNext
     587           1 :         // optimizations behave correctly.
     588           1 :         //
     589           1 :         // During prefix iteration, the iterator does not have a full view of the
     590           1 :         // LSM. Some level iterators may omit keys that are known to fall outside
     591           1 :         // the seek prefix (eg, due to sstable bloom filter exclusion). It's
     592           1 :         // important that in such cases we don't position any iterators beyond
     593           1 :         // m.prefix, because doing so may interfere with future seeks.
     594           1 :         //
     595           1 :         // Let prefixes P1 < P2 < P3. Imagine a SeekPrefixGE to prefix P1, followed
     596           1 :         // by a SeekPrefixGE to prefix P2. Imagine there exist live keys at prefix
     597           1 :         // P2, but they're not visible to the SeekPrefixGE(P1) (because of
     598           1 :         // bloom-filter exclusion or a range tombstone that deletes prefix P1 but
     599           1 :         // not P2). If the SeekPrefixGE(P1) is allowed to move any level iterators
     600           1 :         // to P3, the SeekPrefixGE(P2, TrySeekUsingNext=true) may mistakenly think
     601           1 :         // the level contains no point keys or range tombstones within the prefix
     602           1 :         // P2. Care is taken to avoid ever advancing the iterator beyond the current
     603           1 :         // prefix. If nextEntry is ever invoked while we're already beyond the
     604           1 :         // current prefix, we're violating the invariant.
     605           1 :         if invariants.Enabled && m.prefix != nil {
     606           0 :                 if s := m.split(l.iterKey.UserKey); !bytes.Equal(m.prefix, l.iterKey.UserKey[:s]) {
     607           0 :                         m.logger.Fatalf("mergingIter: prefix violation: nexting beyond prefix %q; existing heap root %q\n%s",
     608           0 :                                 m.prefix, l.iterKey, debug.Stack())
     609           0 :                 }
     610             :         }
     611             : 
     612           1 :         oldTopLevel := l.index
     613           1 :         oldRangeDelIter := l.rangeDelIter
     614           1 : 
     615           1 :         if succKey == nil {
     616           1 :                 l.iterKey, l.iterValue = l.iter.Next()
     617           1 :         } else {
     618           1 :                 l.iterKey, l.iterValue = l.iter.NextPrefix(succKey)
     619           1 :         }
     620             : 
     621           1 :         if l.iterKey != nil {
     622           1 :                 if m.heap.len() > 1 {
     623           1 :                         m.heap.fix(0)
     624           1 :                 }
     625           1 :                 if l.rangeDelIter != oldRangeDelIter {
     626           1 :                         // The rangeDelIter changed which indicates that the l.iter moved to the
     627           1 :                         // next sstable. We have to update the tombstone for oldTopLevel as well.
     628           1 :                         oldTopLevel--
     629           1 :                 }
     630           1 :         } else {
     631           1 :                 m.err = l.iter.Error()
     632           1 :                 if m.err == nil {
     633           1 :                         m.heap.pop()
     634           1 :                 }
     635             :         }
     636             : 
     637             :         // The cached tombstones are only valid for the levels
     638             :         // [0,oldTopLevel]. Updated the cached tombstones for any levels in the range
     639             :         // [oldTopLevel+1,heap[0].index].
     640           1 :         m.initMinRangeDelIters(oldTopLevel)
     641             : }
     642             : 
     643             : // isNextEntryDeleted starts from the current entry (as the next entry) and if
     644             : // it is deleted, moves the iterators forward as needed and returns true, else
     645             : // it returns false. item is the top item in the heap.
     646             : //
     647             : // During prefix iteration mode, isNextEntryDeleted will exhaust the iterator by
     648             : // clearing the heap if the deleted key(s) extend beyond the iteration prefix
     649             : // during prefix-iteration mode.
     650           1 : func (m *mergingIter) isNextEntryDeleted(item *mergingIterLevel) bool {
     651           1 :         // Look for a range deletion tombstone containing item.iterKey at higher
     652           1 :         // levels (level < item.index). If we find such a range tombstone we know
     653           1 :         // it deletes the key in the current level. Also look for a range
     654           1 :         // deletion at the current level (level == item.index). If we find such a
     655           1 :         // range deletion we need to check whether it is newer than the current
     656           1 :         // entry.
     657           1 :         for level := 0; level <= item.index; level++ {
     658           1 :                 l := &m.levels[level]
     659           1 :                 if l.rangeDelIter == nil || l.tombstone == nil {
     660           1 :                         // If l.tombstone is nil, there are no further tombstones
     661           1 :                         // in the current sstable in the current (forward) iteration
     662           1 :                         // direction.
     663           1 :                         continue
     664             :                 }
     665           1 :                 if m.heap.cmp(l.tombstone.End, item.iterKey.UserKey) <= 0 {
     666           1 :                         // The current key is at or past the tombstone end key.
     667           1 :                         //
     668           1 :                         // NB: for the case that this l.rangeDelIter is provided by a levelIter we know that
     669           1 :                         // the levelIter must be positioned at a key >= item.iterKey. So it is sufficient to seek the
     670           1 :                         // current l.rangeDelIter (since any range del iterators that will be provided by the
     671           1 :                         // levelIter in the future cannot contain item.iterKey). Also, it is possible that we
     672           1 :                         // will encounter parts of the range delete that should be ignored -- we handle that
     673           1 :                         // below.
     674           1 :                         l.tombstone = l.rangeDelIter.SeekGE(item.iterKey.UserKey)
     675           1 :                 }
     676           1 :                 if l.tombstone == nil {
     677           1 :                         continue
     678             :                 }
     679             : 
     680             :                 // Reasoning for correctness of untruncated tombstone handling when the untruncated
     681             :                 // tombstone is at a higher level:
     682             :                 // The iterator corresponding to this tombstone is still in the heap so it must be
     683             :                 // positioned >= item.iterKey. Which means the Largest key bound of the sstable containing this
     684             :                 // tombstone is >= item.iterKey. So the upper limit of this tombstone cannot be file-bounds-constrained
     685             :                 // to < item.iterKey. But it is possible that item.key < smallestUserKey, in which
     686             :                 // case this tombstone should be ignored.
     687             :                 //
     688             :                 // Example 1:
     689             :                 // sstable bounds [c#8, g#12] containing a tombstone [b, i)#7, and key is c#6. The
     690             :                 // smallestUserKey is c, so we know the key is within the file bounds and the tombstone
     691             :                 // [b, i) covers it.
     692             :                 //
     693             :                 // Example 2:
     694             :                 // Same sstable bounds but key is b#10. The smallestUserKey is c, so the tombstone [b, i)
     695             :                 // does not cover this key.
     696             :                 //
     697             :                 // For a tombstone at the same level as the key, the file bounds are trivially satisfied.
     698           1 :                 if (l.smallestUserKey == nil || m.heap.cmp(l.smallestUserKey, item.iterKey.UserKey) <= 0) &&
     699           1 :                         l.tombstone.VisibleAt(m.snapshot) && l.tombstone.Contains(m.heap.cmp, item.iterKey.UserKey) {
     700           1 :                         if level < item.index {
     701           1 :                                 // We could also do m.seekGE(..., level + 1). The levels from
     702           1 :                                 // [level + 1, item.index) are already after item.iterKey so seeking them may be
     703           1 :                                 // wasteful.
     704           1 : 
     705           1 :                                 // We can seek up to the min of largestUserKey and tombstone.End.
     706           1 :                                 //
     707           1 :                                 // Using example 1 above, we can seek to the smaller of g and i, which is g.
     708           1 :                                 //
     709           1 :                                 // Another example, where the sstable bounds are [c#8, i#InternalRangeDelSentinel],
     710           1 :                                 // and the tombstone is [b, i)#8. Seeking to i is correct since it is seeking up to
     711           1 :                                 // the exclusive bound of the tombstone. We do not need to look at
     712           1 :                                 // isLargestKeyRangeDelSentinel.
     713           1 :                                 //
     714           1 :                                 // Progress argument: Since this file is at a higher level than item.iterKey we know
     715           1 :                                 // that the iterator in this file must be positioned within its bounds and at a key
     716           1 :                                 // X > item.iterKey (otherwise it would be the min of the heap). It is not
     717           1 :                                 // possible for X.UserKey == item.iterKey.UserKey, since it is incompatible with
     718           1 :                                 // X > item.iterKey (a lower version cannot be in a higher sstable), so it must be that
     719           1 :                                 // X.UserKey > item.iterKey.UserKey. Which means l.largestUserKey > item.key.UserKey.
     720           1 :                                 // We also know that l.tombstone.End > item.iterKey.UserKey. So the min of these,
     721           1 :                                 // seekKey, computed below, is > item.iterKey.UserKey, so the call to seekGE() will
     722           1 :                                 // make forward progress.
     723           1 :                                 seekKey := l.tombstone.End
     724           1 :                                 if l.largestUserKey != nil && m.heap.cmp(l.largestUserKey, seekKey) < 0 {
     725           0 :                                         seekKey = l.largestUserKey
     726           0 :                                 }
     727             :                                 // This seek is not directly due to a SeekGE call, so we don't know
     728             :                                 // enough about the underlying iterator positions, and so we keep the
     729             :                                 // try-seek-using-next optimization disabled. Additionally, if we're in
     730             :                                 // prefix-seek mode and a re-seek would have moved us past the original
     731             :                                 // prefix, we can remove all merging iter levels below the rangedel
     732             :                                 // tombstone's level and return immediately instead of re-seeking. This
     733             :                                 // is correct since those levels cannot provide a key that matches the
     734             :                                 // prefix, and is also visible. Additionally, this is important to make
     735             :                                 // subsequent `TrySeekUsingNext` work correctly, as a re-seek on a
     736             :                                 // different prefix could have resulted in this iterator skipping visible
     737             :                                 // keys at prefixes in between m.prefix and seekKey, that are currently
     738             :                                 // not in the heap due to a bloom filter mismatch.
     739             :                                 //
     740             :                                 // Additionally, we set the relative-seek flag. This is
     741             :                                 // important when iterating with lazy combined iteration. If
     742             :                                 // there's a range key between this level's current file and the
     743             :                                 // file the seek will land on, we need to detect it in order to
     744             :                                 // trigger construction of the combined iterator.
     745           1 :                                 if m.prefix != nil {
     746           1 :                                         if n := m.split(seekKey); !bytes.Equal(m.prefix, seekKey[:n]) {
     747           1 :                                                 for i := item.index; i < len(m.levels); i++ {
     748           1 :                                                         // Remove this level from the heap. Setting iterKey and iterValue
     749           1 :                                                         // to their zero values should be sufficient for initMinHeap to not
     750           1 :                                                         // re-initialize the heap with them in it. Other fields in
     751           1 :                                                         // mergingIterLevel can remain as-is; the iter/rangeDelIter needs
     752           1 :                                                         // to stay intact for future trySeekUsingNexts to work, the level
     753           1 :                                                         // iter boundary context is owned by the levelIter which is not
     754           1 :                                                         // being repositioned, and any tombstones in these levels will be
     755           1 :                                                         // irrelevant for us anyway.
     756           1 :                                                         m.levels[i].iterKey = nil
     757           1 :                                                         m.levels[i].iterValue = base.LazyValue{}
     758           1 :                                                 }
     759             :                                                 // TODO(bilal): Consider a more efficient way of removing levels from
     760             :                                                 // the heap without reinitializing all of it. This would likely
     761             :                                                 // necessitate tracking the heap positions of each mergingIterHeap
     762             :                                                 // item in the mergingIterLevel, and then swapping that item in the
     763             :                                                 // heap with the last-positioned heap item, and shrinking the heap by
     764             :                                                 // one.
     765           1 :                                                 m.initMinHeap()
     766           1 :                                                 return true
     767             :                                         }
     768             :                                 }
     769           1 :                                 m.seekGE(seekKey, item.index, base.SeekGEFlagsNone.EnableRelativeSeek())
     770           1 :                                 return true
     771             :                         }
     772           1 :                         if l.tombstone.CoversAt(m.snapshot, item.iterKey.SeqNum()) {
     773           1 :                                 if m.prefix == nil {
     774           1 :                                         m.nextEntry(item, nil /* succKey */)
     775           1 :                                 } else {
     776           1 :                                         m.maybeNextEntryWithinPrefix(item)
     777           1 :                                 }
     778           1 :                                 return true
     779             :                         }
     780             :                 }
     781             :         }
     782           1 :         return false
     783             : }
     784             : 
     785             : // Starting from the current entry, finds the first (next) entry that can be returned.
     786           1 : func (m *mergingIter) findNextEntry() (*InternalKey, base.LazyValue) {
     787           1 :         for m.heap.len() > 0 && m.err == nil {
     788           1 :                 item := m.heap.items[0]
     789           1 :                 if m.levels[item.index].isSyntheticIterBoundsKey {
     790           1 :                         break
     791             :                 }
     792             : 
     793           1 :                 m.addItemStats(item)
     794           1 : 
     795           1 :                 // Skip ignorable boundary keys. These are not real keys and exist to
     796           1 :                 // keep sstables open until we've surpassed their end boundaries so that
     797           1 :                 // their range deletions are visible.
     798           1 :                 if m.levels[item.index].isIgnorableBoundaryKey {
     799           1 :                         if m.prefix == nil {
     800           1 :                                 m.nextEntry(item, nil /* succKey */)
     801           1 :                         } else {
     802           1 :                                 m.maybeNextEntryWithinPrefix(item)
     803           1 :                         }
     804           1 :                         continue
     805             :                 }
     806             : 
     807             :                 // Check if the heap root key is deleted by a range tombstone in a
     808             :                 // higher level. If it is, isNextEntryDeleted will advance the iterator
     809             :                 // to a later key (through seeking or nexting).
     810           1 :                 if m.isNextEntryDeleted(item) {
     811           1 :                         m.stats.PointsCoveredByRangeTombstones++
     812           1 :                         continue
     813             :                 }
     814             : 
     815             :                 // Check if the key is visible at the iterator sequence numbers.
     816           1 :                 if !item.iterKey.Visible(m.snapshot, m.batchSnapshot) {
     817           1 :                         if m.prefix == nil {
     818           1 :                                 m.nextEntry(item, nil /* succKey */)
     819           1 :                         } else {
     820           1 :                                 m.maybeNextEntryWithinPrefix(item)
     821           1 :                         }
     822           1 :                         continue
     823             :                 }
     824             : 
     825             :                 // The heap root is visible and not deleted by any range tombstones.
     826             :                 // Return it.
     827           1 :                 return item.iterKey, item.iterValue
     828             :         }
     829           1 :         return nil, base.LazyValue{}
     830             : }
     831             : 
     832             : // Steps to the prev entry. item is the current top item in the heap.
     833           1 : func (m *mergingIter) prevEntry(l *mergingIterLevel) {
     834           1 :         oldTopLevel := l.index
     835           1 :         oldRangeDelIter := l.rangeDelIter
     836           1 :         if l.iterKey, l.iterValue = l.iter.Prev(); l.iterKey != nil {
     837           1 :                 if m.heap.len() > 1 {
     838           1 :                         m.heap.fix(0)
     839           1 :                 }
     840           1 :                 if l.rangeDelIter != oldRangeDelIter && l.rangeDelIter != nil {
     841           1 :                         // The rangeDelIter changed which indicates that the l.iter moved to the
     842           1 :                         // previous sstable. We have to update the tombstone for oldTopLevel as
     843           1 :                         // well.
     844           1 :                         oldTopLevel--
     845           1 :                 }
     846           1 :         } else {
     847           1 :                 m.err = l.iter.Error()
     848           1 :                 if m.err == nil {
     849           1 :                         m.heap.pop()
     850           1 :                 }
     851             :         }
     852             : 
     853             :         // The cached tombstones are only valid for the levels
     854             :         // [0,oldTopLevel]. Updated the cached tombstones for any levels in the range
     855             :         // [oldTopLevel+1,heap[0].index].
     856           1 :         m.initMaxRangeDelIters(oldTopLevel)
     857             : }
     858             : 
     859             : // isPrevEntryDeleted() starts from the current entry (as the prev entry) and if it is deleted,
     860             : // moves the iterators backward as needed and returns true, else it returns false. item is the top
     861             : // item in the heap.
     862           1 : func (m *mergingIter) isPrevEntryDeleted(item *mergingIterLevel) bool {
     863           1 :         // Look for a range deletion tombstone containing item.iterKey at higher
     864           1 :         // levels (level < item.index). If we find such a range tombstone we know
     865           1 :         // it deletes the key in the current level. Also look for a range
     866           1 :         // deletion at the current level (level == item.index). If we find such a
     867           1 :         // range deletion we need to check whether it is newer than the current
     868           1 :         // entry.
     869           1 :         for level := 0; level <= item.index; level++ {
     870           1 :                 l := &m.levels[level]
     871           1 :                 if l.rangeDelIter == nil || l.tombstone == nil {
     872           1 :                         // If l.tombstone is nil, there are no further tombstones
     873           1 :                         // in the current sstable in the current (reverse) iteration
     874           1 :                         // direction.
     875           1 :                         continue
     876             :                 }
     877           1 :                 if m.heap.cmp(item.iterKey.UserKey, l.tombstone.Start) < 0 {
     878           1 :                         // The current key is before the tombstone start key.
     879           1 :                         //
     880           1 :                         // NB: for the case that this l.rangeDelIter is provided by a levelIter we know that
     881           1 :                         // the levelIter must be positioned at a key < item.iterKey. So it is sufficient to seek the
     882           1 :                         // current l.rangeDelIter (since any range del iterators that will be provided by the
     883           1 :                         // levelIter in the future cannot contain item.iterKey). Also, it is it is possible that we
     884           1 :                         // will encounter parts of the range delete that should be ignored -- we handle that
     885           1 :                         // below.
     886           1 :                         l.tombstone = keyspan.SeekLE(m.heap.cmp, l.rangeDelIter, item.iterKey.UserKey)
     887           1 :                 }
     888           1 :                 if l.tombstone == nil {
     889           1 :                         continue
     890             :                 }
     891             : 
     892             :                 // Reasoning for correctness of untruncated tombstone handling when the untruncated
     893             :                 // tombstone is at a higher level:
     894             :                 //
     895             :                 // The iterator corresponding to this tombstone is still in the heap so it must be
     896             :                 // positioned <= item.iterKey. Which means the Smallest key bound of the sstable containing this
     897             :                 // tombstone is <= item.iterKey. So the lower limit of this tombstone cannot have been
     898             :                 // file-bounds-constrained to > item.iterKey. But it is possible that item.key >= Largest
     899             :                 // key bound of this sstable, in which case this tombstone should be ignored.
     900             :                 //
     901             :                 // Example 1:
     902             :                 // sstable bounds [c#8, g#12] containing a tombstone [b, i)#7, and key is f#6. The
     903             :                 // largestUserKey is g, so we know the key is within the file bounds and the tombstone
     904             :                 // [b, i) covers it.
     905             :                 //
     906             :                 // Example 2:
     907             :                 // Same sstable but the key is g#6. This cannot happen since the [b, i)#7 untruncated
     908             :                 // tombstone was involved in a compaction which must have had a file to the right of this
     909             :                 // sstable that is part of the same atomic compaction group for future compactions. That
     910             :                 // file must have bounds that cover g#6 and this levelIter must be at that file.
     911             :                 //
     912             :                 // Example 3:
     913             :                 // sstable bounds [c#8, g#RangeDelSentinel] containing [b, i)#7 and the key is g#10.
     914             :                 // This key is not deleted by this tombstone. We need to look at
     915             :                 // isLargestUserKeyExclusive.
     916             :                 //
     917             :                 // For a tombstone at the same level as the key, the file bounds are trivially satisfied.
     918             : 
     919             :                 // Default to within bounds.
     920           1 :                 withinLargestSSTableBound := true
     921           1 :                 if l.largestUserKey != nil {
     922           1 :                         cmpResult := m.heap.cmp(l.largestUserKey, item.iterKey.UserKey)
     923           1 :                         withinLargestSSTableBound = cmpResult > 0 || (cmpResult == 0 && !l.isLargestUserKeyExclusive)
     924           1 :                 }
     925           1 :                 if withinLargestSSTableBound && l.tombstone.Contains(m.heap.cmp, item.iterKey.UserKey) && l.tombstone.VisibleAt(m.snapshot) {
     926           1 :                         if level < item.index {
     927           1 :                                 // We could also do m.seekLT(..., level + 1). The levels from
     928           1 :                                 // [level + 1, item.index) are already before item.iterKey so seeking them may be
     929           1 :                                 // wasteful.
     930           1 : 
     931           1 :                                 // We can seek up to the max of smallestUserKey and tombstone.Start.UserKey.
     932           1 :                                 //
     933           1 :                                 // Using example 1 above, we can seek to the larger of c and b, which is c.
     934           1 :                                 //
     935           1 :                                 // Progress argument: We know that the iterator in this file is positioned within
     936           1 :                                 // its bounds and at a key X < item.iterKey (otherwise it would be the max of the heap).
     937           1 :                                 // So smallestUserKey <= item.iterKey.UserKey and we already know that
     938           1 :                                 // l.tombstone.Start.UserKey <= item.iterKey.UserKey. So the seekKey computed below
     939           1 :                                 // is <= item.iterKey.UserKey, and since we do a seekLT() we will make backwards
     940           1 :                                 // progress.
     941           1 :                                 seekKey := l.tombstone.Start
     942           1 :                                 if l.smallestUserKey != nil && m.heap.cmp(l.smallestUserKey, seekKey) > 0 {
     943           0 :                                         seekKey = l.smallestUserKey
     944           0 :                                 }
     945             :                                 // We set the relative-seek flag. This is important when
     946             :                                 // iterating with lazy combined iteration. If there's a range
     947             :                                 // key between this level's current file and the file the seek
     948             :                                 // will land on, we need to detect it in order to trigger
     949             :                                 // construction of the combined iterator.
     950           1 :                                 m.seekLT(seekKey, item.index, base.SeekLTFlagsNone.EnableRelativeSeek())
     951           1 :                                 return true
     952             :                         }
     953           1 :                         if l.tombstone.CoversAt(m.snapshot, item.iterKey.SeqNum()) {
     954           1 :                                 m.prevEntry(item)
     955           1 :                                 return true
     956           1 :                         }
     957             :                 }
     958             :         }
     959           1 :         return false
     960             : }
     961             : 
     962             : // Starting from the current entry, finds the first (prev) entry that can be returned.
     963           1 : func (m *mergingIter) findPrevEntry() (*InternalKey, base.LazyValue) {
     964           1 :         for m.heap.len() > 0 && m.err == nil {
     965           1 :                 item := m.heap.items[0]
     966           1 :                 if m.levels[item.index].isSyntheticIterBoundsKey {
     967           1 :                         break
     968             :                 }
     969           1 :                 m.addItemStats(item)
     970           1 :                 if m.isPrevEntryDeleted(item) {
     971           1 :                         m.stats.PointsCoveredByRangeTombstones++
     972           1 :                         continue
     973             :                 }
     974           1 :                 if item.iterKey.Visible(m.snapshot, m.batchSnapshot) &&
     975           1 :                         (!m.levels[item.index].isIgnorableBoundaryKey) {
     976           1 :                         return item.iterKey, item.iterValue
     977           1 :                 }
     978           1 :                 m.prevEntry(item)
     979             :         }
     980           1 :         return nil, base.LazyValue{}
     981             : }
     982             : 
     983             : // Seeks levels >= level to >= key. Additionally uses range tombstones to extend the seeks.
     984           1 : func (m *mergingIter) seekGE(key []byte, level int, flags base.SeekGEFlags) {
     985           1 :         // When seeking, we can use tombstones to adjust the key we seek to on each
     986           1 :         // level. Consider the series of range tombstones:
     987           1 :         //
     988           1 :         //   1: a---e
     989           1 :         //   2:    d---h
     990           1 :         //   3:       g---k
     991           1 :         //   4:          j---n
     992           1 :         //   5:             m---q
     993           1 :         //
     994           1 :         // If we SeekGE("b") we also find the tombstone "b" resides within in the
     995           1 :         // first level which is [a,e). Regardless of whether this tombstone deletes
     996           1 :         // "b" in that level, we know it deletes "b" in all lower levels, so we
     997           1 :         // adjust the search key in the next level to the tombstone end key "e". We
     998           1 :         // then SeekGE("e") in the second level and find the corresponding tombstone
     999           1 :         // [d,h). This process continues and we end up seeking for "h" in the 3rd
    1000           1 :         // level, "k" in the 4th level and "n" in the last level.
    1001           1 :         //
    1002           1 :         // TODO(peter,rangedel): In addition to the above we can delay seeking a
    1003           1 :         // level (and any lower levels) when the current iterator position is
    1004           1 :         // contained within a range tombstone at a higher level.
    1005           1 : 
    1006           1 :         // Deterministically disable the TrySeekUsingNext optimizations sometimes in
    1007           1 :         // invariant builds to encourage the metamorphic tests to surface bugs. Note
    1008           1 :         // that we cannot disable the optimization within individual levels. It must
    1009           1 :         // be disabled for all levels or none. If one lower-level iterator performs
    1010           1 :         // a fresh seek whereas another takes advantage of its current iterator
    1011           1 :         // position, the heap can become inconsistent. Consider the following
    1012           1 :         // example:
    1013           1 :         //
    1014           1 :         //     L5:  [ [b-c) ]  [ d ]*
    1015           1 :         //     L6:  [  b ]           [e]*
    1016           1 :         //
    1017           1 :         // Imagine a SeekGE(a). The [b-c) range tombstone deletes the L6 point key
    1018           1 :         // 'b', resulting in the iterator positioned at d with the heap:
    1019           1 :         //
    1020           1 :         //     {L5: d, L6: e}
    1021           1 :         //
    1022           1 :         // A subsequent SeekGE(b) is seeking to a larger key, so the caller may set
    1023           1 :         // TrySeekUsingNext()=true. If the L5 iterator used the TrySeekUsingNext
    1024           1 :         // optimization but the L6 iterator did not, the iterator would have the
    1025           1 :         // heap:
    1026           1 :         //
    1027           1 :         //     {L6: b, L5: d}
    1028           1 :         //
    1029           1 :         // Because the L5 iterator has already advanced to the next sstable, the
    1030           1 :         // merging iterator cannot observe the [b-c) range tombstone and will
    1031           1 :         // mistakenly return L6's deleted point key 'b'.
    1032           1 :         if invariants.Enabled && flags.TrySeekUsingNext() && !m.forceEnableSeekOpt &&
    1033           1 :                 disableSeekOpt(key, uintptr(unsafe.Pointer(m))) {
    1034           0 :                 flags = flags.DisableTrySeekUsingNext()
    1035           0 :         }
    1036             : 
    1037           1 :         for ; level < len(m.levels); level++ {
    1038           1 :                 if invariants.Enabled && m.lower != nil && m.heap.cmp(key, m.lower) < 0 {
    1039           0 :                         m.logger.Fatalf("mergingIter: lower bound violation: %s < %s\n%s", key, m.lower, debug.Stack())
    1040           0 :                 }
    1041             : 
    1042           1 :                 l := &m.levels[level]
    1043           1 :                 if m.prefix != nil {
    1044           1 :                         l.iterKey, l.iterValue = l.iter.SeekPrefixGE(m.prefix, key, flags)
    1045           1 :                 } else {
    1046           1 :                         l.iterKey, l.iterValue = l.iter.SeekGE(key, flags)
    1047           1 :                 }
    1048             : 
    1049             :                 // If this level contains overlapping range tombstones, alter the seek
    1050             :                 // key accordingly. Caveat: If we're performing lazy-combined iteration,
    1051             :                 // we cannot alter the seek key: Range tombstones don't delete range
    1052             :                 // keys, and there might exist live range keys within the range
    1053             :                 // tombstone's span that need to be observed to trigger a switch to
    1054             :                 // combined iteration.
    1055           1 :                 if rangeDelIter := l.rangeDelIter; rangeDelIter != nil &&
    1056           1 :                         (m.combinedIterState == nil || m.combinedIterState.initialized) {
    1057           1 :                         // The level has a range-del iterator. Find the tombstone containing
    1058           1 :                         // the search key.
    1059           1 :                         //
    1060           1 :                         // For untruncated tombstones that are possibly file-bounds-constrained, we are using a
    1061           1 :                         // levelIter which will set smallestUserKey and largestUserKey. Since the levelIter
    1062           1 :                         // is at this file we know that largestUserKey >= key, so we know that the
    1063           1 :                         // tombstone we find cannot be file-bounds-constrained in its upper bound to something < key.
    1064           1 :                         // We do need to  compare with smallestUserKey to ensure that the tombstone is not
    1065           1 :                         // file-bounds-constrained in its lower bound.
    1066           1 :                         //
    1067           1 :                         // See the detailed comments in isNextEntryDeleted() on why similar containment and
    1068           1 :                         // seeking logic is correct. The subtle difference here is that key is a user key,
    1069           1 :                         // so we can have a sstable with bounds [c#8, i#InternalRangeDelSentinel], and the
    1070           1 :                         // tombstone is [b, k)#8 and the seek key is i: levelIter.SeekGE(i) will move past
    1071           1 :                         // this sstable since it realizes the largest key is a InternalRangeDelSentinel.
    1072           1 :                         l.tombstone = rangeDelIter.SeekGE(key)
    1073           1 :                         if l.tombstone != nil && l.tombstone.VisibleAt(m.snapshot) && l.tombstone.Contains(m.heap.cmp, key) &&
    1074           1 :                                 (l.smallestUserKey == nil || m.heap.cmp(l.smallestUserKey, key) <= 0) {
    1075           1 :                                 // NB: Based on the comment above l.largestUserKey >= key, and based on the
    1076           1 :                                 // containment condition tombstone.End > key, so the assignment to key results
    1077           1 :                                 // in a monotonically non-decreasing key across iterations of this loop.
    1078           1 :                                 //
    1079           1 :                                 // The adjustment of key here can only move it to a larger key. Since
    1080           1 :                                 // the caller of seekGE guaranteed that the original key was greater
    1081           1 :                                 // than or equal to m.lower, the new key will continue to be greater
    1082           1 :                                 // than or equal to m.lower.
    1083           1 :                                 if l.largestUserKey != nil &&
    1084           1 :                                         m.heap.cmp(l.largestUserKey, l.tombstone.End) < 0 {
    1085           0 :                                         // Truncate the tombstone for seeking purposes. Note that this can over-truncate
    1086           0 :                                         // but that is harmless for this seek optimization.
    1087           0 :                                         key = l.largestUserKey
    1088           1 :                                 } else {
    1089           1 :                                         key = l.tombstone.End
    1090           1 :                                 }
    1091             :                         }
    1092             :                 }
    1093             :         }
    1094             : 
    1095           1 :         m.initMinHeap()
    1096             : }
    1097             : 
    1098           0 : func (m *mergingIter) String() string {
    1099           0 :         return "merging"
    1100           0 : }
    1101             : 
    1102             : // SeekGE implements base.InternalIterator.SeekGE. Note that SeekGE only checks
    1103             : // the upper bound. It is up to the caller to ensure that key is greater than
    1104             : // or equal to the lower bound.
    1105           1 : func (m *mergingIter) SeekGE(key []byte, flags base.SeekGEFlags) (*InternalKey, base.LazyValue) {
    1106           1 :         m.err = nil // clear cached iteration error
    1107           1 :         m.prefix = nil
    1108           1 :         m.seekGE(key, 0 /* start level */, flags)
    1109           1 :         return m.findNextEntry()
    1110           1 : }
    1111             : 
    1112             : // SeekPrefixGE implements base.InternalIterator.SeekPrefixGE. Note that
    1113             : // SeekPrefixGE only checks the upper bound. It is up to the caller to ensure
    1114             : // that key is greater than or equal to the lower bound.
    1115             : func (m *mergingIter) SeekPrefixGE(
    1116             :         prefix, key []byte, flags base.SeekGEFlags,
    1117           1 : ) (*base.InternalKey, base.LazyValue) {
    1118           1 :         m.err = nil // clear cached iteration error
    1119           1 :         m.prefix = prefix
    1120           1 :         m.seekGE(key, 0 /* start level */, flags)
    1121           1 :         return m.findNextEntry()
    1122           1 : }
    1123             : 
    1124             : // Seeks levels >= level to < key. Additionally uses range tombstones to extend the seeks.
    1125           1 : func (m *mergingIter) seekLT(key []byte, level int, flags base.SeekLTFlags) {
    1126           1 :         // See the comment in seekGE regarding using tombstones to adjust the seek
    1127           1 :         // target per level.
    1128           1 :         m.prefix = nil
    1129           1 :         for ; level < len(m.levels); level++ {
    1130           1 :                 if invariants.Enabled && m.upper != nil && m.heap.cmp(key, m.upper) > 0 {
    1131           0 :                         m.logger.Fatalf("mergingIter: upper bound violation: %s > %s\n%s", key, m.upper, debug.Stack())
    1132           0 :                 }
    1133             : 
    1134           1 :                 l := &m.levels[level]
    1135           1 :                 l.iterKey, l.iterValue = l.iter.SeekLT(key, flags)
    1136           1 : 
    1137           1 :                 // If this level contains overlapping range tombstones, alter the seek
    1138           1 :                 // key accordingly. Caveat: If we're performing lazy-combined iteration,
    1139           1 :                 // we cannot alter the seek key: Range tombstones don't delete range
    1140           1 :                 // keys, and there might exist live range keys within the range
    1141           1 :                 // tombstone's span that need to be observed to trigger a switch to
    1142           1 :                 // combined iteration.
    1143           1 :                 if rangeDelIter := l.rangeDelIter; rangeDelIter != nil &&
    1144           1 :                         (m.combinedIterState == nil || m.combinedIterState.initialized) {
    1145           1 :                         // The level has a range-del iterator. Find the tombstone containing
    1146           1 :                         // the search key.
    1147           1 :                         //
    1148           1 :                         // For untruncated tombstones that are possibly file-bounds-constrained we are using a
    1149           1 :                         // levelIter which will set smallestUserKey and largestUserKey. Since the levelIter
    1150           1 :                         // is at this file we know that smallestUserKey <= key, so we know that the
    1151           1 :                         // tombstone we find cannot be file-bounds-constrained in its lower bound to something > key.
    1152           1 :                         // We do need to  compare with largestUserKey to ensure that the tombstone is not
    1153           1 :                         // file-bounds-constrained in its upper bound.
    1154           1 :                         //
    1155           1 :                         // See the detailed comments in isPrevEntryDeleted() on why similar containment and
    1156           1 :                         // seeking logic is correct.
    1157           1 : 
    1158           1 :                         // Default to within bounds.
    1159           1 :                         withinLargestSSTableBound := true
    1160           1 :                         if l.largestUserKey != nil {
    1161           1 :                                 cmpResult := m.heap.cmp(l.largestUserKey, key)
    1162           1 :                                 withinLargestSSTableBound = cmpResult > 0 || (cmpResult == 0 && !l.isLargestUserKeyExclusive)
    1163           1 :                         }
    1164             : 
    1165           1 :                         l.tombstone = keyspan.SeekLE(m.heap.cmp, rangeDelIter, key)
    1166           1 :                         if l.tombstone != nil && l.tombstone.VisibleAt(m.snapshot) &&
    1167           1 :                                 l.tombstone.Contains(m.heap.cmp, key) && withinLargestSSTableBound {
    1168           1 :                                 // NB: Based on the comment above l.smallestUserKey <= key, and based
    1169           1 :                                 // on the containment condition tombstone.Start.UserKey <= key, so the
    1170           1 :                                 // assignment to key results in a monotonically non-increasing key
    1171           1 :                                 // across iterations of this loop.
    1172           1 :                                 //
    1173           1 :                                 // The adjustment of key here can only move it to a smaller key. Since
    1174           1 :                                 // the caller of seekLT guaranteed that the original key was less than
    1175           1 :                                 // or equal to m.upper, the new key will continue to be less than or
    1176           1 :                                 // equal to m.upper.
    1177           1 :                                 if l.smallestUserKey != nil &&
    1178           1 :                                         m.heap.cmp(l.smallestUserKey, l.tombstone.Start) >= 0 {
    1179           1 :                                         // Truncate the tombstone for seeking purposes. Note that this can over-truncate
    1180           1 :                                         // but that is harmless for this seek optimization.
    1181           1 :                                         key = l.smallestUserKey
    1182           1 :                                 } else {
    1183           1 :                                         key = l.tombstone.Start
    1184           1 :                                 }
    1185             :                         }
    1186             :                 }
    1187             :         }
    1188             : 
    1189           1 :         m.initMaxHeap()
    1190             : }
    1191             : 
    1192             : // SeekLT implements base.InternalIterator.SeekLT. Note that SeekLT only checks
    1193             : // the lower bound. It is up to the caller to ensure that key is less than the
    1194             : // upper bound.
    1195           1 : func (m *mergingIter) SeekLT(key []byte, flags base.SeekLTFlags) (*InternalKey, base.LazyValue) {
    1196           1 :         m.err = nil // clear cached iteration error
    1197           1 :         m.prefix = nil
    1198           1 :         m.seekLT(key, 0 /* start level */, flags)
    1199           1 :         return m.findPrevEntry()
    1200           1 : }
    1201             : 
    1202             : // First implements base.InternalIterator.First. Note that First only checks
    1203             : // the upper bound. It is up to the caller to ensure that key is greater than
    1204             : // or equal to the lower bound (e.g. via a call to SeekGE(lower)).
    1205           1 : func (m *mergingIter) First() (*InternalKey, base.LazyValue) {
    1206           1 :         m.err = nil // clear cached iteration error
    1207           1 :         m.prefix = nil
    1208           1 :         m.heap.items = m.heap.items[:0]
    1209           1 :         for i := range m.levels {
    1210           1 :                 l := &m.levels[i]
    1211           1 :                 l.iterKey, l.iterValue = l.iter.First()
    1212           1 :         }
    1213           1 :         m.initMinHeap()
    1214           1 :         return m.findNextEntry()
    1215             : }
    1216             : 
    1217             : // Last implements base.InternalIterator.Last. Note that Last only checks the
    1218             : // lower bound. It is up to the caller to ensure that key is less than the
    1219             : // upper bound (e.g. via a call to SeekLT(upper))
    1220           1 : func (m *mergingIter) Last() (*InternalKey, base.LazyValue) {
    1221           1 :         m.err = nil // clear cached iteration error
    1222           1 :         m.prefix = nil
    1223           1 :         for i := range m.levels {
    1224           1 :                 l := &m.levels[i]
    1225           1 :                 l.iterKey, l.iterValue = l.iter.Last()
    1226           1 :         }
    1227           1 :         m.initMaxHeap()
    1228           1 :         return m.findPrevEntry()
    1229             : }
    1230             : 
    1231           1 : func (m *mergingIter) Next() (*InternalKey, base.LazyValue) {
    1232           1 :         if m.err != nil {
    1233           0 :                 return nil, base.LazyValue{}
    1234           0 :         }
    1235             : 
    1236           1 :         if m.dir != 1 {
    1237           1 :                 m.switchToMinHeap()
    1238           1 :                 return m.findNextEntry()
    1239           1 :         }
    1240             : 
    1241           1 :         if m.heap.len() == 0 {
    1242           0 :                 return nil, base.LazyValue{}
    1243           0 :         }
    1244             : 
    1245             :         // NB: It's okay to call nextEntry directly even during prefix iteration
    1246             :         // mode (as opposed to indirectly through maybeNextEntryWithinPrefix).
    1247             :         // During prefix iteration mode, we rely on the caller to not call Next if
    1248             :         // the iterator has already advanced beyond the iteration prefix. See the
    1249             :         // comment above the base.InternalIterator interface.
    1250           1 :         m.nextEntry(m.heap.items[0], nil /* succKey */)
    1251           1 :         return m.findNextEntry()
    1252             : }
    1253             : 
    1254           1 : func (m *mergingIter) NextPrefix(succKey []byte) (*InternalKey, LazyValue) {
    1255           1 :         if m.dir != 1 {
    1256           0 :                 panic("pebble: cannot switch directions with NextPrefix")
    1257             :         }
    1258           1 :         if m.err != nil || m.heap.len() == 0 {
    1259           0 :                 return nil, LazyValue{}
    1260           0 :         }
    1261           1 :         if m.levelsPositioned == nil {
    1262           1 :                 m.levelsPositioned = make([]bool, len(m.levels))
    1263           1 :         } else {
    1264           1 :                 for i := range m.levelsPositioned {
    1265           1 :                         m.levelsPositioned[i] = false
    1266           1 :                 }
    1267             :         }
    1268             : 
    1269             :         // The heap root necessarily must be positioned at a key < succKey, because
    1270             :         // NextPrefix was invoked.
    1271           1 :         root := &m.heap.items[0]
    1272           1 :         m.levelsPositioned[(*root).index] = true
    1273           1 :         if invariants.Enabled && m.heap.cmp((*root).iterKey.UserKey, succKey) >= 0 {
    1274           0 :                 m.logger.Fatalf("pebble: invariant violation: NextPrefix(%q) called on merging iterator already positioned at %q",
    1275           0 :                         succKey, (*root).iterKey)
    1276           0 :         }
    1277           1 :         m.nextEntry(*root, succKey)
    1278           1 :         // NB: root is a pointer to the heap root. nextEntry may have changed
    1279           1 :         // the heap root, so we must not expect root to still point to the same
    1280           1 :         // level (or to even be valid, if the heap is now exhaused).
    1281           1 : 
    1282           1 :         for m.heap.len() > 0 {
    1283           1 :                 if m.levelsPositioned[(*root).index] {
    1284           1 :                         // A level we've previously positioned is at the top of the heap, so
    1285           1 :                         // there are no other levels positioned at keys < succKey. We've
    1286           1 :                         // advanced as far as we need to.
    1287           1 :                         break
    1288             :                 }
    1289             :                 // Since this level was not the original heap root when NextPrefix was
    1290             :                 // called, we don't know whether this level's current key has the
    1291             :                 // previous prefix or a new one.
    1292           1 :                 if m.heap.cmp((*root).iterKey.UserKey, succKey) >= 0 {
    1293           1 :                         break
    1294             :                 }
    1295           1 :                 m.levelsPositioned[(*root).index] = true
    1296           1 :                 m.nextEntry(*root, succKey)
    1297             :         }
    1298           1 :         return m.findNextEntry()
    1299             : }
    1300             : 
    1301           1 : func (m *mergingIter) Prev() (*InternalKey, base.LazyValue) {
    1302           1 :         if m.err != nil {
    1303           0 :                 return nil, base.LazyValue{}
    1304           0 :         }
    1305             : 
    1306           1 :         if m.dir != -1 {
    1307           1 :                 if m.prefix != nil {
    1308           0 :                         m.err = errors.New("pebble: unsupported reverse prefix iteration")
    1309           0 :                         return nil, base.LazyValue{}
    1310           0 :                 }
    1311           1 :                 m.switchToMaxHeap()
    1312           1 :                 return m.findPrevEntry()
    1313             :         }
    1314             : 
    1315           1 :         if m.heap.len() == 0 {
    1316           0 :                 return nil, base.LazyValue{}
    1317           0 :         }
    1318             : 
    1319           1 :         m.prevEntry(m.heap.items[0])
    1320           1 :         return m.findPrevEntry()
    1321             : }
    1322             : 
    1323           1 : func (m *mergingIter) Error() error {
    1324           1 :         if m.heap.len() == 0 || m.err != nil {
    1325           1 :                 return m.err
    1326           1 :         }
    1327           1 :         return m.levels[m.heap.items[0].index].iter.Error()
    1328             : }
    1329             : 
    1330           1 : func (m *mergingIter) Close() error {
    1331           1 :         for i := range m.levels {
    1332           1 :                 iter := m.levels[i].iter
    1333           1 :                 if err := iter.Close(); err != nil && m.err == nil {
    1334           0 :                         m.err = err
    1335           0 :                 }
    1336           1 :                 if rangeDelIter := m.levels[i].rangeDelIter; rangeDelIter != nil {
    1337           1 :                         if err := rangeDelIter.Close(); err != nil && m.err == nil {
    1338           0 :                                 m.err = err
    1339           0 :                         }
    1340             :                 }
    1341             :         }
    1342           1 :         m.levels = nil
    1343           1 :         m.heap.items = m.heap.items[:0]
    1344           1 :         return m.err
    1345             : }
    1346             : 
    1347           1 : func (m *mergingIter) SetBounds(lower, upper []byte) {
    1348           1 :         m.prefix = nil
    1349           1 :         m.lower = lower
    1350           1 :         m.upper = upper
    1351           1 :         for i := range m.levels {
    1352           1 :                 m.levels[i].iter.SetBounds(lower, upper)
    1353           1 :         }
    1354           1 :         m.heap.clear()
    1355             : }
    1356             : 
    1357           0 : func (m *mergingIter) DebugString() string {
    1358           0 :         var buf bytes.Buffer
    1359           0 :         sep := ""
    1360           0 :         for m.heap.len() > 0 {
    1361           0 :                 item := m.heap.pop()
    1362           0 :                 fmt.Fprintf(&buf, "%s%s", sep, item.iterKey)
    1363           0 :                 sep = " "
    1364           0 :         }
    1365           0 :         if m.dir == 1 {
    1366           0 :                 m.initMinHeap()
    1367           0 :         } else {
    1368           0 :                 m.initMaxHeap()
    1369           0 :         }
    1370           0 :         return buf.String()
    1371             : }
    1372             : 
    1373           1 : func (m *mergingIter) ForEachLevelIter(fn func(li *levelIter) bool) {
    1374           1 :         for _, iter := range m.levels {
    1375           1 :                 if li, ok := iter.iter.(*levelIter); ok {
    1376           1 :                         if done := fn(li); done {
    1377           1 :                                 break
    1378             :                         }
    1379             :                 }
    1380             :         }
    1381             : }
    1382             : 
    1383           1 : func (m *mergingIter) addItemStats(l *mergingIterLevel) {
    1384           1 :         m.stats.PointCount++
    1385           1 :         m.stats.KeyBytes += uint64(len(l.iterKey.UserKey))
    1386           1 :         m.stats.ValueBytes += uint64(len(l.iterValue.ValueOrHandle))
    1387           1 : }
    1388             : 
    1389             : var _ internalIterator = &mergingIter{}

Generated by: LCOV version 1.14