LCOV - code coverage report
Current view: top level - pebble - scan_internal.go (source / functions) Coverage Total Hit
Test: 2025-02-28 08:17Z 9af14eed - tests only.lcov Lines: 83.9 % 728 611
Test Date: 2025-02-28 08:18:08 Functions: - 0 0

            Line data    Source code
       1              : // Copyright 2023 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              :         "context"
       9              :         "fmt"
      10              :         "slices"
      11              : 
      12              :         "github.com/cockroachdb/errors"
      13              :         "github.com/cockroachdb/pebble/internal/base"
      14              :         "github.com/cockroachdb/pebble/internal/invariants"
      15              :         "github.com/cockroachdb/pebble/internal/keyspan"
      16              :         "github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
      17              :         "github.com/cockroachdb/pebble/internal/manifest"
      18              :         "github.com/cockroachdb/pebble/internal/treeprinter"
      19              :         "github.com/cockroachdb/pebble/objstorage"
      20              :         "github.com/cockroachdb/pebble/objstorage/remote"
      21              :         "github.com/cockroachdb/pebble/sstable/block"
      22              : )
      23              : 
      24              : const (
      25              :         // In skip-shared iteration mode, keys in levels greater than
      26              :         // sharedLevelsStart (i.e. lower in the LSM) are skipped. Keys
      27              :         // in sharedLevelsStart are returned iff they are not in a
      28              :         // shared file.
      29              :         sharedLevelsStart = remote.SharedLevelsStart
      30              : 
      31              :         // In skip-external iteration mode, keys in levels greater
      32              :         // than externalSkipStart are skipped. Keys in
      33              :         // externalSkipStart are returned iff they are not in an
      34              :         // external file.
      35              :         externalSkipStart = 6
      36              : )
      37              : 
      38              : // ErrInvalidSkipSharedIteration is returned by ScanInternal if it was called
      39              : // with a shared file visitor function, and a file in a shareable level (i.e.
      40              : // level >= sharedLevelsStart) was found to not be in shared storage according
      41              : // to objstorage.Provider, or not shareable for another reason such as for
      42              : // containing keys newer than the snapshot sequence number.
      43              : var ErrInvalidSkipSharedIteration = errors.New("pebble: cannot use skip-shared iteration due to non-shareable files in lower levels")
      44              : 
      45              : // SharedSSTMeta represents an sstable on shared storage that can be ingested
      46              : // by another pebble instance. This struct must contain all fields that are
      47              : // required for a Pebble instance to ingest a foreign sstable on shared storage,
      48              : // including constructing any relevant objstorage.Provider / remoteobjcat.Catalog
      49              : // data structures, as well as creating virtual TableMetadatas.
      50              : //
      51              : // Note that the Pebble instance creating and returning a SharedSSTMeta might
      52              : // not be the one that created the underlying sstable on shared storage to begin
      53              : // with; it's possible for a Pebble instance to reshare an sstable that was
      54              : // shared to it.
      55              : type SharedSSTMeta struct {
      56              :         // Backing is the shared object underlying this SST. Can be attached to an
      57              :         // objstorage.Provider.
      58              :         Backing objstorage.RemoteObjectBackingHandle
      59              : 
      60              :         // Smallest and Largest internal keys for the overall bounds. The kind and
      61              :         // SeqNum of these will reflect what is physically present on the source Pebble
      62              :         // instance's view of the sstable; it's up to the ingesting instance to set the
      63              :         // sequence number in the trailer to match the read-time sequence numbers
      64              :         // reserved for the level this SST is being ingested into. The Kind is expected
      65              :         // to remain unchanged by the ingesting instance.
      66              :         //
      67              :         // Note that these bounds could be narrower than the bounds of the underlying
      68              :         // sstable; ScanInternal is expected to truncate sstable bounds to the user key
      69              :         // bounds passed into that method.
      70              :         Smallest, Largest InternalKey
      71              : 
      72              :         // SmallestRangeKey and LargestRangeKey are internal keys that denote the
      73              :         // range key bounds of this sstable. Must lie within [Smallest, Largest].
      74              :         SmallestRangeKey, LargestRangeKey InternalKey
      75              : 
      76              :         // SmallestPointKey and LargestPointKey are internal keys that denote the
      77              :         // point key bounds of this sstable. Must lie within [Smallest, Largest].
      78              :         SmallestPointKey, LargestPointKey InternalKey
      79              : 
      80              :         // Level denotes the level at which this file was present at read time.
      81              :         // For files visited by ScanInternal, this value will only be 5 or 6.
      82              :         Level uint8
      83              : 
      84              :         // Size contains an estimate of the size of this sstable.
      85              :         Size uint64
      86              : 
      87              :         // fileNum at time of creation in the creator instance. Only used for
      88              :         // debugging/tests.
      89              :         fileNum base.FileNum
      90              : }
      91              : 
      92            1 : func (s *SharedSSTMeta) cloneFromFileMeta(f *tableMetadata) {
      93            1 :         *s = SharedSSTMeta{
      94            1 :                 Smallest:         f.Smallest.Clone(),
      95            1 :                 Largest:          f.Largest.Clone(),
      96            1 :                 SmallestRangeKey: f.SmallestRangeKey.Clone(),
      97            1 :                 LargestRangeKey:  f.LargestRangeKey.Clone(),
      98            1 :                 SmallestPointKey: f.SmallestPointKey.Clone(),
      99            1 :                 LargestPointKey:  f.LargestPointKey.Clone(),
     100            1 :                 Size:             f.Size,
     101            1 :                 fileNum:          f.FileNum,
     102            1 :         }
     103            1 : }
     104              : 
     105              : type sharedByLevel []SharedSSTMeta
     106              : 
     107            1 : func (s sharedByLevel) Len() int           { return len(s) }
     108            0 : func (s sharedByLevel) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
     109            1 : func (s sharedByLevel) Less(i, j int) bool { return s[i].Level < s[j].Level }
     110              : 
     111              : type pcIterPos int
     112              : 
     113              : const (
     114              :         pcIterPosCur pcIterPos = iota
     115              :         pcIterPosNext
     116              : )
     117              : 
     118              : // pointCollapsingIterator is an internalIterator that collapses point keys and
     119              : // returns at most one point internal key for each user key. Merges and
     120              : // SingleDels are not supported and result in a panic if encountered. Point keys
     121              : // deleted by rangedels are considered shadowed and not exposed.
     122              : //
     123              : // Only used in ScanInternal to return at most one internal key per user key.
     124              : type pointCollapsingIterator struct {
     125              :         iter     keyspan.InterleavingIter
     126              :         pos      pcIterPos
     127              :         comparer *base.Comparer
     128              :         merge    base.Merge
     129              :         err      error
     130              :         seqNum   base.SeqNum
     131              :         // The current position of `iter`. Always owned by the underlying iter.
     132              :         iterKV *base.InternalKV
     133              :         // The last saved key. findNextEntry and similar methods are expected to save
     134              :         // the current value of iterKey to savedKey if they're iterating away from the
     135              :         // current key but still need to retain it. See comments in findNextEntry on
     136              :         // how this field is used.
     137              :         //
     138              :         // At the end of a positioning call:
     139              :         //  - if pos == pcIterPosNext, iterKey is pointing to the next user key owned
     140              :         //    by `iter` while savedKey is holding a copy to our current key.
     141              :         //  - If pos == pcIterPosCur, iterKey is pointing to an `iter`-owned current
     142              :         //    key, and savedKey is either undefined or pointing to a version of the
     143              :         //    current key owned by this iterator (i.e. backed by savedKeyBuf).
     144              :         savedKey    InternalKey
     145              :         savedKeyBuf []byte
     146              :         // If fixedSeqNum is non-zero, all emitted points are verified to have this
     147              :         // fixed sequence number.
     148              :         fixedSeqNum base.SeqNum
     149              : }
     150              : 
     151            1 : func (p *pointCollapsingIterator) Span() *keyspan.Span {
     152            1 :         return p.iter.Span()
     153            1 : }
     154              : 
     155              : // SeekPrefixGE implements the InternalIterator interface.
     156              : func (p *pointCollapsingIterator) SeekPrefixGE(
     157              :         prefix, key []byte, flags base.SeekGEFlags,
     158            0 : ) *base.InternalKV {
     159            0 :         p.resetKey()
     160            0 :         p.iterKV = p.iter.SeekPrefixGE(prefix, key, flags)
     161            0 :         p.pos = pcIterPosCur
     162            0 :         if p.iterKV == nil {
     163            0 :                 return nil
     164            0 :         }
     165            0 :         return p.findNextEntry()
     166              : }
     167              : 
     168              : // SeekGE implements the InternalIterator interface.
     169            1 : func (p *pointCollapsingIterator) SeekGE(key []byte, flags base.SeekGEFlags) *base.InternalKV {
     170            1 :         p.resetKey()
     171            1 :         p.iterKV = p.iter.SeekGE(key, flags)
     172            1 :         p.pos = pcIterPosCur
     173            1 :         if p.iterKV == nil {
     174            1 :                 return nil
     175            1 :         }
     176            1 :         return p.findNextEntry()
     177              : }
     178              : 
     179              : // SeekLT implements the InternalIterator interface.
     180            0 : func (p *pointCollapsingIterator) SeekLT(key []byte, flags base.SeekLTFlags) *base.InternalKV {
     181            0 :         panic("unimplemented")
     182              : }
     183              : 
     184            1 : func (p *pointCollapsingIterator) resetKey() {
     185            1 :         p.savedKey.UserKey = p.savedKeyBuf[:0]
     186            1 :         p.savedKey.Trailer = 0
     187            1 :         p.iterKV = nil
     188            1 :         p.pos = pcIterPosCur
     189            1 : }
     190              : 
     191            1 : func (p *pointCollapsingIterator) verifySeqNum(kv *base.InternalKV) *base.InternalKV {
     192            1 :         if !invariants.Enabled {
     193            0 :                 return kv
     194            0 :         }
     195            1 :         if p.fixedSeqNum == 0 || kv == nil || kv.Kind() == InternalKeyKindRangeDelete {
     196            1 :                 return kv
     197            1 :         }
     198            0 :         if kv.SeqNum() != p.fixedSeqNum {
     199            0 :                 panic(fmt.Sprintf("expected foreign point key to have seqnum %d, got %d", p.fixedSeqNum, kv.SeqNum()))
     200              :         }
     201            0 :         return kv
     202              : }
     203              : 
     204              : // findNextEntry is called to return the next key. p.iter must be positioned at the
     205              : // start of the first user key we are interested in.
     206            1 : func (p *pointCollapsingIterator) findNextEntry() *base.InternalKV {
     207            1 :         p.saveKey()
     208            1 :         // Saves a comparison in the fast path
     209            1 :         firstIteration := true
     210            1 :         for p.iterKV != nil {
     211            1 :                 // NB: p.savedKey is either the current key (iff p.iterKV == firstKey),
     212            1 :                 // or the previous key.
     213            1 :                 if !firstIteration && !p.comparer.Equal(p.iterKV.K.UserKey, p.savedKey.UserKey) {
     214            1 :                         p.saveKey()
     215            1 :                         continue
     216              :                 }
     217            1 :                 firstIteration = false
     218            1 :                 if s := p.iter.Span(); s != nil && s.CoversAt(p.seqNum, p.iterKV.SeqNum()) {
     219            1 :                         // All future keys for this user key must be deleted.
     220            1 :                         if p.savedKey.Kind() == InternalKeyKindSingleDelete {
     221            0 :                                 panic("cannot process singledel key in point collapsing iterator")
     222              :                         }
     223              :                         // Fast forward to the next user key.
     224            1 :                         p.saveKey()
     225            1 :                         p.iterKV = p.iter.Next()
     226            1 :                         for p.iterKV != nil && p.savedKey.SeqNum() >= p.iterKV.SeqNum() && p.comparer.Equal(p.iterKV.K.UserKey, p.savedKey.UserKey) {
     227            1 :                                 p.iterKV = p.iter.Next()
     228            1 :                         }
     229            1 :                         continue
     230              :                 }
     231            1 :                 switch p.savedKey.Kind() {
     232            1 :                 case InternalKeyKindSet, InternalKeyKindDelete, InternalKeyKindSetWithDelete, InternalKeyKindDeleteSized:
     233            1 :                         // Note that we return SETs directly, even if they would otherwise get
     234            1 :                         // compacted into a Del to turn into a SetWithDelete. This is a fast
     235            1 :                         // path optimization that can break SINGLEDEL determinism. To lead to
     236            1 :                         // consistent SINGLEDEL behaviour, this iterator should *not* be used for
     237            1 :                         // a keyspace where SINGLEDELs could be in use. If this iterator observes
     238            1 :                         // a SINGLEDEL as the first internal key for a user key, it will panic.
     239            1 :                         //
     240            1 :                         // As p.value is a lazy value owned by the child iterator, we can thread
     241            1 :                         // it through without loading it into p.valueBuf.
     242            1 :                         //
     243            1 :                         // TODO(bilal): We can even avoid saving the key in this fast path if
     244            1 :                         // we are in a block where setHasSamePrefix = false in a v3 sstable,
     245            1 :                         // guaranteeing that there's only one internal key for each user key.
     246            1 :                         // Thread this logic through the sstable iterators and/or consider
     247            1 :                         // collapsing (ha) this logic into the sstable iterators that are aware
     248            1 :                         // of blocks and can determine user key changes without doing key saves
     249            1 :                         // or comparisons.
     250            1 :                         p.pos = pcIterPosCur
     251            1 :                         return p.verifySeqNum(p.iterKV)
     252            0 :                 case InternalKeyKindSingleDelete:
     253            0 :                         // Panic, as this iterator is not expected to observe single deletes.
     254            0 :                         panic("cannot process singledel key in point collapsing iterator")
     255            0 :                 case InternalKeyKindMerge:
     256            0 :                         // Panic, as this iterator is not expected to observe merges.
     257            0 :                         panic("cannot process merge key in point collapsing iterator")
     258            1 :                 case InternalKeyKindRangeDelete:
     259            1 :                         // These are interleaved by the interleaving iterator ahead of all points.
     260            1 :                         // We should pass them as-is, but also account for any points ahead of
     261            1 :                         // them.
     262            1 :                         p.pos = pcIterPosCur
     263            1 :                         return p.verifySeqNum(p.iterKV)
     264            0 :                 default:
     265            0 :                         panic(fmt.Sprintf("unexpected kind: %d", p.iterKV.Kind()))
     266              :                 }
     267              :         }
     268            0 :         p.resetKey()
     269            0 :         return nil
     270              : }
     271              : 
     272              : // First implements the InternalIterator interface.
     273            1 : func (p *pointCollapsingIterator) First() *base.InternalKV {
     274            1 :         p.resetKey()
     275            1 :         p.iterKV = p.iter.First()
     276            1 :         p.pos = pcIterPosCur
     277            1 :         if p.iterKV == nil {
     278            0 :                 return nil
     279            0 :         }
     280            1 :         return p.findNextEntry()
     281              : }
     282              : 
     283              : // Last implements the InternalIterator interface.
     284            0 : func (p *pointCollapsingIterator) Last() *base.InternalKV {
     285            0 :         panic("unimplemented")
     286              : }
     287              : 
     288            1 : func (p *pointCollapsingIterator) saveKey() {
     289            1 :         if p.iterKV == nil {
     290            1 :                 p.savedKey = InternalKey{UserKey: p.savedKeyBuf[:0]}
     291            1 :                 return
     292            1 :         }
     293            1 :         p.savedKeyBuf = append(p.savedKeyBuf[:0], p.iterKV.K.UserKey...)
     294            1 :         p.savedKey = InternalKey{UserKey: p.savedKeyBuf, Trailer: p.iterKV.K.Trailer}
     295              : }
     296              : 
     297              : // Next implements the InternalIterator interface.
     298            1 : func (p *pointCollapsingIterator) Next() *base.InternalKV {
     299            1 :         switch p.pos {
     300            1 :         case pcIterPosCur:
     301            1 :                 p.saveKey()
     302            1 :                 if p.iterKV != nil && p.iterKV.Kind() == InternalKeyKindRangeDelete {
     303            1 :                         // Step over the interleaved range delete and process the very next
     304            1 :                         // internal key, even if it's at the same user key. This is because a
     305            1 :                         // point for that user key has not been returned yet.
     306            1 :                         p.iterKV = p.iter.Next()
     307            1 :                         break
     308              :                 }
     309              :                 // Fast forward to the next user key.
     310            1 :                 kv := p.iter.Next()
     311            1 :                 // p.iterKV.SeqNum() >= key.SeqNum() is an optimization that allows us to
     312            1 :                 // use p.iterKV.SeqNum() < key.SeqNum() as a sign that the user key has
     313            1 :                 // changed, without needing to do the full key comparison.
     314            1 :                 for kv != nil && p.savedKey.SeqNum() >= kv.SeqNum() &&
     315            1 :                         p.comparer.Equal(p.savedKey.UserKey, kv.K.UserKey) {
     316            1 :                         kv = p.iter.Next()
     317            1 :                 }
     318            1 :                 if kv == nil {
     319            1 :                         // There are no keys to return.
     320            1 :                         p.resetKey()
     321            1 :                         return nil
     322            1 :                 }
     323            1 :                 p.iterKV = kv
     324            0 :         case pcIterPosNext:
     325            0 :                 p.pos = pcIterPosCur
     326              :         }
     327            1 :         if p.iterKV == nil {
     328            1 :                 p.resetKey()
     329            1 :                 return nil
     330            1 :         }
     331            1 :         return p.findNextEntry()
     332              : }
     333              : 
     334              : // NextPrefix implements the InternalIterator interface.
     335            0 : func (p *pointCollapsingIterator) NextPrefix(succKey []byte) *base.InternalKV {
     336            0 :         panic("unimplemented")
     337              : }
     338              : 
     339              : // Prev implements the InternalIterator interface.
     340            0 : func (p *pointCollapsingIterator) Prev() *base.InternalKV {
     341            0 :         panic("unimplemented")
     342              : }
     343              : 
     344              : // Error implements the InternalIterator interface.
     345            1 : func (p *pointCollapsingIterator) Error() error {
     346            1 :         if p.err != nil {
     347            0 :                 return p.err
     348            0 :         }
     349            1 :         return p.iter.Error()
     350              : }
     351              : 
     352              : // Close implements the InternalIterator interface.
     353            1 : func (p *pointCollapsingIterator) Close() error {
     354            1 :         return p.iter.Close()
     355            1 : }
     356              : 
     357              : // SetBounds implements the InternalIterator interface.
     358            0 : func (p *pointCollapsingIterator) SetBounds(lower, upper []byte) {
     359            0 :         p.resetKey()
     360            0 :         p.iter.SetBounds(lower, upper)
     361            0 : }
     362              : 
     363            0 : func (p *pointCollapsingIterator) SetContext(ctx context.Context) {
     364            0 :         p.iter.SetContext(ctx)
     365            0 : }
     366              : 
     367              : // DebugTree is part of the InternalIterator interface.
     368            0 : func (p *pointCollapsingIterator) DebugTree(tp treeprinter.Node) {
     369            0 :         n := tp.Childf("%T(%p)", p, p)
     370            0 :         p.iter.DebugTree(n)
     371            0 : }
     372              : 
     373              : // String implements the InternalIterator interface.
     374            0 : func (p *pointCollapsingIterator) String() string {
     375            0 :         return p.iter.String()
     376            0 : }
     377              : 
     378              : var _ internalIterator = &pointCollapsingIterator{}
     379              : 
     380              : // IteratorLevelKind is used to denote whether the current ScanInternal iterator
     381              : // is unknown, belongs to a flushable, or belongs to an LSM level type.
     382              : type IteratorLevelKind int8
     383              : 
     384              : const (
     385              :         // IteratorLevelUnknown indicates an unknown LSM level.
     386              :         IteratorLevelUnknown IteratorLevelKind = iota
     387              :         // IteratorLevelLSM indicates an LSM level.
     388              :         IteratorLevelLSM
     389              :         // IteratorLevelFlushable indicates a flushable (i.e. memtable).
     390              :         IteratorLevelFlushable
     391              : )
     392              : 
     393              : // IteratorLevel is used with scanInternalIterator to surface additional iterator-specific info where possible.
     394              : // Note: this is struct is only provided for point keys.
     395              : type IteratorLevel struct {
     396              :         Kind IteratorLevelKind
     397              :         // FlushableIndex indicates the position within the flushable queue of this level.
     398              :         // Only valid if kind == IteratorLevelFlushable.
     399              :         FlushableIndex int
     400              :         // The level within the LSM. Only valid if Kind == IteratorLevelLSM.
     401              :         Level int
     402              :         // Sublevel is only valid if Kind == IteratorLevelLSM and Level == 0.
     403              :         Sublevel int
     404              : }
     405              : 
     406              : // scanInternalIterator is an iterator that returns all internal keys, including
     407              : // tombstones. For instance, an InternalKeyKindDelete would be returned as an
     408              : // InternalKeyKindDelete instead of the iterator skipping over to the next key.
     409              : // Internal keys within a user key are collapsed, eg. if there are two SETs, the
     410              : // one with the higher sequence is returned. Useful if an external user of Pebble
     411              : // needs to observe and rebuild Pebble's history of internal keys, such as in
     412              : // node-to-node replication. For use with {db,snapshot}.ScanInternal().
     413              : //
     414              : // scanInternalIterator is expected to ignore point keys deleted by range
     415              : // deletions, and range keys shadowed by a range key unset or delete, however it
     416              : // *must* return the range delete as well as the range key unset/delete that did
     417              : // the shadowing.
     418              : type scanInternalIterator struct {
     419              :         ctx             context.Context
     420              :         db              *DB
     421              :         opts            scanInternalOptions
     422              :         comparer        *base.Comparer
     423              :         merge           Merge
     424              :         iter            internalIterator
     425              :         readState       *readState
     426              :         version         *version
     427              :         rangeKey        *iteratorRangeKeyState
     428              :         pointKeyIter    internalIterator
     429              :         iterKV          *base.InternalKV
     430              :         alloc           *iterAlloc
     431              :         newIters        tableNewIters
     432              :         newIterRangeKey keyspanimpl.TableNewSpanIter
     433              :         seqNum          base.SeqNum
     434              :         iterLevels      []IteratorLevel
     435              :         mergingIter     *mergingIter
     436              : 
     437              :         // boundsBuf holds two buffers used to store the lower and upper bounds.
     438              :         // Whenever the InternalIterator's bounds change, the new bounds are copied
     439              :         // into boundsBuf[boundsBufIdx]. The two bounds share a slice to reduce
     440              :         // allocations. opts.LowerBound and opts.UpperBound point into this slice.
     441              :         boundsBuf    [2][]byte
     442              :         boundsBufIdx int
     443              : }
     444              : 
     445              : // truncateExternalFile truncates an External file's [SmallestUserKey,
     446              : // LargestUserKey] fields to [lower, upper). A ExternalFile is
     447              : // produced that is suitable for external consumption by other Pebble
     448              : // instances.
     449              : //
     450              : // truncateSharedFile reads the file to try to create the smallest
     451              : // possible bounds.  Here, we blindly truncate them. This may mean we
     452              : // include this SST in iterations it isn't really needed in. Since we
     453              : // don't expect External files to be long-lived in the pebble
     454              : // instance, We think this is OK.
     455              : //
     456              : // TODO(ssd) 2024-01-26: Potentially de-duplicate with
     457              : // truncateSharedFile.
     458              : func (d *DB) truncateExternalFile(
     459              :         ctx context.Context,
     460              :         lower, upper []byte,
     461              :         level int,
     462              :         file *tableMetadata,
     463              :         objMeta objstorage.ObjectMetadata,
     464            1 : ) (*ExternalFile, error) {
     465            1 :         cmp := d.cmp
     466            1 :         sst := &ExternalFile{
     467            1 :                 Level:           uint8(level),
     468            1 :                 ObjName:         objMeta.Remote.CustomObjectName,
     469            1 :                 Locator:         objMeta.Remote.Locator,
     470            1 :                 HasPointKey:     file.HasPointKeys,
     471            1 :                 HasRangeKey:     file.HasRangeKeys,
     472            1 :                 Size:            file.Size,
     473            1 :                 SyntheticPrefix: slices.Clone(file.SyntheticPrefixAndSuffix.Prefix()),
     474            1 :                 SyntheticSuffix: slices.Clone(file.SyntheticPrefixAndSuffix.Suffix()),
     475            1 :         }
     476            1 : 
     477            1 :         needsLowerTruncate := cmp(lower, file.Smallest.UserKey) > 0
     478            1 :         if needsLowerTruncate {
     479            1 :                 sst.StartKey = slices.Clone(lower)
     480            1 :         } else {
     481            1 :                 sst.StartKey = slices.Clone(file.Smallest.UserKey)
     482            1 :         }
     483              : 
     484            1 :         cmpUpper := cmp(upper, file.Largest.UserKey)
     485            1 :         needsUpperTruncate := cmpUpper < 0
     486            1 :         if needsUpperTruncate {
     487            0 :                 sst.EndKey = slices.Clone(upper)
     488            0 :                 sst.EndKeyIsInclusive = false
     489            1 :         } else {
     490            1 :                 sst.EndKey = slices.Clone(file.Largest.UserKey)
     491            1 :                 sst.EndKeyIsInclusive = !file.Largest.IsExclusiveSentinel()
     492            1 :         }
     493              : 
     494            1 :         if cmp(sst.StartKey, sst.EndKey) > 0 {
     495            0 :                 return nil, base.AssertionFailedf("pebble: invalid external file bounds after truncation [%q, %q)", sst.StartKey, sst.EndKey)
     496            0 :         }
     497              : 
     498            1 :         if cmp(sst.StartKey, sst.EndKey) == 0 && !sst.EndKeyIsInclusive {
     499            0 :                 return nil, base.AssertionFailedf("pebble: invalid external file bounds after truncation [%q, %q)", sst.StartKey, sst.EndKey)
     500            0 :         }
     501              : 
     502            1 :         return sst, nil
     503              : }
     504              : 
     505              : // truncateSharedFile truncates a shared file's [Smallest, Largest] fields to
     506              : // [lower, upper), potentially opening iterators on the file to find keys within
     507              : // the requested bounds. A SharedSSTMeta is produced that is suitable for
     508              : // external consumption by other Pebble instances. If shouldSkip is true, this
     509              : // file does not contain any keys in [lower, upper) and can be skipped.
     510              : //
     511              : // TODO(bilal): If opening iterators and doing reads in this method is too
     512              : // inefficient, consider producing non-tight file bounds instead.
     513              : func (d *DB) truncateSharedFile(
     514              :         ctx context.Context,
     515              :         lower, upper []byte,
     516              :         level int,
     517              :         file *tableMetadata,
     518              :         objMeta objstorage.ObjectMetadata,
     519            1 : ) (sst *SharedSSTMeta, shouldSkip bool, err error) {
     520            1 :         cmp := d.cmp
     521            1 :         sst = &SharedSSTMeta{}
     522            1 :         sst.cloneFromFileMeta(file)
     523            1 :         sst.Level = uint8(level)
     524            1 :         sst.Backing, err = d.objProvider.RemoteObjectBacking(&objMeta)
     525            1 :         if err != nil {
     526            0 :                 return nil, false, err
     527            0 :         }
     528            1 :         needsLowerTruncate := cmp(lower, file.Smallest.UserKey) > 0
     529            1 :         needsUpperTruncate := cmp(upper, file.Largest.UserKey) < 0 || (cmp(upper, file.Largest.UserKey) == 0 && !file.Largest.IsExclusiveSentinel())
     530            1 :         // Fast path: file is entirely within [lower, upper).
     531            1 :         if !needsLowerTruncate && !needsUpperTruncate {
     532            1 :                 return sst, false, nil
     533            1 :         }
     534              : 
     535              :         // We will need to truncate file bounds in at least one direction. Open all
     536              :         // relevant iterators.
     537            1 :         iters, err := d.newIters(ctx, file, &IterOptions{
     538            1 :                 LowerBound: lower,
     539            1 :                 UpperBound: upper,
     540            1 :                 layer:      manifest.Level(level),
     541            1 :         }, internalIterOpts{}, iterPointKeys|iterRangeDeletions|iterRangeKeys)
     542            1 :         if err != nil {
     543            0 :                 return nil, false, err
     544            0 :         }
     545            1 :         defer iters.CloseAll()
     546            1 :         iter := iters.point
     547            1 :         rangeDelIter := iters.rangeDeletion
     548            1 :         rangeKeyIter := iters.rangeKey
     549            1 :         if rangeDelIter != nil {
     550            1 :                 rangeDelIter = keyspan.Truncate(cmp, rangeDelIter, base.UserKeyBoundsEndExclusive(lower, upper))
     551            1 :         }
     552            1 :         if rangeKeyIter != nil {
     553            1 :                 rangeKeyIter = keyspan.Truncate(cmp, rangeKeyIter, base.UserKeyBoundsEndExclusive(lower, upper))
     554            1 :         }
     555              :         // Check if we need to truncate on the left side. This means finding a new
     556              :         // LargestPointKey and LargestRangeKey that is >= lower.
     557            1 :         if needsLowerTruncate {
     558            1 :                 sst.SmallestPointKey.UserKey = sst.SmallestPointKey.UserKey[:0]
     559            1 :                 sst.SmallestPointKey.Trailer = 0
     560            1 :                 kv := iter.SeekGE(lower, base.SeekGEFlagsNone)
     561            1 :                 foundPointKey := kv != nil
     562            1 :                 if kv != nil {
     563            1 :                         sst.SmallestPointKey.CopyFrom(kv.K)
     564            1 :                 }
     565            1 :                 if rangeDelIter != nil {
     566            1 :                         if span, err := rangeDelIter.SeekGE(lower); err != nil {
     567            0 :                                 return nil, false, err
     568            1 :                         } else if span != nil && (len(sst.SmallestPointKey.UserKey) == 0 || base.InternalCompare(cmp, span.SmallestKey(), sst.SmallestPointKey) < 0) {
     569            1 :                                 sst.SmallestPointKey.CopyFrom(span.SmallestKey())
     570            1 :                                 foundPointKey = true
     571            1 :                         }
     572              :                 }
     573            1 :                 if !foundPointKey {
     574            1 :                         // There are no point keys in the span we're interested in.
     575            1 :                         sst.SmallestPointKey = InternalKey{}
     576            1 :                         sst.LargestPointKey = InternalKey{}
     577            1 :                 }
     578            1 :                 sst.SmallestRangeKey.UserKey = sst.SmallestRangeKey.UserKey[:0]
     579            1 :                 sst.SmallestRangeKey.Trailer = 0
     580            1 :                 if rangeKeyIter != nil {
     581            1 :                         span, err := rangeKeyIter.SeekGE(lower)
     582            1 :                         switch {
     583            0 :                         case err != nil:
     584            0 :                                 return nil, false, err
     585            1 :                         case span != nil:
     586            1 :                                 sst.SmallestRangeKey.CopyFrom(span.SmallestKey())
     587            1 :                         default:
     588            1 :                                 // There are no range keys in the span we're interested in.
     589            1 :                                 sst.SmallestRangeKey = InternalKey{}
     590            1 :                                 sst.LargestRangeKey = InternalKey{}
     591              :                         }
     592              :                 }
     593              :         }
     594              :         // Check if we need to truncate on the right side. This means finding a new
     595              :         // LargestPointKey and LargestRangeKey that is < upper.
     596            1 :         if needsUpperTruncate {
     597            1 :                 sst.LargestPointKey.UserKey = sst.LargestPointKey.UserKey[:0]
     598            1 :                 sst.LargestPointKey.Trailer = 0
     599            1 :                 kv := iter.SeekLT(upper, base.SeekLTFlagsNone)
     600            1 :                 foundPointKey := kv != nil
     601            1 :                 if kv != nil {
     602            1 :                         sst.LargestPointKey.CopyFrom(kv.K)
     603            1 :                 }
     604            1 :                 if rangeDelIter != nil {
     605            1 :                         if span, err := rangeDelIter.SeekLT(upper); err != nil {
     606            0 :                                 return nil, false, err
     607            1 :                         } else if span != nil && (len(sst.LargestPointKey.UserKey) == 0 || base.InternalCompare(cmp, span.LargestKey(), sst.LargestPointKey) > 0) {
     608            1 :                                 sst.LargestPointKey.CopyFrom(span.LargestKey())
     609            1 :                                 foundPointKey = true
     610            1 :                         }
     611              :                 }
     612            1 :                 if !foundPointKey {
     613            1 :                         // There are no point keys in the span we're interested in.
     614            1 :                         sst.SmallestPointKey = InternalKey{}
     615            1 :                         sst.LargestPointKey = InternalKey{}
     616            1 :                 }
     617            1 :                 sst.LargestRangeKey.UserKey = sst.LargestRangeKey.UserKey[:0]
     618            1 :                 sst.LargestRangeKey.Trailer = 0
     619            1 :                 if rangeKeyIter != nil {
     620            1 :                         span, err := rangeKeyIter.SeekLT(upper)
     621            1 :                         switch {
     622            0 :                         case err != nil:
     623            0 :                                 return nil, false, err
     624            1 :                         case span != nil:
     625            1 :                                 sst.LargestRangeKey.CopyFrom(span.LargestKey())
     626            1 :                         default:
     627            1 :                                 // There are no range keys in the span we're interested in.
     628            1 :                                 sst.SmallestRangeKey = InternalKey{}
     629            1 :                                 sst.LargestRangeKey = InternalKey{}
     630              :                         }
     631              :                 }
     632              :         }
     633              :         // Set overall bounds based on {Smallest,Largest}{Point,Range}Key.
     634            1 :         switch {
     635            1 :         case len(sst.SmallestRangeKey.UserKey) == 0:
     636            1 :                 sst.Smallest = sst.SmallestPointKey
     637            1 :         case len(sst.SmallestPointKey.UserKey) == 0:
     638            1 :                 sst.Smallest = sst.SmallestRangeKey
     639            1 :         default:
     640            1 :                 sst.Smallest = sst.SmallestPointKey
     641            1 :                 if base.InternalCompare(cmp, sst.SmallestRangeKey, sst.SmallestPointKey) < 0 {
     642            1 :                         sst.Smallest = sst.SmallestRangeKey
     643            1 :                 }
     644              :         }
     645            1 :         switch {
     646            1 :         case len(sst.LargestRangeKey.UserKey) == 0:
     647            1 :                 sst.Largest = sst.LargestPointKey
     648            1 :         case len(sst.LargestPointKey.UserKey) == 0:
     649            1 :                 sst.Largest = sst.LargestRangeKey
     650            1 :         default:
     651            1 :                 sst.Largest = sst.LargestPointKey
     652            1 :                 if base.InternalCompare(cmp, sst.LargestRangeKey, sst.LargestPointKey) > 0 {
     653            1 :                         sst.Largest = sst.LargestRangeKey
     654            1 :                 }
     655              :         }
     656              :         // On rare occasion, a file might overlap with [lower, upper) but not actually
     657              :         // have any keys within those bounds. Skip such files.
     658            1 :         if len(sst.Smallest.UserKey) == 0 {
     659            1 :                 return nil, true, nil
     660            1 :         }
     661            1 :         sst.Size, err = d.fileCache.estimateSize(file, sst.Smallest.UserKey, sst.Largest.UserKey)
     662            1 :         if err != nil {
     663            0 :                 return nil, false, err
     664            0 :         }
     665              :         // On occasion, estimateSize gives us a low estimate, i.e. a 0 file size. This
     666              :         // can cause panics in places where we divide by file sizes. Correct for it
     667              :         // here.
     668            1 :         if sst.Size == 0 {
     669            1 :                 sst.Size = 1
     670            1 :         }
     671            1 :         return sst, false, nil
     672              : }
     673              : 
     674              : func scanInternalImpl(
     675              :         ctx context.Context, lower, upper []byte, iter *scanInternalIterator, opts *scanInternalOptions,
     676            1 : ) error {
     677            1 :         if opts.visitSharedFile != nil && (lower == nil || upper == nil) {
     678            0 :                 panic("lower and upper bounds must be specified in skip-shared iteration mode")
     679              :         }
     680            1 :         if opts.visitSharedFile != nil && opts.visitExternalFile != nil {
     681            0 :                 return base.AssertionFailedf("cannot provide both a shared-file and external-file visitor")
     682            0 :         }
     683              : 
     684              :         // Before starting iteration, check if any files in levels sharedLevelsStart
     685              :         // and below are *not* shared. Error out if that is the case, as skip-shared
     686              :         // iteration will not produce a consistent point-in-time view of this range
     687              :         // of keys. For files that are shared, call visitSharedFile with a truncated
     688              :         // version of that file.
     689            1 :         cmp := iter.comparer.Compare
     690            1 :         provider := iter.db.ObjProvider()
     691            1 :         seqNum := iter.seqNum
     692            1 :         current := iter.version
     693            1 :         if current == nil {
     694            1 :                 current = iter.readState.current
     695            1 :         }
     696              : 
     697            1 :         if opts.visitSharedFile != nil || opts.visitExternalFile != nil {
     698            1 :                 if provider == nil {
     699            0 :                         panic("expected non-nil Provider in skip-shared iteration mode")
     700              :                 }
     701              : 
     702            1 :                 firstLevelWithRemote := opts.skipLevelForOpts()
     703            1 :                 for level := firstLevelWithRemote; level < numLevels; level++ {
     704            1 :                         files := current.Levels[level].Iter()
     705            1 :                         for f := files.SeekGE(cmp, lower); f != nil && cmp(f.Smallest.UserKey, upper) < 0; f = files.Next() {
     706            1 :                                 if cmp(lower, f.Largest.UserKey) == 0 && f.Largest.IsExclusiveSentinel() {
     707            0 :                                         continue
     708              :                                 }
     709              : 
     710            1 :                                 var objMeta objstorage.ObjectMetadata
     711            1 :                                 var err error
     712            1 :                                 objMeta, err = provider.Lookup(base.FileTypeTable, f.FileBacking.DiskFileNum)
     713            1 :                                 if err != nil {
     714            0 :                                         return err
     715            0 :                                 }
     716              : 
     717              :                                 // We allow a mix of files at the first level.
     718            1 :                                 if level != firstLevelWithRemote {
     719            1 :                                         if !objMeta.IsShared() && !objMeta.IsExternal() {
     720            0 :                                                 return errors.Wrapf(ErrInvalidSkipSharedIteration, "file %s is not shared or external", objMeta.DiskFileNum)
     721            0 :                                         }
     722              :                                 }
     723              : 
     724            1 :                                 if objMeta.IsShared() && opts.visitSharedFile == nil {
     725            0 :                                         return errors.Wrapf(ErrInvalidSkipSharedIteration, "shared file is present but no shared file visitor is defined")
     726            0 :                                 }
     727              : 
     728            1 :                                 if objMeta.IsExternal() && opts.visitExternalFile == nil {
     729            1 :                                         return errors.Wrapf(ErrInvalidSkipSharedIteration, "external file is present but no external file visitor is defined")
     730            1 :                                 }
     731              : 
     732            1 :                                 if !base.Visible(f.LargestSeqNum, seqNum, base.SeqNumMax) {
     733            1 :                                         return errors.Wrapf(ErrInvalidSkipSharedIteration, "file %s contains keys newer than snapshot", objMeta.DiskFileNum)
     734            1 :                                 }
     735              : 
     736            1 :                                 if level != firstLevelWithRemote && (!objMeta.IsShared() && !objMeta.IsExternal()) {
     737            0 :                                         return errors.Wrapf(ErrInvalidSkipSharedIteration, "file %s is not shared or external", objMeta.DiskFileNum)
     738            0 :                                 }
     739              : 
     740            1 :                                 if objMeta.IsShared() {
     741            1 :                                         var sst *SharedSSTMeta
     742            1 :                                         var skip bool
     743            1 :                                         sst, skip, err = iter.db.truncateSharedFile(ctx, lower, upper, level, f, objMeta)
     744            1 :                                         if err != nil {
     745            0 :                                                 return err
     746            0 :                                         }
     747            1 :                                         if skip {
     748            1 :                                                 continue
     749              :                                         }
     750            1 :                                         if err = opts.visitSharedFile(sst); err != nil {
     751            0 :                                                 return err
     752            0 :                                         }
     753            1 :                                 } else if objMeta.IsExternal() {
     754            1 :                                         sst, err := iter.db.truncateExternalFile(ctx, lower, upper, level, f, objMeta)
     755            1 :                                         if err != nil {
     756            0 :                                                 return err
     757            0 :                                         }
     758            1 :                                         if err := opts.visitExternalFile(sst); err != nil {
     759            0 :                                                 return err
     760            0 :                                         }
     761              :                                 }
     762              : 
     763              :                         }
     764              :                 }
     765              :         }
     766              : 
     767            1 :         for valid := iter.seekGE(lower); valid && iter.error() == nil; valid = iter.next() {
     768            1 :                 key := iter.unsafeKey()
     769            1 : 
     770            1 :                 if opts.rateLimitFunc != nil {
     771            0 :                         if err := opts.rateLimitFunc(key, iter.lazyValue()); err != nil {
     772            0 :                                 return err
     773            0 :                         }
     774              :                 }
     775              : 
     776            1 :                 switch key.Kind() {
     777            1 :                 case InternalKeyKindRangeKeyDelete, InternalKeyKindRangeKeyUnset, InternalKeyKindRangeKeySet:
     778            1 :                         if opts.visitRangeKey != nil {
     779            1 :                                 span := iter.unsafeSpan()
     780            1 :                                 // NB: The caller isn't interested in the sequence numbers of these
     781            1 :                                 // range keys. Rather, the caller wants them to be in trailer order
     782            1 :                                 // _after_ zeroing of sequence numbers. Copy span.Keys, sort it, and then
     783            1 :                                 // call visitRangeKey.
     784            1 :                                 keysCopy := make([]keyspan.Key, len(span.Keys))
     785            1 :                                 for i := range span.Keys {
     786            1 :                                         keysCopy[i].CopyFrom(span.Keys[i])
     787            1 :                                         keysCopy[i].Trailer = base.MakeTrailer(0, span.Keys[i].Kind())
     788            1 :                                 }
     789            1 :                                 keyspan.SortKeysByTrailer(keysCopy)
     790            1 :                                 if err := opts.visitRangeKey(span.Start, span.End, keysCopy); err != nil {
     791            0 :                                         return err
     792            0 :                                 }
     793              :                         }
     794            1 :                 case InternalKeyKindRangeDelete:
     795            1 :                         if opts.visitRangeDel != nil {
     796            1 :                                 rangeDel := iter.unsafeRangeDel()
     797            1 :                                 if err := opts.visitRangeDel(rangeDel.Start, rangeDel.End, rangeDel.LargestSeqNum()); err != nil {
     798            0 :                                         return err
     799            0 :                                 }
     800              :                         }
     801            1 :                 default:
     802            1 :                         if opts.visitPointKey != nil {
     803            1 :                                 var info IteratorLevel
     804            1 :                                 if len(iter.mergingIter.heap.items) > 0 {
     805            1 :                                         mergingIterIdx := iter.mergingIter.heap.items[0].index
     806            1 :                                         info = iter.iterLevels[mergingIterIdx]
     807            1 :                                 } else {
     808            0 :                                         info = IteratorLevel{Kind: IteratorLevelUnknown}
     809            0 :                                 }
     810            1 :                                 val := iter.lazyValue()
     811            1 :                                 if err := opts.visitPointKey(key, val, info); err != nil {
     812            0 :                                         return err
     813            0 :                                 }
     814              :                         }
     815              :                 }
     816              :         }
     817              : 
     818            1 :         return nil
     819              : }
     820              : 
     821            1 : func (opts *scanInternalOptions) skipLevelForOpts() int {
     822            1 :         if opts.visitSharedFile != nil {
     823            1 :                 return sharedLevelsStart
     824            1 :         }
     825            1 :         if opts.visitExternalFile != nil {
     826            1 :                 return externalSkipStart
     827            1 :         }
     828            1 :         return numLevels
     829              : }
     830              : 
     831              : // constructPointIter constructs a merging iterator and sets i.iter to it.
     832              : func (i *scanInternalIterator) constructPointIter(
     833              :         category block.Category, memtables flushableList, buf *iterAlloc,
     834            1 : ) error {
     835            1 :         // Merging levels and levels from iterAlloc.
     836            1 :         mlevels := buf.mlevels[:0]
     837            1 :         levels := buf.levels[:0]
     838            1 : 
     839            1 :         // We compute the number of levels needed ahead of time and reallocate a slice if
     840            1 :         // the array from the iterAlloc isn't large enough. Doing this allocation once
     841            1 :         // should improve the performance.
     842            1 :         numMergingLevels := len(memtables)
     843            1 :         numLevelIters := 0
     844            1 : 
     845            1 :         current := i.version
     846            1 :         if current == nil {
     847            1 :                 current = i.readState.current
     848            1 :         }
     849            1 :         numMergingLevels += len(current.L0SublevelFiles)
     850            1 :         numLevelIters += len(current.L0SublevelFiles)
     851            1 : 
     852            1 :         skipStart := i.opts.skipLevelForOpts()
     853            1 :         for level := 1; level < len(current.Levels); level++ {
     854            1 :                 if current.Levels[level].Empty() {
     855            1 :                         continue
     856              :                 }
     857            1 :                 if level > skipStart {
     858            1 :                         continue
     859              :                 }
     860            1 :                 numMergingLevels++
     861            1 :                 numLevelIters++
     862              :         }
     863              : 
     864            1 :         if numMergingLevels > cap(mlevels) {
     865            0 :                 mlevels = make([]mergingIterLevel, 0, numMergingLevels)
     866            0 :         }
     867            1 :         if numLevelIters > cap(levels) {
     868            0 :                 levels = make([]levelIter, 0, numLevelIters)
     869            0 :         }
     870              :         // TODO(bilal): Push these into the iterAlloc buf.
     871            1 :         var rangeDelMiter keyspanimpl.MergingIter
     872            1 :         rangeDelIters := make([]keyspan.FragmentIterator, 0, numMergingLevels)
     873            1 :         rangeDelLevels := make([]keyspanimpl.LevelIter, 0, numLevelIters)
     874            1 : 
     875            1 :         i.iterLevels = make([]IteratorLevel, numMergingLevels)
     876            1 :         mlevelsIndex := 0
     877            1 : 
     878            1 :         // Next are the memtables.
     879            1 :         for j := len(memtables) - 1; j >= 0; j-- {
     880            1 :                 mem := memtables[j]
     881            1 :                 mlevels = append(mlevels, mergingIterLevel{
     882            1 :                         iter: mem.newIter(&i.opts.IterOptions),
     883            1 :                 })
     884            1 :                 i.iterLevels[mlevelsIndex] = IteratorLevel{
     885            1 :                         Kind:           IteratorLevelFlushable,
     886            1 :                         FlushableIndex: j,
     887            1 :                 }
     888            1 :                 mlevelsIndex++
     889            1 :                 if rdi := mem.newRangeDelIter(&i.opts.IterOptions); rdi != nil {
     890            1 :                         rangeDelIters = append(rangeDelIters, rdi)
     891            1 :                 }
     892              :         }
     893              : 
     894              :         // Next are the file levels: L0 sub-levels followed by lower levels.
     895            1 :         levelsIndex := len(levels)
     896            1 :         mlevels = mlevels[:numMergingLevels]
     897            1 :         levels = levels[:numLevelIters]
     898            1 :         rangeDelLevels = rangeDelLevels[:numLevelIters]
     899            1 :         i.opts.IterOptions.snapshotForHideObsoletePoints = i.seqNum
     900            1 :         i.opts.IterOptions.Category = category
     901            1 :         addLevelIterForFiles := func(files manifest.LevelIterator, level manifest.Layer) {
     902            1 :                 li := &levels[levelsIndex]
     903            1 :                 rli := &rangeDelLevels[levelsIndex]
     904            1 : 
     905            1 :                 li.init(
     906            1 :                         i.ctx, i.opts.IterOptions, i.comparer, i.newIters, files, level,
     907            1 :                         internalIterOpts{})
     908            1 :                 mlevels[mlevelsIndex].iter = li
     909            1 :                 rli.Init(i.ctx, keyspan.SpanIterOptions{RangeKeyFilters: i.opts.RangeKeyFilters},
     910            1 :                         i.comparer.Compare, tableNewRangeDelIter(i.newIters), files, level,
     911            1 :                         manifest.KeyTypePoint)
     912            1 :                 rangeDelIters = append(rangeDelIters, rli)
     913            1 : 
     914            1 :                 levelsIndex++
     915            1 :                 mlevelsIndex++
     916            1 :         }
     917              : 
     918            1 :         for j := len(current.L0SublevelFiles) - 1; j >= 0; j-- {
     919            1 :                 i.iterLevels[mlevelsIndex] = IteratorLevel{
     920            1 :                         Kind:     IteratorLevelLSM,
     921            1 :                         Level:    0,
     922            1 :                         Sublevel: j,
     923            1 :                 }
     924            1 :                 addLevelIterForFiles(current.L0SublevelFiles[j].Iter(), manifest.L0Sublevel(j))
     925            1 :         }
     926              :         // Add level iterators for the non-empty non-L0 levels.
     927            1 :         for level := 1; level < numLevels; level++ {
     928            1 :                 if current.Levels[level].Empty() {
     929            1 :                         continue
     930              :                 }
     931              : 
     932            1 :                 if level > skipStart {
     933            1 :                         continue
     934              :                 }
     935            1 :                 i.iterLevels[mlevelsIndex] = IteratorLevel{Kind: IteratorLevelLSM, Level: level}
     936            1 :                 levIter := current.Levels[level].Iter()
     937            1 :                 if level == skipStart {
     938            1 :                         nonRemoteFiles := make([]*manifest.TableMetadata, 0)
     939            1 :                         for f := levIter.First(); f != nil; f = levIter.Next() {
     940            1 :                                 meta, err := i.db.objProvider.Lookup(base.FileTypeTable, f.FileBacking.DiskFileNum)
     941            1 :                                 if err != nil {
     942            0 :                                         return err
     943            0 :                                 }
     944            1 :                                 if (meta.IsShared() && i.opts.visitSharedFile != nil) ||
     945            1 :                                         (meta.IsExternal() && i.opts.visitExternalFile != nil) {
     946            1 :                                         // Skip this file.
     947            1 :                                         continue
     948              :                                 }
     949            1 :                                 nonRemoteFiles = append(nonRemoteFiles, f)
     950              :                         }
     951            1 :                         levSlice := manifest.NewLevelSliceKeySorted(i.db.cmp, nonRemoteFiles)
     952            1 :                         levIter = levSlice.Iter()
     953              :                 }
     954              : 
     955            1 :                 addLevelIterForFiles(levIter, manifest.Level(level))
     956              :         }
     957              : 
     958            1 :         buf.merging.init(&i.opts.IterOptions, &InternalIteratorStats{}, i.comparer.Compare, i.comparer.Split, mlevels...)
     959            1 :         buf.merging.snapshot = i.seqNum
     960            1 :         rangeDelMiter.Init(i.comparer, keyspan.VisibleTransform(i.seqNum), new(keyspanimpl.MergingBuffers), rangeDelIters...)
     961            1 : 
     962            1 :         if i.opts.includeObsoleteKeys {
     963            1 :                 iiter := &keyspan.InterleavingIter{}
     964            1 :                 iiter.Init(i.comparer, &buf.merging, &rangeDelMiter,
     965            1 :                         keyspan.InterleavingIterOpts{
     966            1 :                                 LowerBound: i.opts.LowerBound,
     967            1 :                                 UpperBound: i.opts.UpperBound,
     968            1 :                         })
     969            1 :                 i.pointKeyIter = iiter
     970            1 :         } else {
     971            1 :                 pcIter := &pointCollapsingIterator{
     972            1 :                         comparer: i.comparer,
     973            1 :                         merge:    i.merge,
     974            1 :                         seqNum:   i.seqNum,
     975            1 :                 }
     976            1 :                 pcIter.iter.Init(i.comparer, &buf.merging, &rangeDelMiter, keyspan.InterleavingIterOpts{
     977            1 :                         LowerBound: i.opts.LowerBound,
     978            1 :                         UpperBound: i.opts.UpperBound,
     979            1 :                 })
     980            1 :                 i.pointKeyIter = pcIter
     981            1 :         }
     982            1 :         i.iter = i.pointKeyIter
     983            1 :         return nil
     984              : }
     985              : 
     986              : // constructRangeKeyIter constructs the range-key iterator stack, populating
     987              : // i.rangeKey.rangeKeyIter with the resulting iterator. This is similar to
     988              : // Iterator.constructRangeKeyIter, except it doesn't handle batches and ensures
     989              : // iterConfig does *not* elide unsets/deletes.
     990            1 : func (i *scanInternalIterator) constructRangeKeyIter() error {
     991            1 :         // We want the bounded iter from iterConfig, but not the collapsing of
     992            1 :         // RangeKeyUnsets and RangeKeyDels.
     993            1 :         i.rangeKey.rangeKeyIter = i.rangeKey.iterConfig.Init(
     994            1 :                 i.comparer, i.seqNum, i.opts.LowerBound, i.opts.UpperBound,
     995            1 :                 nil /* hasPrefix */, nil /* prefix */, true, /* internalKeys */
     996            1 :                 &i.rangeKey.rangeKeyBuffers.internal)
     997            1 : 
     998            1 :         // Next are the flushables: memtables and large batches.
     999            1 :         if i.readState != nil {
    1000            1 :                 for j := len(i.readState.memtables) - 1; j >= 0; j-- {
    1001            1 :                         mem := i.readState.memtables[j]
    1002            1 :                         // We only need to read from memtables which contain sequence numbers older
    1003            1 :                         // than seqNum.
    1004            1 :                         if logSeqNum := mem.logSeqNum; logSeqNum >= i.seqNum {
    1005            1 :                                 continue
    1006              :                         }
    1007            1 :                         if rki := mem.newRangeKeyIter(&i.opts.IterOptions); rki != nil {
    1008            1 :                                 i.rangeKey.iterConfig.AddLevel(rki)
    1009            1 :                         }
    1010              :                 }
    1011              :         }
    1012              : 
    1013            1 :         current := i.version
    1014            1 :         if current == nil {
    1015            1 :                 current = i.readState.current
    1016            1 :         }
    1017              :         // Next are the file levels: L0 sub-levels followed by lower levels.
    1018              :         //
    1019              :         // Add file-specific iterators for L0 files containing range keys. This is less
    1020              :         // efficient than using levelIters for sublevels of L0 files containing
    1021              :         // range keys, but range keys are expected to be sparse anyway, reducing the
    1022              :         // cost benefit of maintaining a separate L0Sublevels instance for range key
    1023              :         // files and then using it here.
    1024              :         //
    1025              :         // NB: We iterate L0's files in reverse order. They're sorted by
    1026              :         // LargestSeqNum ascending, and we need to add them to the merging iterator
    1027              :         // in LargestSeqNum descending to preserve the merging iterator's invariants
    1028              :         // around Key InternalKeyTrailer order.
    1029            1 :         iter := current.RangeKeyLevels[0].Iter()
    1030            1 :         for f := iter.Last(); f != nil; f = iter.Prev() {
    1031            1 :                 spanIter, err := i.newIterRangeKey(i.ctx, f, i.opts.SpanIterOptions())
    1032            1 :                 if err != nil {
    1033            0 :                         return err
    1034            0 :                 }
    1035            1 :                 i.rangeKey.iterConfig.AddLevel(spanIter)
    1036              :         }
    1037              :         // Add level iterators for the non-empty non-L0 levels.
    1038            1 :         skipStart := i.opts.skipLevelForOpts()
    1039            1 :         for level := 1; level < len(current.RangeKeyLevels); level++ {
    1040            1 :                 if current.RangeKeyLevels[level].Empty() {
    1041            1 :                         continue
    1042              :                 }
    1043            1 :                 if level > skipStart {
    1044            1 :                         continue
    1045              :                 }
    1046            1 :                 li := i.rangeKey.iterConfig.NewLevelIter()
    1047            1 :                 spanIterOpts := i.opts.SpanIterOptions()
    1048            1 :                 levIter := current.RangeKeyLevels[level].Iter()
    1049            1 :                 if level == skipStart {
    1050            1 :                         nonRemoteFiles := make([]*manifest.TableMetadata, 0)
    1051            1 :                         for f := levIter.First(); f != nil; f = levIter.Next() {
    1052            1 :                                 meta, err := i.db.objProvider.Lookup(base.FileTypeTable, f.FileBacking.DiskFileNum)
    1053            1 :                                 if err != nil {
    1054            0 :                                         return err
    1055            0 :                                 }
    1056            1 :                                 if (meta.IsShared() && i.opts.visitSharedFile != nil) ||
    1057            1 :                                         (meta.IsExternal() && i.opts.visitExternalFile != nil) {
    1058            1 :                                         // Skip this file.
    1059            1 :                                         continue
    1060              :                                 }
    1061            0 :                                 nonRemoteFiles = append(nonRemoteFiles, f)
    1062              :                         }
    1063            1 :                         levSlice := manifest.NewLevelSliceKeySorted(i.db.cmp, nonRemoteFiles)
    1064            1 :                         levIter = levSlice.Iter()
    1065              :                 }
    1066            1 :                 li.Init(i.ctx, spanIterOpts, i.comparer.Compare, i.newIterRangeKey, levIter,
    1067            1 :                         manifest.Level(level), manifest.KeyTypeRange)
    1068            1 :                 i.rangeKey.iterConfig.AddLevel(li)
    1069              :         }
    1070            1 :         return nil
    1071              : }
    1072              : 
    1073              : // seekGE seeks this iterator to the first key that's greater than or equal
    1074              : // to the specified user key.
    1075            1 : func (i *scanInternalIterator) seekGE(key []byte) bool {
    1076            1 :         i.iterKV = i.iter.SeekGE(key, base.SeekGEFlagsNone)
    1077            1 :         return i.iterKV != nil
    1078            1 : }
    1079              : 
    1080              : // unsafeKey returns the unsafe InternalKey at the current position. The value
    1081              : // is nil if the iterator is invalid or exhausted.
    1082            1 : func (i *scanInternalIterator) unsafeKey() *InternalKey {
    1083            1 :         return &i.iterKV.K
    1084            1 : }
    1085              : 
    1086              : // lazyValue returns a value pointer to the value at the current iterator
    1087              : // position. Behaviour undefined if unsafeKey() returns a Range key or Rangedel
    1088              : // kind key.
    1089            1 : func (i *scanInternalIterator) lazyValue() LazyValue {
    1090            1 :         return i.iterKV.LazyValue()
    1091            1 : }
    1092              : 
    1093              : // unsafeRangeDel returns a range key span. Behaviour undefined if UnsafeKey returns
    1094              : // a non-rangedel kind.
    1095            1 : func (i *scanInternalIterator) unsafeRangeDel() *keyspan.Span {
    1096            1 :         type spanInternalIterator interface {
    1097            1 :                 Span() *keyspan.Span
    1098            1 :         }
    1099            1 :         return i.pointKeyIter.(spanInternalIterator).Span()
    1100            1 : }
    1101              : 
    1102              : // unsafeSpan returns a range key span. Behaviour undefined if UnsafeKey returns
    1103              : // a non-rangekey type.
    1104            1 : func (i *scanInternalIterator) unsafeSpan() *keyspan.Span {
    1105            1 :         return i.rangeKey.iiter.Span()
    1106            1 : }
    1107              : 
    1108              : // next advances the iterator in the forward direction, and returns the
    1109              : // iterator's new validity state.
    1110            1 : func (i *scanInternalIterator) next() bool {
    1111            1 :         i.iterKV = i.iter.Next()
    1112            1 :         return i.iterKV != nil
    1113            1 : }
    1114              : 
    1115              : // error returns an error from the internal iterator, if there's any.
    1116            1 : func (i *scanInternalIterator) error() error {
    1117            1 :         return i.iter.Error()
    1118            1 : }
    1119              : 
    1120              : // close closes this iterator, and releases any pooled objects.
    1121            1 : func (i *scanInternalIterator) close() error {
    1122            1 :         if err := i.iter.Close(); err != nil {
    1123            0 :                 return err
    1124            0 :         }
    1125            1 :         if i.readState != nil {
    1126            1 :                 i.readState.unref()
    1127            1 :         }
    1128            1 :         if i.version != nil {
    1129            1 :                 i.version.Unref()
    1130            1 :         }
    1131            1 :         if i.rangeKey != nil {
    1132            1 :                 i.rangeKey.PrepareForReuse()
    1133            1 :                 *i.rangeKey = iteratorRangeKeyState{
    1134            1 :                         rangeKeyBuffers: i.rangeKey.rangeKeyBuffers,
    1135            1 :                 }
    1136            1 :                 iterRangeKeyStateAllocPool.Put(i.rangeKey)
    1137            1 :                 i.rangeKey = nil
    1138            1 :         }
    1139            1 :         if alloc := i.alloc; alloc != nil {
    1140            1 :                 for j := range i.boundsBuf {
    1141            1 :                         if cap(i.boundsBuf[j]) >= maxKeyBufCacheSize {
    1142            0 :                                 alloc.boundsBuf[j] = nil
    1143            1 :                         } else {
    1144            1 :                                 alloc.boundsBuf[j] = i.boundsBuf[j]
    1145            1 :                         }
    1146              :                 }
    1147            1 :                 *alloc = iterAlloc{
    1148            1 :                         keyBuf:              alloc.keyBuf[:0],
    1149            1 :                         boundsBuf:           alloc.boundsBuf,
    1150            1 :                         prefixOrFullSeekKey: alloc.prefixOrFullSeekKey[:0],
    1151            1 :                 }
    1152            1 :                 iterAllocPool.Put(alloc)
    1153            1 :                 i.alloc = nil
    1154              :         }
    1155            1 :         return nil
    1156              : }
    1157              : 
    1158            1 : func (i *scanInternalIterator) initializeBoundBufs(lower, upper []byte) {
    1159            1 :         buf := i.boundsBuf[i.boundsBufIdx][:0]
    1160            1 :         if lower != nil {
    1161            1 :                 buf = append(buf, lower...)
    1162            1 :                 i.opts.LowerBound = buf
    1163            1 :         } else {
    1164            1 :                 i.opts.LowerBound = nil
    1165            1 :         }
    1166            1 :         if upper != nil {
    1167            1 :                 buf = append(buf, upper...)
    1168            1 :                 i.opts.UpperBound = buf[len(buf)-len(upper):]
    1169            1 :         } else {
    1170            1 :                 i.opts.UpperBound = nil
    1171            1 :         }
    1172            1 :         i.boundsBuf[i.boundsBufIdx] = buf
    1173            1 :         i.boundsBufIdx = 1 - i.boundsBufIdx
    1174              : }
        

Generated by: LCOV version 2.0-1