LCOV - code coverage report
Current view: top level - pebble - db.go (source / functions) Coverage Total Hit
Test: 2025-09-21 08:18Z 489b133b - tests only.lcov Lines: 90.0 % 1516 1364
Test Date: 2025-09-21 08:19:57 Functions: - 0 0

            Line data    Source code
       1              : // Copyright 2012 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 provides an ordered key/value store.
       6              : package pebble // import "github.com/cockroachdb/pebble"
       7              : 
       8              : import (
       9              :         "context"
      10              :         "fmt"
      11              :         "io"
      12              :         "reflect"
      13              :         "slices"
      14              :         "sync"
      15              :         "sync/atomic"
      16              :         "time"
      17              :         "unsafe"
      18              : 
      19              :         "github.com/cockroachdb/crlib/crtime"
      20              :         "github.com/cockroachdb/errors"
      21              :         "github.com/cockroachdb/pebble/internal/arenaskl"
      22              :         "github.com/cockroachdb/pebble/internal/base"
      23              :         "github.com/cockroachdb/pebble/internal/cache"
      24              :         "github.com/cockroachdb/pebble/internal/invalidating"
      25              :         "github.com/cockroachdb/pebble/internal/invariants"
      26              :         "github.com/cockroachdb/pebble/internal/keyspan"
      27              :         "github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
      28              :         "github.com/cockroachdb/pebble/internal/manifest"
      29              :         "github.com/cockroachdb/pebble/internal/manual"
      30              :         "github.com/cockroachdb/pebble/internal/problemspans"
      31              :         "github.com/cockroachdb/pebble/objstorage"
      32              :         "github.com/cockroachdb/pebble/objstorage/remote"
      33              :         "github.com/cockroachdb/pebble/rangekey"
      34              :         "github.com/cockroachdb/pebble/record"
      35              :         "github.com/cockroachdb/pebble/sstable"
      36              :         "github.com/cockroachdb/pebble/sstable/blob"
      37              :         "github.com/cockroachdb/pebble/sstable/block"
      38              :         "github.com/cockroachdb/pebble/vfs"
      39              :         "github.com/cockroachdb/pebble/vfs/atomicfs"
      40              :         "github.com/cockroachdb/pebble/wal"
      41              :         "github.com/cockroachdb/tokenbucket"
      42              :         "github.com/prometheus/client_golang/prometheus"
      43              : )
      44              : 
      45              : const (
      46              :         // minFileCacheSize is the minimum size of the file cache, for a single db.
      47              :         minFileCacheSize = 64
      48              : 
      49              :         // numNonFileCacheFiles is an approximation for the number of files
      50              :         // that we don't account for in the file cache, for a given db.
      51              :         numNonFileCacheFiles = 10
      52              : )
      53              : 
      54              : var (
      55              :         // ErrNotFound is returned when a get operation does not find the requested
      56              :         // key.
      57              :         ErrNotFound = base.ErrNotFound
      58              :         // ErrClosed is panicked when an operation is performed on a closed snapshot or
      59              :         // DB. Use errors.Is(err, ErrClosed) to check for this error.
      60              :         ErrClosed = errors.New("pebble: closed")
      61              :         // ErrReadOnly is returned when a write operation is performed on a read-only
      62              :         // database.
      63              :         ErrReadOnly = errors.New("pebble: read-only")
      64              :         // errNoSplit indicates that the user is trying to perform a range key
      65              :         // operation but the configured Comparer does not provide a Split
      66              :         // implementation.
      67              :         errNoSplit = errors.New("pebble: Comparer.Split required for range key operations")
      68              : )
      69              : 
      70              : // Reader is a readable key/value store.
      71              : //
      72              : // It is safe to call Get and NewIter from concurrent goroutines.
      73              : type Reader interface {
      74              :         // Get gets the value for the given key. It returns ErrNotFound if the DB
      75              :         // does not contain the key.
      76              :         //
      77              :         // The caller should not modify the contents of the returned slice, but it is
      78              :         // safe to modify the contents of the argument after Get returns. The
      79              :         // returned slice will remain valid until the returned Closer is closed. On
      80              :         // success, the caller MUST call closer.Close() or a memory leak will occur.
      81              :         Get(key []byte) (value []byte, closer io.Closer, err error)
      82              : 
      83              :         // NewIter returns an iterator that is unpositioned (Iterator.Valid() will
      84              :         // return false). The iterator can be positioned via a call to SeekGE,
      85              :         // SeekLT, First or Last.
      86              :         NewIter(o *IterOptions) (*Iterator, error)
      87              : 
      88              :         // NewIterWithContext is like NewIter, and additionally accepts a context
      89              :         // for tracing.
      90              :         NewIterWithContext(ctx context.Context, o *IterOptions) (*Iterator, error)
      91              : 
      92              :         // Close closes the Reader. It may or may not close any underlying io.Reader
      93              :         // or io.Writer, depending on how the DB was created.
      94              :         //
      95              :         // It is not safe to close a DB until all outstanding iterators are closed.
      96              :         // It is valid to call Close multiple times. Other methods should not be
      97              :         // called after the DB has been closed.
      98              :         Close() error
      99              : }
     100              : 
     101              : // Writer is a writable key/value store.
     102              : //
     103              : // Goroutine safety is dependent on the specific implementation.
     104              : type Writer interface {
     105              :         // Apply the operations contained in the batch to the DB.
     106              :         //
     107              :         // It is safe to modify the contents of the arguments after Apply returns.
     108              :         Apply(batch *Batch, o *WriteOptions) error
     109              : 
     110              :         // Delete deletes the value for the given key. Deletes are blind all will
     111              :         // succeed even if the given key does not exist.
     112              :         //
     113              :         // It is safe to modify the contents of the arguments after Delete returns.
     114              :         Delete(key []byte, o *WriteOptions) error
     115              : 
     116              :         // DeleteSized behaves identically to Delete, but takes an additional
     117              :         // argument indicating the size of the value being deleted. DeleteSized
     118              :         // should be preferred when the caller has the expectation that there exists
     119              :         // a single internal KV pair for the key (eg, the key has not been
     120              :         // overwritten recently), and the caller knows the size of its value.
     121              :         //
     122              :         // DeleteSized will record the value size within the tombstone and use it to
     123              :         // inform compaction-picking heuristics which strive to reduce space
     124              :         // amplification in the LSM. This "calling your shot" mechanic allows the
     125              :         // storage engine to more accurately estimate and reduce space
     126              :         // amplification.
     127              :         //
     128              :         // It is safe to modify the contents of the arguments after DeleteSized
     129              :         // returns.
     130              :         DeleteSized(key []byte, valueSize uint32, _ *WriteOptions) error
     131              : 
     132              :         // SingleDelete is similar to Delete in that it deletes the value for the given key. Like Delete,
     133              :         // it is a blind operation that will succeed even if the given key does not exist.
     134              :         //
     135              :         // WARNING: Undefined (non-deterministic) behavior will result if a key is overwritten and
     136              :         // then deleted using SingleDelete. The record may appear deleted immediately, but be
     137              :         // resurrected at a later time after compactions have been performed. Or the record may
     138              :         // be deleted permanently. A Delete operation lays down a "tombstone" which shadows all
     139              :         // previous versions of a key. The SingleDelete operation is akin to "anti-matter" and will
     140              :         // only delete the most recently written version for a key. These different semantics allow
     141              :         // the DB to avoid propagating a SingleDelete operation during a compaction as soon as the
     142              :         // corresponding Set operation is encountered. These semantics require extreme care to handle
     143              :         // properly. Only use if you have a workload where the performance gain is critical and you
     144              :         // can guarantee that a record is written once and then deleted once.
     145              :         //
     146              :         // Note that SINGLEDEL, SET, SINGLEDEL, SET, DEL/RANGEDEL, ... from most
     147              :         // recent to older will work as intended since there is a single SET
     148              :         // sandwiched between SINGLEDEL/DEL/RANGEDEL.
     149              :         //
     150              :         // IMPLEMENTATION WARNING: By offering SingleDelete, Pebble must guarantee
     151              :         // that there is no duplication of writes inside Pebble. That is, idempotent
     152              :         // application of writes is insufficient. For example, if a SET operation
     153              :         // gets duplicated inside Pebble, resulting in say SET#20 and SET#17, the
     154              :         // caller may issue a SINGLEDEL#25 and it will not have the desired effect.
     155              :         // A duplication where a SET#20 is duplicated across two sstables will have
     156              :         // the same correctness problem, since the SINGLEDEL may meet one of the
     157              :         // SETs. This guarantee is partially achieved by ensuring that a WAL and a
     158              :         // flushable are usually in one-to-one correspondence, and atomically
     159              :         // updating the MANIFEST when the flushable is flushed (which ensures the
     160              :         // WAL will never be replayed). There is one exception: a flushableBatch (a
     161              :         // batch too large to fit in a memtable) is written to the end of the WAL
     162              :         // that it shares with the preceding memtable. This is safe because the
     163              :         // memtable and the flushableBatch are part of the same flush (see DB.flush1
     164              :         // where this invariant is maintained). If the memtable were to be flushed
     165              :         // without the flushableBatch, the WAL cannot yet be deleted and if a crash
     166              :         // happened, the WAL would be replayed despite the memtable already being
     167              :         // flushed.
     168              :         //
     169              :         // It is safe to modify the contents of the arguments after SingleDelete returns.
     170              :         SingleDelete(key []byte, o *WriteOptions) error
     171              : 
     172              :         // DeleteRange deletes all of the point keys (and values) in the range
     173              :         // [start,end) (inclusive on start, exclusive on end). DeleteRange does NOT
     174              :         // delete overlapping range keys (eg, keys set via RangeKeySet).
     175              :         //
     176              :         // It is safe to modify the contents of the arguments after DeleteRange
     177              :         // returns.
     178              :         DeleteRange(start, end []byte, o *WriteOptions) error
     179              : 
     180              :         // LogData adds the specified to the batch. The data will be written to the
     181              :         // WAL, but not added to memtables or sstables. Log data is never indexed,
     182              :         // which makes it useful for testing WAL performance.
     183              :         //
     184              :         // It is safe to modify the contents of the argument after LogData returns.
     185              :         LogData(data []byte, opts *WriteOptions) error
     186              : 
     187              :         // Merge merges the value for the given key. The details of the merge are
     188              :         // dependent upon the configured merge operation.
     189              :         //
     190              :         // It is safe to modify the contents of the arguments after Merge returns.
     191              :         Merge(key, value []byte, o *WriteOptions) error
     192              : 
     193              :         // Set sets the value for the given key. It overwrites any previous value
     194              :         // for that key; a DB is not a multi-map.
     195              :         //
     196              :         // It is safe to modify the contents of the arguments after Set returns.
     197              :         Set(key, value []byte, o *WriteOptions) error
     198              : 
     199              :         // RangeKeySet sets a range key mapping the key range [start, end) at the MVCC
     200              :         // timestamp suffix to value. The suffix is optional. If any portion of the key
     201              :         // range [start, end) is already set by a range key with the same suffix value,
     202              :         // RangeKeySet overrides it.
     203              :         //
     204              :         // It is safe to modify the contents of the arguments after RangeKeySet returns.
     205              :         RangeKeySet(start, end, suffix, value []byte, opts *WriteOptions) error
     206              : 
     207              :         // RangeKeyUnset removes a range key mapping the key range [start, end) at the
     208              :         // MVCC timestamp suffix. The suffix may be omitted to remove an unsuffixed
     209              :         // range key. RangeKeyUnset only removes portions of range keys that fall within
     210              :         // the [start, end) key span, and only range keys with suffixes that exactly
     211              :         // match the unset suffix.
     212              :         //
     213              :         // It is safe to modify the contents of the arguments after RangeKeyUnset
     214              :         // returns.
     215              :         RangeKeyUnset(start, end, suffix []byte, opts *WriteOptions) error
     216              : 
     217              :         // RangeKeyDelete deletes all of the range keys in the range [start,end)
     218              :         // (inclusive on start, exclusive on end). It does not delete point keys (for
     219              :         // that use DeleteRange). RangeKeyDelete removes all range keys within the
     220              :         // bounds, including those with or without suffixes.
     221              :         //
     222              :         // It is safe to modify the contents of the arguments after RangeKeyDelete
     223              :         // returns.
     224              :         RangeKeyDelete(start, end []byte, opts *WriteOptions) error
     225              : }
     226              : 
     227              : // DB provides a concurrent, persistent ordered key/value store.
     228              : //
     229              : // A DB's basic operations (Get, Set, Delete) should be self-explanatory. Get
     230              : // and Delete will return ErrNotFound if the requested key is not in the store.
     231              : // Callers are free to ignore this error.
     232              : //
     233              : // A DB also allows for iterating over the key/value pairs in key order. If d
     234              : // is a DB, the code below prints all key/value pairs whose keys are 'greater
     235              : // than or equal to' k:
     236              : //
     237              : //      iter := d.NewIter(readOptions)
     238              : //      for iter.SeekGE(k); iter.Valid(); iter.Next() {
     239              : //              fmt.Printf("key=%q value=%q\n", iter.Key(), iter.Value())
     240              : //      }
     241              : //      return iter.Close()
     242              : //
     243              : // The Options struct holds the optional parameters for the DB, including a
     244              : // Comparer to define a 'less than' relationship over keys. It is always valid
     245              : // to pass a nil *Options, which means to use the default parameter values. Any
     246              : // zero field of a non-nil *Options also means to use the default value for
     247              : // that parameter. Thus, the code below uses a custom Comparer, but the default
     248              : // values for every other parameter:
     249              : //
     250              : //      db := pebble.Open(&Options{
     251              : //              Comparer: myComparer,
     252              : //      })
     253              : type DB struct {
     254              :         // The count and size of referenced memtables. This includes memtables
     255              :         // present in DB.mu.mem.queue, as well as memtables that have been flushed
     256              :         // but are still referenced by an inuse readState, as well as up to one
     257              :         // memTable waiting to be reused and stored in d.memTableRecycle.
     258              :         memTableCount    atomic.Int64
     259              :         memTableReserved atomic.Int64 // number of bytes reserved in the cache for memtables
     260              :         // memTableRecycle holds a pointer to an obsolete memtable. The next
     261              :         // memtable allocation will reuse this memtable if it has not already been
     262              :         // recycled.
     263              :         memTableRecycle atomic.Pointer[memTable]
     264              : 
     265              :         // The logical size of the current WAL.
     266              :         logSize atomic.Uint64
     267              :         // The number of input bytes to the log. This is the raw size of the
     268              :         // batches written to the WAL, without the overhead of the record
     269              :         // envelopes.
     270              :         logBytesIn atomic.Uint64
     271              : 
     272              :         // The number of bytes available on disk.
     273              :         diskAvailBytes       atomic.Uint64
     274              :         lowDiskSpaceReporter lowDiskSpaceReporter
     275              : 
     276              :         cacheHandle    *cache.Handle
     277              :         dirname        string
     278              :         opts           *Options
     279              :         cmp            Compare
     280              :         equal          Equal
     281              :         merge          Merge
     282              :         split          Split
     283              :         abbreviatedKey AbbreviatedKey
     284              :         // The threshold for determining when a batch is "large" and will skip being
     285              :         // inserted into a memtable.
     286              :         largeBatchThreshold uint64
     287              :         // The current OPTIONS file number.
     288              :         optionsFileNum base.DiskFileNum
     289              :         // The on-disk size of the current OPTIONS file.
     290              :         optionsFileSize uint64
     291              : 
     292              :         // objProvider is used to access and manage SSTs.
     293              :         objProvider objstorage.Provider
     294              : 
     295              :         dataDirLock *base.DirLock
     296              :         dataDir     vfs.File
     297              : 
     298              :         fileCache            *fileCacheHandle
     299              :         newIters             tableNewIters
     300              :         tableNewRangeKeyIter keyspanimpl.TableNewSpanIter
     301              : 
     302              :         commit *commitPipeline
     303              : 
     304              :         // readState provides access to the state needed for reading without needing
     305              :         // to acquire DB.mu.
     306              :         readState struct {
     307              :                 sync.RWMutex
     308              :                 val *readState
     309              :         }
     310              : 
     311              :         closed   *atomic.Value
     312              :         closedCh chan struct{}
     313              : 
     314              :         cleanupManager *cleanupManager
     315              : 
     316              :         compactionScheduler CompactionScheduler
     317              : 
     318              :         // During an iterator close, we may asynchronously schedule read compactions.
     319              :         // We want to wait for those goroutines to finish, before closing the DB.
     320              :         // compactionShedulers.Wait() should not be called while the DB.mu is held.
     321              :         compactionSchedulers sync.WaitGroup
     322              : 
     323              :         // The main mutex protecting internal DB state. This mutex encompasses many
     324              :         // fields because those fields need to be accessed and updated atomically. In
     325              :         // particular, the current version, log.*, mem.*, and snapshot list need to
     326              :         // be accessed and updated atomically during compaction.
     327              :         //
     328              :         // Care is taken to avoid holding DB.mu during IO operations. Accomplishing
     329              :         // this sometimes requires releasing DB.mu in a method that was called with
     330              :         // it held. See versionSet.UpdateVersionLocked() and DB.makeRoomForWrite() for
     331              :         // examples. This is a common pattern, so be careful about expectations that
     332              :         // DB.mu will be held continuously across a set of calls.
     333              :         mu struct {
     334              :                 sync.Mutex
     335              : 
     336              :                 formatVers struct {
     337              :                         // vers is the database's current format major version.
     338              :                         // Backwards-incompatible features are gated behind new
     339              :                         // format major versions and not enabled until a database's
     340              :                         // version is ratcheted upwards.
     341              :                         //
     342              :                         // Although this is under the `mu` prefix, readers may read vers
     343              :                         // atomically without holding d.mu. Writers must only write to this
     344              :                         // value through finalizeFormatVersUpgrade which requires d.mu is
     345              :                         // held.
     346              :                         vers atomic.Uint64
     347              :                         // marker is the atomic marker for the format major version.
     348              :                         // When a database's version is ratcheted upwards, the
     349              :                         // marker is moved in order to atomically record the new
     350              :                         // version.
     351              :                         marker *atomicfs.Marker
     352              :                         // ratcheting when set to true indicates that the database is
     353              :                         // currently in the process of ratcheting the format major version
     354              :                         // to vers + 1. As a part of ratcheting the format major version,
     355              :                         // migrations may drop and re-acquire the mutex.
     356              :                         ratcheting bool
     357              :                 }
     358              : 
     359              :                 // The ID of the next job. Job IDs are passed to event listener
     360              :                 // notifications and act as a mechanism for tying together the events and
     361              :                 // log messages for a single job such as a flush, compaction, or file
     362              :                 // ingestion. Job IDs are not serialized to disk or used for correctness.
     363              :                 nextJobID JobID
     364              : 
     365              :                 // The collection of immutable versions and state about the log and visible
     366              :                 // sequence numbers. Use the pointer here to ensure the atomic fields in
     367              :                 // version set are aligned properly.
     368              :                 versions *versionSet
     369              : 
     370              :                 log struct {
     371              :                         // manager is not protected by mu, but calls to Create must be
     372              :                         // serialized, and happen after the previous writer is closed.
     373              :                         manager wal.Manager
     374              :                         // The Writer is protected by commitPipeline.mu. This allows log writes
     375              :                         // to be performed without holding DB.mu, but requires both
     376              :                         // commitPipeline.mu and DB.mu to be held when rotating the WAL/memtable
     377              :                         // (i.e. makeRoomForWrite). Can be nil.
     378              :                         writer  wal.Writer
     379              :                         metrics struct {
     380              :                                 // fsyncLatency has its own internal synchronization, and is not
     381              :                                 // protected by mu.
     382              :                                 fsyncLatency prometheus.Histogram
     383              :                                 // Updated whenever a wal.Writer is closed.
     384              :                                 record.LogWriterMetrics
     385              :                         }
     386              :                 }
     387              : 
     388              :                 mem struct {
     389              :                         // The current mutable memTable. Readers of the pointer may hold
     390              :                         // either DB.mu or commitPipeline.mu.
     391              :                         //
     392              :                         // Its internal fields are protected by commitPipeline.mu. This
     393              :                         // allows batch commits to be performed without DB.mu as long as no
     394              :                         // memtable rotation is required.
     395              :                         //
     396              :                         // Both commitPipeline.mu and DB.mu must be held when rotating the
     397              :                         // memtable.
     398              :                         mutable *memTable
     399              :                         // Queue of flushables (the mutable memtable is at end). Elements are
     400              :                         // added to the end of the slice and removed from the beginning. Once an
     401              :                         // index is set it is never modified making a fixed slice immutable and
     402              :                         // safe for concurrent reads.
     403              :                         queue flushableList
     404              :                         // nextSize is the size of the next memtable. The memtable size starts at
     405              :                         // min(256KB,Options.MemTableSize) and doubles each time a new memtable
     406              :                         // is allocated up to Options.MemTableSize. This reduces the memory
     407              :                         // footprint of memtables when lots of DB instances are used concurrently
     408              :                         // in test environments.
     409              :                         nextSize uint64
     410              :                 }
     411              : 
     412              :                 compact struct {
     413              :                         // Condition variable used to signal when a flush or compaction has
     414              :                         // completed. Used by the write-stall mechanism to wait for the stall
     415              :                         // condition to clear. See DB.makeRoomForWrite().
     416              :                         cond sync.Cond
     417              :                         // True when a flush is in progress.
     418              :                         flushing bool
     419              :                         // The number of ongoing non-download compactions.
     420              :                         compactingCount int
     421              :                         // The number of download compactions.
     422              :                         downloadingCount int
     423              :                         // The list of deletion hints, suggesting ranges for delete-only
     424              :                         // compactions.
     425              :                         deletionHints []deleteCompactionHint
     426              :                         // The list of manual compactions. The next manual compaction to perform
     427              :                         // is at the start of the list. New entries are added to the end.
     428              :                         manual    []*manualCompaction
     429              :                         manualLen atomic.Int32
     430              :                         // manualID is used to identify manualCompactions in the manual slice.
     431              :                         manualID uint64
     432              :                         // downloads is the list of pending download tasks. The next download to
     433              :                         // perform is at the start of the list. New entries are added to the end.
     434              :                         downloads []*downloadSpanTask
     435              :                         // inProgress is the set of in-progress flushes and compactions.
     436              :                         // It's used in the calculation of some metrics and to initialize L0
     437              :                         // sublevels' state. Some of the compactions contained within this
     438              :                         // map may have already committed an edit to the version but are
     439              :                         // lingering performing cleanup, like deleting obsolete files.
     440              :                         inProgress map[compaction]struct{}
     441              :                         // burstConcurrency is the number of additional compaction
     442              :                         // concurrency slots that have been added in order to allow
     443              :                         // high-priority compactions to run.
     444              :                         //
     445              :                         // Today, it's used when scheduling 'high priority' blob file
     446              :                         // rewrite compactions to reclaim disk space. Normally compactions
     447              :                         // that reclaim disk space and don't reshape the LSM are considered
     448              :                         // low priority. If there's sufficient space amplification,
     449              :                         // heuristics may decide to let these space-reclamation compactions
     450              :                         // run anyways.
     451              :                         //
     452              :                         // In this case we don't want to steal concurrency from the default
     453              :                         // compactions, so we temporarily inflate the allowed compaction
     454              :                         // concurrency for the duration of the compaction. This field is the
     455              :                         // count of compactions within inProgress for which
     456              :                         // UsesBurstConcurrency is true. It's incremented when one begins
     457              :                         // and decremented when it completes.
     458              :                         burstConcurrency atomic.Int32
     459              : 
     460              :                         // rescheduleReadCompaction indicates to an iterator that a read compaction
     461              :                         // should be scheduled.
     462              :                         rescheduleReadCompaction bool
     463              : 
     464              :                         // readCompactions is a readCompactionQueue which keeps track of the
     465              :                         // compactions which we might have to perform.
     466              :                         readCompactions readCompactionQueue
     467              : 
     468              :                         // The cumulative duration of all completed compactions since Open.
     469              :                         // Does not include flushes.
     470              :                         duration time.Duration
     471              :                         // Flush throughput metric.
     472              :                         flushWriteThroughput ThroughputMetric
     473              :                         // The idle start time for the flush "loop", i.e., when the flushing
     474              :                         // bool above transitions to false.
     475              :                         noOngoingFlushStartTime crtime.Mono
     476              :                 }
     477              : 
     478              :                 fileDeletions struct {
     479              :                         // Non-zero when file cleaning is disableCount. The disableCount
     480              :                         // count acts as a reference count to prohibit file cleaning. See
     481              :                         // DB.{disable,enable}FileDeletions().
     482              :                         disableCount int
     483              :                         // queuedStats holds cumulative stats for files that have been
     484              :                         // queued for deletion by the cleanup manager. These stats are
     485              :                         // monotonically increasing for the *DB's lifetime.
     486              :                         queuedStats obsoleteObjectStats
     487              :                 }
     488              : 
     489              :                 snapshots struct {
     490              :                         // The list of active snapshots.
     491              :                         snapshotList
     492              : 
     493              :                         // The cumulative count and size of snapshot-pinned keys written to
     494              :                         // sstables.
     495              :                         cumulativePinnedCount uint64
     496              :                         cumulativePinnedSize  uint64
     497              :                 }
     498              : 
     499              :                 tableStats struct {
     500              :                         // Condition variable used to signal the completion of a
     501              :                         // job to collect table stats.
     502              :                         cond sync.Cond
     503              :                         // True when a stat collection operation is in progress.
     504              :                         loading bool
     505              :                         // True if stat collection has loaded statistics for all tables
     506              :                         // other than those listed explicitly in pending. This flag starts
     507              :                         // as false when a database is opened and flips to true once stat
     508              :                         // collection has caught up.
     509              :                         loadedInitial bool
     510              :                         // A slice of files for which stats have not been computed.
     511              :                         // Compactions, ingests, flushes append files to be processed. An
     512              :                         // active stat collection goroutine clears the list and processes
     513              :                         // them.
     514              :                         pending []manifest.NewTableEntry
     515              :                 }
     516              : 
     517              :                 tableValidation struct {
     518              :                         // cond is a condition variable used to signal the completion of a
     519              :                         // job to validate one or more sstables.
     520              :                         cond sync.Cond
     521              :                         // pending is a slice of metadata for sstables waiting to be
     522              :                         // validated. Only physical sstables should be added to the pending
     523              :                         // queue.
     524              :                         pending []manifest.NewTableEntry
     525              :                         // validating is set to true when validation is running.
     526              :                         validating bool
     527              :                 }
     528              :         }
     529              : 
     530              :         fileSizeAnnotator manifest.TableAnnotator[fileSizeByBacking]
     531              : 
     532              :         // problemSpans keeps track of spans of keys within LSM levels where
     533              :         // compactions have failed; used to avoid retrying these compactions too
     534              :         // quickly.
     535              :         problemSpans problemspans.ByLevel
     536              : 
     537              :         // Normally equal to time.Now() but may be overridden in tests.
     538              :         timeNow func() time.Time
     539              :         // the time at database Open; may be used to compute metrics like effective
     540              :         // compaction concurrency
     541              :         openedAt time.Time
     542              : }
     543              : 
     544              : var _ Reader = (*DB)(nil)
     545              : var _ Writer = (*DB)(nil)
     546              : 
     547              : // TestOnlyWaitForCleaning MUST only be used in tests.
     548            1 : func (d *DB) TestOnlyWaitForCleaning() {
     549            1 :         d.cleanupManager.Wait()
     550            1 : }
     551              : 
     552              : // Set sets the value for the given key. It overwrites any previous value
     553              : // for that key; a DB is not a multi-map.
     554              : //
     555              : // It is safe to modify the contents of the arguments after Set returns.
     556            1 : func (d *DB) Set(key, value []byte, opts *WriteOptions) error {
     557            1 :         b := newBatch(d)
     558            1 :         _ = b.Set(key, value, opts)
     559            1 :         if err := d.Apply(b, opts); err != nil {
     560            1 :                 return err
     561            1 :         }
     562              :         // Only release the batch on success.
     563            1 :         return b.Close()
     564              : }
     565              : 
     566              : // Delete deletes the value for the given key. Deletes are blind all will
     567              : // succeed even if the given key does not exist.
     568              : //
     569              : // It is safe to modify the contents of the arguments after Delete returns.
     570            1 : func (d *DB) Delete(key []byte, opts *WriteOptions) error {
     571            1 :         b := newBatch(d)
     572            1 :         _ = b.Delete(key, opts)
     573            1 :         if err := d.Apply(b, opts); err != nil {
     574            1 :                 return err
     575            1 :         }
     576              :         // Only release the batch on success.
     577            1 :         return b.Close()
     578              : }
     579              : 
     580              : // DeleteSized behaves identically to Delete, but takes an additional
     581              : // argument indicating the size of the value being deleted. DeleteSized
     582              : // should be preferred when the caller has the expectation that there exists
     583              : // a single internal KV pair for the key (eg, the key has not been
     584              : // overwritten recently), and the caller knows the size of its value.
     585              : //
     586              : // DeleteSized will record the value size within the tombstone and use it to
     587              : // inform compaction-picking heuristics which strive to reduce space
     588              : // amplification in the LSM. This "calling your shot" mechanic allows the
     589              : // storage engine to more accurately estimate and reduce space amplification.
     590              : //
     591              : // It is safe to modify the contents of the arguments after DeleteSized
     592              : // returns.
     593            1 : func (d *DB) DeleteSized(key []byte, valueSize uint32, opts *WriteOptions) error {
     594            1 :         b := newBatch(d)
     595            1 :         _ = b.DeleteSized(key, valueSize, opts)
     596            1 :         if err := d.Apply(b, opts); err != nil {
     597            0 :                 return err
     598            0 :         }
     599              :         // Only release the batch on success.
     600            1 :         return b.Close()
     601              : }
     602              : 
     603              : // SingleDelete adds an action to the batch that single deletes the entry for key.
     604              : // See Writer.SingleDelete for more details on the semantics of SingleDelete.
     605              : //
     606              : // WARNING: See the detailed warning in Writer.SingleDelete before using this.
     607              : //
     608              : // It is safe to modify the contents of the arguments after SingleDelete returns.
     609            1 : func (d *DB) SingleDelete(key []byte, opts *WriteOptions) error {
     610            1 :         b := newBatch(d)
     611            1 :         _ = b.SingleDelete(key, opts)
     612            1 :         if err := d.Apply(b, opts); err != nil {
     613            0 :                 return err
     614            0 :         }
     615              :         // Only release the batch on success.
     616            1 :         return b.Close()
     617              : }
     618              : 
     619              : // DeleteRange deletes all of the keys (and values) in the range [start,end)
     620              : // (inclusive on start, exclusive on end).
     621              : //
     622              : // It is safe to modify the contents of the arguments after DeleteRange
     623              : // returns.
     624            1 : func (d *DB) DeleteRange(start, end []byte, opts *WriteOptions) error {
     625            1 :         b := newBatch(d)
     626            1 :         _ = b.DeleteRange(start, end, opts)
     627            1 :         if err := d.Apply(b, opts); err != nil {
     628            1 :                 return err
     629            1 :         }
     630              :         // Only release the batch on success.
     631            1 :         return b.Close()
     632              : }
     633              : 
     634              : // Merge adds an action to the DB that merges the value at key with the new
     635              : // value. The details of the merge are dependent upon the configured merge
     636              : // operator.
     637              : //
     638              : // It is safe to modify the contents of the arguments after Merge returns.
     639            1 : func (d *DB) Merge(key, value []byte, opts *WriteOptions) error {
     640            1 :         b := newBatch(d)
     641            1 :         _ = b.Merge(key, value, opts)
     642            1 :         if err := d.Apply(b, opts); err != nil {
     643            1 :                 return err
     644            1 :         }
     645              :         // Only release the batch on success.
     646            1 :         return b.Close()
     647              : }
     648              : 
     649              : // LogData adds the specified to the batch. The data will be written to the
     650              : // WAL, but not added to memtables or sstables. Log data is never indexed,
     651              : // which makes it useful for testing WAL performance.
     652              : //
     653              : // It is safe to modify the contents of the argument after LogData returns.
     654            1 : func (d *DB) LogData(data []byte, opts *WriteOptions) error {
     655            1 :         b := newBatch(d)
     656            1 :         _ = b.LogData(data, opts)
     657            1 :         if err := d.Apply(b, opts); err != nil {
     658            1 :                 return err
     659            1 :         }
     660              :         // Only release the batch on success.
     661            1 :         return b.Close()
     662              : }
     663              : 
     664              : // RangeKeySet sets a range key mapping the key range [start, end) at the MVCC
     665              : // timestamp suffix to value. The suffix is optional. If any portion of the key
     666              : // range [start, end) is already set by a range key with the same suffix value,
     667              : // RangeKeySet overrides it.
     668              : //
     669              : // It is safe to modify the contents of the arguments after RangeKeySet returns.
     670            1 : func (d *DB) RangeKeySet(start, end, suffix, value []byte, opts *WriteOptions) error {
     671            1 :         b := newBatch(d)
     672            1 :         _ = b.RangeKeySet(start, end, suffix, value, opts)
     673            1 :         if err := d.Apply(b, opts); err != nil {
     674            0 :                 return err
     675            0 :         }
     676              :         // Only release the batch on success.
     677            1 :         return b.Close()
     678              : }
     679              : 
     680              : // RangeKeyUnset removes a range key mapping the key range [start, end) at the
     681              : // MVCC timestamp suffix. The suffix may be omitted to remove an unsuffixed
     682              : // range key. RangeKeyUnset only removes portions of range keys that fall within
     683              : // the [start, end) key span, and only range keys with suffixes that exactly
     684              : // match the unset suffix.
     685              : //
     686              : // It is safe to modify the contents of the arguments after RangeKeyUnset
     687              : // returns.
     688            1 : func (d *DB) RangeKeyUnset(start, end, suffix []byte, opts *WriteOptions) error {
     689            1 :         b := newBatch(d)
     690            1 :         _ = b.RangeKeyUnset(start, end, suffix, opts)
     691            1 :         if err := d.Apply(b, opts); err != nil {
     692            0 :                 return err
     693            0 :         }
     694              :         // Only release the batch on success.
     695            1 :         return b.Close()
     696              : }
     697              : 
     698              : // RangeKeyDelete deletes all of the range keys in the range [start,end)
     699              : // (inclusive on start, exclusive on end). It does not delete point keys (for
     700              : // that use DeleteRange). RangeKeyDelete removes all range keys within the
     701              : // bounds, including those with or without suffixes.
     702              : //
     703              : // It is safe to modify the contents of the arguments after RangeKeyDelete
     704              : // returns.
     705            1 : func (d *DB) RangeKeyDelete(start, end []byte, opts *WriteOptions) error {
     706            1 :         b := newBatch(d)
     707            1 :         _ = b.RangeKeyDelete(start, end, opts)
     708            1 :         if err := d.Apply(b, opts); err != nil {
     709            0 :                 return err
     710            0 :         }
     711              :         // Only release the batch on success.
     712            1 :         return b.Close()
     713              : }
     714              : 
     715              : // Apply the operations contained in the batch to the DB. If the batch is large
     716              : // the contents of the batch may be retained by the database. If that occurs
     717              : // the batch contents will be cleared preventing the caller from attempting to
     718              : // reuse them.
     719              : //
     720              : // It is safe to modify the contents of the arguments after Apply returns.
     721              : //
     722              : // Apply returns ErrInvalidBatch if the provided batch is invalid in any way.
     723            1 : func (d *DB) Apply(batch *Batch, opts *WriteOptions) error {
     724            1 :         return d.applyInternal(batch, opts, false)
     725            1 : }
     726              : 
     727              : // ApplyNoSyncWait must only be used when opts.Sync is true and the caller
     728              : // does not want to wait for the WAL fsync to happen. The method will return
     729              : // once the mutation is applied to the memtable and is visible (note that a
     730              : // mutation is visible before the WAL sync even in the wait case, so we have
     731              : // not weakened the durability semantics). The caller must call Batch.SyncWait
     732              : // to wait for the WAL fsync. The caller must not Close the batch without
     733              : // first calling Batch.SyncWait.
     734              : //
     735              : // RECOMMENDATION: Prefer using Apply unless you really understand why you
     736              : // need ApplyNoSyncWait.
     737              : // EXPERIMENTAL: API/feature subject to change. Do not yet use outside
     738              : // CockroachDB.
     739            1 : func (d *DB) ApplyNoSyncWait(batch *Batch, opts *WriteOptions) error {
     740            1 :         if !opts.Sync {
     741            0 :                 return errors.Errorf("cannot request asynchonous apply when WriteOptions.Sync is false")
     742            0 :         }
     743            1 :         return d.applyInternal(batch, opts, true)
     744              : }
     745              : 
     746              : // REQUIRES: noSyncWait => opts.Sync
     747            1 : func (d *DB) applyInternal(batch *Batch, opts *WriteOptions, noSyncWait bool) error {
     748            1 :         if err := d.closed.Load(); err != nil {
     749            1 :                 panic(err)
     750              :         }
     751            1 :         if batch.committing {
     752            0 :                 panic("pebble: batch already committing")
     753              :         }
     754            1 :         if batch.applied.Load() {
     755            0 :                 panic("pebble: batch already applied")
     756              :         }
     757            1 :         if d.opts.ReadOnly {
     758            1 :                 return ErrReadOnly
     759            1 :         }
     760            1 :         if batch.db != nil && batch.db != d {
     761            1 :                 panic(fmt.Sprintf("pebble: batch db mismatch: %p != %p", batch.db, d))
     762              :         }
     763              : 
     764            1 :         sync := opts.GetSync()
     765            1 :         if sync && d.opts.DisableWAL {
     766            0 :                 return errors.New("pebble: WAL disabled")
     767            0 :         }
     768              : 
     769            1 :         if fmv := d.FormatMajorVersion(); fmv < batch.minimumFormatMajorVersion {
     770            0 :                 panic(fmt.Sprintf(
     771            0 :                         "pebble: batch requires at least format major version %d (current: %d)",
     772            0 :                         batch.minimumFormatMajorVersion, fmv,
     773            0 :                 ))
     774              :         }
     775              : 
     776            1 :         if batch.countRangeKeys > 0 {
     777            1 :                 if d.split == nil {
     778            0 :                         return errNoSplit
     779            0 :                 }
     780              :         }
     781            1 :         batch.committing = true
     782            1 : 
     783            1 :         if batch.db == nil {
     784            1 :                 if err := batch.refreshMemTableSize(); err != nil {
     785            0 :                         return err
     786            0 :                 }
     787              :         }
     788            1 :         if batch.memTableSize >= d.largeBatchThreshold {
     789            1 :                 var err error
     790            1 :                 batch.flushable, err = newFlushableBatch(batch, d.opts.Comparer)
     791            1 :                 if err != nil {
     792            0 :                         return err
     793            0 :                 }
     794              :         }
     795            1 :         if err := d.commit.Commit(batch, sync, noSyncWait); err != nil {
     796            0 :                 // There isn't much we can do on an error here. The commit pipeline will be
     797            0 :                 // horked at this point.
     798            0 :                 d.opts.Logger.Fatalf("pebble: fatal commit error: %v", err)
     799            0 :         }
     800              :         // If this is a large batch, we need to clear the batch contents as the
     801              :         // flushable batch may still be present in the flushables queue.
     802              :         //
     803              :         // TODO(peter): Currently large batches are written to the WAL. We could
     804              :         // skip the WAL write and instead wait for the large batch to be flushed to
     805              :         // an sstable. For a 100 MB batch, this might actually be faster. For a 1
     806              :         // GB batch this is almost certainly faster.
     807            1 :         if batch.flushable != nil {
     808            1 :                 batch.data = nil
     809            1 :         }
     810            1 :         return nil
     811              : }
     812              : 
     813            1 : func (d *DB) commitApply(b *Batch, mem *memTable) error {
     814            1 :         if b.flushable != nil {
     815            1 :                 // This is a large batch which was already added to the immutable queue.
     816            1 :                 return nil
     817            1 :         }
     818            1 :         err := mem.apply(b, b.SeqNum())
     819            1 :         if err != nil {
     820            0 :                 return err
     821            0 :         }
     822              : 
     823              :         // If the batch contains range tombstones and the database is configured
     824              :         // to flush range deletions, schedule a delayed flush so that disk space
     825              :         // may be reclaimed without additional writes or an explicit flush.
     826            1 :         if b.countRangeDels > 0 && d.opts.FlushDelayDeleteRange > 0 {
     827            1 :                 d.mu.Lock()
     828            1 :                 d.maybeScheduleDelayedFlush(mem, d.opts.FlushDelayDeleteRange)
     829            1 :                 d.mu.Unlock()
     830            1 :         }
     831              : 
     832              :         // If the batch contains range keys and the database is configured to flush
     833              :         // range keys, schedule a delayed flush so that the range keys are cleared
     834              :         // from the memtable.
     835            1 :         if b.countRangeKeys > 0 && d.opts.FlushDelayRangeKey > 0 {
     836            1 :                 d.mu.Lock()
     837            1 :                 d.maybeScheduleDelayedFlush(mem, d.opts.FlushDelayRangeKey)
     838            1 :                 d.mu.Unlock()
     839            1 :         }
     840              : 
     841            1 :         if mem.writerUnref() {
     842            1 :                 d.mu.Lock()
     843            1 :                 d.maybeScheduleFlush()
     844            1 :                 d.mu.Unlock()
     845            1 :         }
     846            1 :         return nil
     847              : }
     848              : 
     849            1 : func (d *DB) commitWrite(b *Batch, syncWG *sync.WaitGroup, syncErr *error) (*memTable, error) {
     850            1 :         var size int64
     851            1 :         repr := b.Repr()
     852            1 : 
     853            1 :         if b.flushable != nil {
     854            1 :                 // We have a large batch. Such batches are special in that they don't get
     855            1 :                 // added to the memtable, and are instead inserted into the queue of
     856            1 :                 // memtables. The call to makeRoomForWrite with this batch will force the
     857            1 :                 // current memtable to be flushed. We want the large batch to be part of
     858            1 :                 // the same log, so we add it to the WAL here, rather than after the call
     859            1 :                 // to makeRoomForWrite().
     860            1 :                 //
     861            1 :                 // Set the sequence number since it was not set to the correct value earlier
     862            1 :                 // (see comment in newFlushableBatch()).
     863            1 :                 b.flushable.setSeqNum(b.SeqNum())
     864            1 :                 if !d.opts.DisableWAL {
     865            1 :                         var err error
     866            1 :                         size, err = d.mu.log.writer.WriteRecord(repr, wal.SyncOptions{Done: syncWG, Err: syncErr}, b)
     867            1 :                         if err != nil {
     868            0 :                                 panic(err)
     869              :                         }
     870              :                 }
     871              :         }
     872              : 
     873            1 :         var err error
     874            1 :         // Grab a reference to the memtable. We don't hold DB.mu, but we do hold
     875            1 :         // d.commit.mu. It's okay for readers of d.mu.mem.mutable to only hold one of
     876            1 :         // d.commit.mu or d.mu, because memtable rotations require holding both.
     877            1 :         mem := d.mu.mem.mutable
     878            1 :         // Batches which contain keys of kind InternalKeyKindIngestSST will
     879            1 :         // never be applied to the memtable, so we don't need to make room for
     880            1 :         // write.
     881            1 :         if !b.ingestedSSTBatch {
     882            1 :                 // Flushable batches will require a rotation of the memtable regardless,
     883            1 :                 // so only attempt an optimistic reservation of space in the current
     884            1 :                 // memtable if this batch is not a large flushable batch.
     885            1 :                 if b.flushable == nil {
     886            1 :                         err = d.mu.mem.mutable.prepare(b)
     887            1 :                 }
     888            1 :                 if b.flushable != nil || err == arenaskl.ErrArenaFull {
     889            1 :                         // Slow path.
     890            1 :                         // We need to acquire DB.mu and rotate the memtable.
     891            1 :                         func() {
     892            1 :                                 d.mu.Lock()
     893            1 :                                 defer d.mu.Unlock()
     894            1 :                                 err = d.makeRoomForWrite(b)
     895            1 :                                 mem = d.mu.mem.mutable
     896            1 :                         }()
     897              :                 }
     898              :         }
     899            1 :         if err != nil {
     900            0 :                 return nil, err
     901            0 :         }
     902            1 :         if d.opts.DisableWAL {
     903            1 :                 return mem, nil
     904            1 :         }
     905            1 :         d.logBytesIn.Add(uint64(len(repr)))
     906            1 : 
     907            1 :         if b.flushable == nil {
     908            1 :                 size, err = d.mu.log.writer.WriteRecord(repr, wal.SyncOptions{Done: syncWG, Err: syncErr}, b)
     909            1 :                 if err != nil {
     910            0 :                         panic(err)
     911              :                 }
     912              :         }
     913              : 
     914            1 :         d.logSize.Store(uint64(size))
     915            1 :         return mem, err
     916              : }
     917              : 
     918              : type iterAlloc struct {
     919              :         keyBuf              []byte    `invariants:"reused"`
     920              :         boundsBuf           [2][]byte `invariants:"reused"`
     921              :         prefixOrFullSeekKey []byte    `invariants:"reused"`
     922              :         batchState          iteratorBatchState
     923              :         dbi                 Iterator
     924              :         merging             mergingIter
     925              :         mlevels             [3 + numLevels]mergingIterLevel
     926              :         levels              [3 + numLevels]levelIter
     927              :         levelsPositioned    [3 + numLevels]bool
     928              : }
     929              : 
     930              : // maybeAssertZeroed asserts that i is a "zeroed" value. See assertZeroed for
     931              : // the definition of "zeroed". It's used to ensure we're properly zeroing out
     932              : // memory before returning the iterAlloc to the shared pool.
     933            1 : func (i *iterAlloc) maybeAssertZeroed() {
     934            1 :         if invariants.Enabled {
     935            1 :                 v := reflect.ValueOf(i).Elem()
     936            1 :                 if err := assertZeroed(v); err != nil {
     937            0 :                         panic(err)
     938              :                 }
     939              :         }
     940              : }
     941              : 
     942              : // assertZeroed asserts that v is a "zeroed" value. A "zeroed" value is a value
     943              : // that is:
     944              : //   - the Go zero value for its type, or
     945              : //   - a pointer to a "zeroed" value, or
     946              : //   - a slice of len()=0, with any values in the backing array being "zeroed
     947              : //     values", or
     948              : //   - a struct with all fields being "zeroed" values,
     949              : //   - a struct field explicitly marked with a "invariants:reused" tag.
     950            1 : func assertZeroed(v reflect.Value) error {
     951            1 :         if v.IsZero() {
     952            1 :                 return nil
     953            1 :         }
     954            1 :         typ := v.Type()
     955            1 :         switch typ.Kind() {
     956            0 :         case reflect.Pointer:
     957            0 :                 return assertZeroed(v.Elem())
     958            1 :         case reflect.Slice:
     959            1 :                 if v.Len() > 0 {
     960            0 :                         return errors.AssertionFailedf("%s is not zeroed (%d len): %#v", typ.Name(), v.Len(), v)
     961            0 :                 }
     962            1 :                 resliced := v.Slice(0, v.Cap())
     963            1 :                 for i := 0; i < resliced.Len(); i++ {
     964            1 :                         if err := assertZeroed(resliced.Index(i)); err != nil {
     965            0 :                                 return errors.Wrapf(err, "[%d]", i)
     966            0 :                         }
     967              :                 }
     968            1 :                 return nil
     969            1 :         case reflect.Struct:
     970            1 :                 for i := 0; i < typ.NumField(); i++ {
     971            1 :                         if typ.Field(i).Tag.Get("invariants") == "reused" {
     972            1 :                                 continue
     973              :                         }
     974            1 :                         if err := assertZeroed(v.Field(i)); err != nil {
     975            0 :                                 return errors.Wrapf(err, "%q", typ.Field(i).Name)
     976            0 :                         }
     977              :                 }
     978            1 :                 return nil
     979              :         }
     980            0 :         return errors.AssertionFailedf("%s (%s) is not zeroed: %#v", typ.Name(), typ.Kind(), v)
     981              : }
     982              : 
     983            1 : func newIterAlloc() *iterAlloc {
     984            1 :         buf := iterAllocPool.Get().(*iterAlloc)
     985            1 :         buf.maybeAssertZeroed()
     986            1 :         return buf
     987            1 : }
     988              : 
     989              : var iterAllocPool = sync.Pool{
     990            1 :         New: func() interface{} {
     991            1 :                 return &iterAlloc{}
     992            1 :         },
     993              : }
     994              : 
     995              : // snapshotIterOpts denotes snapshot-related iterator options when calling
     996              : // newIter. These are the possible cases for a snapshotIterOpts:
     997              : //   - No snapshot: All fields are zero values.
     998              : //   - Classic snapshot: Only `seqNum` is set. The latest readState will be used
     999              : //     and the specified seqNum will be used as the snapshot seqNum.
    1000              : //   - EventuallyFileOnlySnapshot (EFOS) behaving as a classic snapshot. Only
    1001              : //     the `seqNum` is set. The latest readState will be used
    1002              : //     and the specified seqNum will be used as the snapshot seqNum.
    1003              : //   - EFOS in file-only state: Only `seqNum` and `vers` are set. All the
    1004              : //     relevant SSTs are referenced by the *version.
    1005              : //   - EFOS that has been excised but is in alwaysCreateIters mode (tests only).
    1006              : //     Only `seqNum` and `readState` are set.
    1007              : type snapshotIterOpts struct {
    1008              :         seqNum    base.SeqNum
    1009              :         vers      *manifest.Version
    1010              :         readState *readState
    1011              : }
    1012              : 
    1013              : type batchIterOpts struct {
    1014              :         batchOnly bool
    1015              : }
    1016              : type newIterOpts struct {
    1017              :         snapshot snapshotIterOpts
    1018              :         batch    batchIterOpts
    1019              : }
    1020              : 
    1021              : // newIter constructs a new iterator, merging in batch iterators as an extra
    1022              : // level.
    1023              : func (d *DB) newIter(
    1024              :         ctx context.Context, batch *Batch, newIterOpts newIterOpts, o *IterOptions,
    1025            1 : ) *Iterator {
    1026            1 :         if newIterOpts.batch.batchOnly {
    1027            1 :                 if batch == nil {
    1028            0 :                         panic("batchOnly is true, but batch is nil")
    1029              :                 }
    1030            1 :                 if newIterOpts.snapshot.vers != nil {
    1031            0 :                         panic("batchOnly is true, but snapshotIterOpts is initialized")
    1032              :                 }
    1033              :         }
    1034            1 :         if err := d.closed.Load(); err != nil {
    1035            1 :                 panic(err)
    1036              :         }
    1037            1 :         seqNum := newIterOpts.snapshot.seqNum
    1038            1 :         if o != nil && o.RangeKeyMasking.Suffix != nil && o.KeyTypes != IterKeyTypePointsAndRanges {
    1039            0 :                 panic("pebble: range key masking requires IterKeyTypePointsAndRanges")
    1040              :         }
    1041            1 :         if (batch != nil || seqNum != 0) && (o != nil && o.OnlyReadGuaranteedDurable) {
    1042            1 :                 // We could add support for OnlyReadGuaranteedDurable on snapshots if
    1043            1 :                 // there was a need: this would require checking that the sequence number
    1044            1 :                 // of the snapshot has been flushed, by comparing with
    1045            1 :                 // DB.mem.queue[0].logSeqNum.
    1046            1 :                 panic("OnlyReadGuaranteedDurable is not supported for batches or snapshots")
    1047              :         }
    1048            1 :         var readState *readState
    1049            1 :         var newIters tableNewIters
    1050            1 :         var newIterRangeKey keyspanimpl.TableNewSpanIter
    1051            1 :         if !newIterOpts.batch.batchOnly {
    1052            1 :                 // Grab and reference the current readState. This prevents the underlying
    1053            1 :                 // files in the associated version from being deleted if there is a current
    1054            1 :                 // compaction. The readState is unref'd by Iterator.Close().
    1055            1 :                 if newIterOpts.snapshot.vers == nil {
    1056            1 :                         if newIterOpts.snapshot.readState != nil {
    1057            0 :                                 readState = newIterOpts.snapshot.readState
    1058            0 :                                 readState.ref()
    1059            1 :                         } else {
    1060            1 :                                 // NB: loadReadState() calls readState.ref().
    1061            1 :                                 readState = d.loadReadState()
    1062            1 :                         }
    1063            1 :                 } else {
    1064            1 :                         // vers != nil
    1065            1 :                         newIterOpts.snapshot.vers.Ref()
    1066            1 :                 }
    1067              : 
    1068              :                 // Determine the seqnum to read at after grabbing the read state (current and
    1069              :                 // memtables) above.
    1070            1 :                 if seqNum == 0 {
    1071            1 :                         seqNum = d.mu.versions.visibleSeqNum.Load()
    1072            1 :                 }
    1073            1 :                 newIters = d.newIters
    1074            1 :                 newIterRangeKey = d.tableNewRangeKeyIter
    1075              :         }
    1076              : 
    1077              :         // Bundle various structures under a single umbrella in order to allocate
    1078              :         // them together.
    1079            1 :         buf := newIterAlloc()
    1080            1 :         dbi := &buf.dbi
    1081            1 :         dbi.ctx = ctx
    1082            1 :         dbi.alloc = buf
    1083            1 :         dbi.merge = d.merge
    1084            1 :         dbi.comparer = d.opts.Comparer
    1085            1 :         dbi.readState = readState
    1086            1 :         dbi.version = newIterOpts.snapshot.vers
    1087            1 :         dbi.keyBuf = buf.keyBuf
    1088            1 :         dbi.prefixOrFullSeekKey = buf.prefixOrFullSeekKey
    1089            1 :         dbi.boundsBuf = buf.boundsBuf
    1090            1 :         dbi.fc = d.fileCache
    1091            1 :         dbi.newIters = newIters
    1092            1 :         dbi.newIterRangeKey = newIterRangeKey
    1093            1 :         dbi.seqNum = seqNum
    1094            1 :         dbi.batchOnlyIter = newIterOpts.batch.batchOnly
    1095            1 :         if o != nil {
    1096            1 :                 dbi.opts = *o
    1097            1 :                 dbi.processBounds(o.LowerBound, o.UpperBound)
    1098            1 :         }
    1099            1 :         dbi.opts.logger = d.opts.Logger
    1100            1 :         if d.opts.private.disableLazyCombinedIteration {
    1101            0 :                 dbi.opts.disableLazyCombinedIteration = true
    1102            0 :         }
    1103            1 :         if batch != nil {
    1104            1 :                 dbi.batch = &buf.batchState
    1105            1 :                 dbi.batch.batch = batch
    1106            1 :                 dbi.batch.batchSeqNum = batch.nextSeqNum()
    1107            1 :         }
    1108            1 :         return finishInitializingIter(ctx, buf)
    1109              : }
    1110              : 
    1111              : // finishInitializingIter is a helper for doing the non-trivial initialization
    1112              : // of an Iterator. It's invoked to perform the initial initialization of an
    1113              : // Iterator during NewIter or Clone, and to perform reinitialization due to a
    1114              : // change in IterOptions by a call to Iterator.SetOptions.
    1115            1 : func finishInitializingIter(ctx context.Context, buf *iterAlloc) *Iterator {
    1116            1 :         // Short-hand.
    1117            1 :         dbi := &buf.dbi
    1118            1 :         var memtables flushableList
    1119            1 :         if dbi.readState != nil {
    1120            1 :                 memtables = dbi.readState.memtables
    1121            1 :         }
    1122            1 :         if dbi.opts.OnlyReadGuaranteedDurable {
    1123            1 :                 memtables = nil
    1124            1 :         } else {
    1125            1 :                 // We only need to read from memtables which contain sequence numbers older
    1126            1 :                 // than seqNum. Trim off newer memtables.
    1127            1 :                 for i := len(memtables) - 1; i >= 0; i-- {
    1128            1 :                         if logSeqNum := memtables[i].logSeqNum; logSeqNum < dbi.seqNum {
    1129            1 :                                 break
    1130              :                         }
    1131            1 :                         memtables = memtables[:i]
    1132              :                 }
    1133              :         }
    1134              : 
    1135            1 :         if dbi.opts.pointKeys() {
    1136            1 :                 // Construct the point iterator, initializing dbi.pointIter to point to
    1137            1 :                 // dbi.merging. If this is called during a SetOptions call and this
    1138            1 :                 // Iterator has already initialized dbi.merging, constructPointIter is a
    1139            1 :                 // noop and an initialized pointIter already exists in dbi.pointIter.
    1140            1 :                 dbi.constructPointIter(ctx, memtables, buf)
    1141            1 :                 dbi.iter = dbi.pointIter
    1142            1 :         } else {
    1143            1 :                 dbi.iter = emptyIter
    1144            1 :         }
    1145              : 
    1146            1 :         if dbi.opts.rangeKeys() {
    1147            1 :                 dbi.rangeKeyMasking.init(dbi, dbi.comparer)
    1148            1 : 
    1149            1 :                 // When iterating over both point and range keys, don't create the
    1150            1 :                 // range-key iterator stack immediately if we can avoid it. This
    1151            1 :                 // optimization takes advantage of the expected sparseness of range
    1152            1 :                 // keys, and configures the point-key iterator to dynamically switch to
    1153            1 :                 // combined iteration when it observes a file containing range keys.
    1154            1 :                 //
    1155            1 :                 // Lazy combined iteration is not possible if a batch or a memtable
    1156            1 :                 // contains any range keys.
    1157            1 :                 useLazyCombinedIteration := dbi.rangeKey == nil &&
    1158            1 :                         dbi.opts.KeyTypes == IterKeyTypePointsAndRanges &&
    1159            1 :                         (dbi.batch == nil || dbi.batch.batch.countRangeKeys == 0) &&
    1160            1 :                         !dbi.opts.disableLazyCombinedIteration
    1161            1 :                 if useLazyCombinedIteration {
    1162            1 :                         // The user requested combined iteration, and there's no indexed
    1163            1 :                         // batch currently containing range keys that would prevent lazy
    1164            1 :                         // combined iteration. Check the memtables to see if they contain
    1165            1 :                         // any range keys.
    1166            1 :                         for i := range memtables {
    1167            1 :                                 if memtables[i].containsRangeKeys() {
    1168            1 :                                         useLazyCombinedIteration = false
    1169            1 :                                         break
    1170              :                                 }
    1171              :                         }
    1172              :                 }
    1173              : 
    1174            1 :                 if useLazyCombinedIteration {
    1175            1 :                         dbi.lazyCombinedIter = lazyCombinedIter{
    1176            1 :                                 parent:    dbi,
    1177            1 :                                 pointIter: dbi.pointIter,
    1178            1 :                                 combinedIterState: combinedIterState{
    1179            1 :                                         initialized: false,
    1180            1 :                                 },
    1181            1 :                         }
    1182            1 :                         dbi.iter = &dbi.lazyCombinedIter
    1183            1 :                         dbi.iter = invalidating.MaybeWrapIfInvariants(dbi.iter)
    1184            1 :                 } else {
    1185            1 :                         dbi.lazyCombinedIter.combinedIterState = combinedIterState{
    1186            1 :                                 initialized: true,
    1187            1 :                         }
    1188            1 :                         if dbi.rangeKey == nil {
    1189            1 :                                 dbi.rangeKey = iterRangeKeyStateAllocPool.Get().(*iteratorRangeKeyState)
    1190            1 :                                 dbi.constructRangeKeyIter()
    1191            1 :                         } else {
    1192            1 :                                 dbi.rangeKey.iterConfig.SetBounds(dbi.opts.LowerBound, dbi.opts.UpperBound)
    1193            1 :                         }
    1194              : 
    1195              :                         // Wrap the point iterator (currently dbi.iter) with an interleaving
    1196              :                         // iterator that interleaves range keys pulled from
    1197              :                         // dbi.rangeKey.rangeKeyIter.
    1198              :                         //
    1199              :                         // NB: The interleaving iterator is always reinitialized, even if
    1200              :                         // dbi already had an initialized range key iterator, in case the point
    1201              :                         // iterator changed or the range key masking suffix changed.
    1202            1 :                         dbi.rangeKey.iiter.Init(dbi.comparer, dbi.iter, dbi.rangeKey.rangeKeyIter,
    1203            1 :                                 keyspan.InterleavingIterOpts{
    1204            1 :                                         Mask:       &dbi.rangeKeyMasking,
    1205            1 :                                         LowerBound: dbi.opts.LowerBound,
    1206            1 :                                         UpperBound: dbi.opts.UpperBound,
    1207            1 :                                 })
    1208            1 :                         dbi.iter = &dbi.rangeKey.iiter
    1209              :                 }
    1210            1 :         } else {
    1211            1 :                 // !dbi.opts.rangeKeys()
    1212            1 :                 //
    1213            1 :                 // Reset the combined iterator state. The initialized=true ensures the
    1214            1 :                 // iterator doesn't unnecessarily try to switch to combined iteration.
    1215            1 :                 dbi.lazyCombinedIter.combinedIterState = combinedIterState{initialized: true}
    1216            1 :         }
    1217            1 :         return dbi
    1218              : }
    1219              : 
    1220              : func (i *Iterator) constructPointIter(
    1221              :         ctx context.Context, memtables flushableList, buf *iterAlloc,
    1222            1 : ) {
    1223            1 :         if i.pointIter != nil {
    1224            1 :                 // Already have one.
    1225            1 :                 return
    1226            1 :         }
    1227            1 :         readEnv := block.ReadEnv{
    1228            1 :                 Stats: &i.stats.InternalStats,
    1229            1 :                 // If the file cache has a sstable stats collector, ask it for an
    1230            1 :                 // accumulator for this iterator's configured category and QoS. All SSTable
    1231            1 :                 // iterators created by this Iterator will accumulate their stats to it as
    1232            1 :                 // they Close during iteration.
    1233            1 :                 IterStats: i.fc.SSTStatsCollector().Accumulator(
    1234            1 :                         uint64(uintptr(unsafe.Pointer(i))),
    1235            1 :                         i.opts.Category,
    1236            1 :                 ),
    1237            1 :         }
    1238            1 :         if i.readState != nil {
    1239            1 :                 i.blobValueFetcher.Init(&i.readState.current.BlobFiles, i.fc, readEnv,
    1240            1 :                         blob.SuggestedCachedReaders(i.readState.current.MaxReadAmp()))
    1241            1 :         } else if i.version != nil {
    1242            1 :                 i.blobValueFetcher.Init(&i.version.BlobFiles, i.fc, readEnv,
    1243            1 :                         blob.SuggestedCachedReaders(i.version.MaxReadAmp()))
    1244            1 :         }
    1245            1 :         internalOpts := internalIterOpts{
    1246            1 :                 readEnv:          sstable.ReadEnv{Block: readEnv},
    1247            1 :                 blobValueFetcher: &i.blobValueFetcher,
    1248            1 :         }
    1249            1 :         if i.opts.RangeKeyMasking.Filter != nil {
    1250            1 :                 internalOpts.boundLimitedFilter = &i.rangeKeyMasking
    1251            1 :         }
    1252              : 
    1253              :         // Merging levels and levels from iterAlloc.
    1254            1 :         mlevels := buf.mlevels[:0]
    1255            1 :         levels := buf.levels[:0]
    1256            1 : 
    1257            1 :         // We compute the number of levels needed ahead of time and reallocate a slice if
    1258            1 :         // the array from the iterAlloc isn't large enough. Doing this allocation once
    1259            1 :         // should improve the performance.
    1260            1 :         numMergingLevels := 0
    1261            1 :         numLevelIters := 0
    1262            1 :         if i.batch != nil {
    1263            1 :                 numMergingLevels++
    1264            1 :         }
    1265              : 
    1266            1 :         var current *manifest.Version
    1267            1 :         if !i.batchOnlyIter {
    1268            1 :                 numMergingLevels += len(memtables)
    1269            1 :                 current = i.version
    1270            1 :                 if current == nil {
    1271            1 :                         current = i.readState.current
    1272            1 :                 }
    1273            1 :                 maxReadAmp := current.MaxReadAmp()
    1274            1 :                 numMergingLevels += maxReadAmp
    1275            1 :                 numLevelIters += maxReadAmp
    1276              :         }
    1277              : 
    1278            1 :         if numMergingLevels > cap(mlevels) {
    1279            1 :                 mlevels = make([]mergingIterLevel, 0, numMergingLevels)
    1280            1 :         }
    1281            1 :         if numLevelIters > cap(levels) {
    1282            1 :                 levels = make([]levelIter, 0, numLevelIters)
    1283            1 :         }
    1284              : 
    1285              :         // Top-level is the batch, if any.
    1286            1 :         if i.batch != nil {
    1287            1 :                 if i.batch.batch.index == nil {
    1288            0 :                         // This isn't an indexed batch. We shouldn't have gotten this far.
    1289            0 :                         panic(errors.AssertionFailedf("creating an iterator over an unindexed batch"))
    1290            1 :                 } else {
    1291            1 :                         i.batch.batch.initInternalIter(&i.opts, &i.batch.pointIter)
    1292            1 :                         i.batch.batch.initRangeDelIter(&i.opts, &i.batch.rangeDelIter, i.batch.batchSeqNum)
    1293            1 :                         // Only include the batch's rangedel iterator if it's non-empty.
    1294            1 :                         // This requires some subtle logic in the case a rangedel is later
    1295            1 :                         // written to the batch and the view of the batch is refreshed
    1296            1 :                         // during a call to SetOptions—in this case, we need to reconstruct
    1297            1 :                         // the point iterator to add the batch rangedel iterator.
    1298            1 :                         var rangeDelIter keyspan.FragmentIterator
    1299            1 :                         if i.batch.rangeDelIter.Count() > 0 {
    1300            1 :                                 rangeDelIter = &i.batch.rangeDelIter
    1301            1 :                         }
    1302            1 :                         mlevels = append(mlevels, mergingIterLevel{
    1303            1 :                                 iter:         &i.batch.pointIter,
    1304            1 :                                 rangeDelIter: rangeDelIter,
    1305            1 :                         })
    1306              :                 }
    1307              :         }
    1308              : 
    1309            1 :         if !i.batchOnlyIter {
    1310            1 :                 // Next are the memtables.
    1311            1 :                 for j := len(memtables) - 1; j >= 0; j-- {
    1312            1 :                         mem := memtables[j]
    1313            1 :                         mlevels = append(mlevels, mergingIterLevel{
    1314            1 :                                 iter:         mem.newIter(&i.opts),
    1315            1 :                                 rangeDelIter: mem.newRangeDelIter(&i.opts),
    1316            1 :                         })
    1317            1 :                 }
    1318              : 
    1319              :                 // Next are the file levels: L0 sub-levels followed by lower levels.
    1320            1 :                 mlevelsIndex := len(mlevels)
    1321            1 :                 levelsIndex := len(levels)
    1322            1 :                 mlevels = mlevels[:numMergingLevels]
    1323            1 :                 levels = levels[:numLevelIters]
    1324            1 :                 i.opts.snapshotForHideObsoletePoints = buf.dbi.seqNum
    1325            1 :                 addLevelIterForFiles := func(files manifest.LevelIterator, level manifest.Layer) {
    1326            1 :                         li := &levels[levelsIndex]
    1327            1 : 
    1328            1 :                         li.init(ctx, i.opts, i.comparer, i.newIters, files, level, internalOpts)
    1329            1 :                         li.initRangeDel(&mlevels[mlevelsIndex])
    1330            1 :                         li.initCombinedIterState(&i.lazyCombinedIter.combinedIterState)
    1331            1 :                         mlevels[mlevelsIndex].levelIter = li
    1332            1 :                         mlevels[mlevelsIndex].iter = invalidating.MaybeWrapIfInvariants(li)
    1333            1 : 
    1334            1 :                         levelsIndex++
    1335            1 :                         mlevelsIndex++
    1336            1 :                 }
    1337              : 
    1338              :                 // Add level iterators for the L0 sublevels, iterating from newest to
    1339              :                 // oldest.
    1340            1 :                 for i := len(current.L0SublevelFiles) - 1; i >= 0; i-- {
    1341            1 :                         addLevelIterForFiles(current.L0SublevelFiles[i].Iter(), manifest.L0Sublevel(i))
    1342            1 :                 }
    1343              : 
    1344              :                 // Add level iterators for the non-empty non-L0 levels.
    1345            1 :                 for level := 1; level < len(current.Levels); level++ {
    1346            1 :                         if current.Levels[level].Empty() {
    1347            1 :                                 continue
    1348              :                         }
    1349            1 :                         addLevelIterForFiles(current.Levels[level].Iter(), manifest.Level(level))
    1350              :                 }
    1351              :         }
    1352            1 :         buf.merging.init(&i.opts, &i.stats.InternalStats, i.comparer.Compare, i.comparer.Split, mlevels...)
    1353            1 :         if len(mlevels) <= cap(buf.levelsPositioned) {
    1354            1 :                 buf.merging.levelsPositioned = buf.levelsPositioned[:len(mlevels)]
    1355            1 :         }
    1356            1 :         buf.merging.snapshot = i.seqNum
    1357            1 :         if i.batch != nil {
    1358            1 :                 buf.merging.batchSnapshot = i.batch.batchSeqNum
    1359            1 :         }
    1360            1 :         buf.merging.combinedIterState = &i.lazyCombinedIter.combinedIterState
    1361            1 :         i.pointIter = invalidating.MaybeWrapIfInvariants(&buf.merging).(topLevelIterator)
    1362            1 :         i.merging = &buf.merging
    1363              : }
    1364              : 
    1365              : // NewBatch returns a new empty write-only batch. Any reads on the batch will
    1366              : // return an error. If the batch is committed it will be applied to the DB.
    1367            1 : func (d *DB) NewBatch(opts ...BatchOption) *Batch {
    1368            1 :         return newBatch(d, opts...)
    1369            1 : }
    1370              : 
    1371              : // NewBatchWithSize is mostly identical to NewBatch, but it will allocate the
    1372              : // the specified memory space for the internal slice in advance.
    1373            0 : func (d *DB) NewBatchWithSize(size int, opts ...BatchOption) *Batch {
    1374            0 :         return newBatchWithSize(d, size, opts...)
    1375            0 : }
    1376              : 
    1377              : // NewIndexedBatch returns a new empty read-write batch. Any reads on the batch
    1378              : // will read from both the batch and the DB. If the batch is committed it will
    1379              : // be applied to the DB. An indexed batch is slower that a non-indexed batch
    1380              : // for insert operations. If you do not need to perform reads on the batch, use
    1381              : // NewBatch instead.
    1382            1 : func (d *DB) NewIndexedBatch() *Batch {
    1383            1 :         return newIndexedBatch(d, d.opts.Comparer)
    1384            1 : }
    1385              : 
    1386              : // NewIndexedBatchWithSize is mostly identical to NewIndexedBatch, but it will
    1387              : // allocate the specified memory space for the internal slice in advance.
    1388            0 : func (d *DB) NewIndexedBatchWithSize(size int) *Batch {
    1389            0 :         return newIndexedBatchWithSize(d, d.opts.Comparer, size)
    1390            0 : }
    1391              : 
    1392              : // NewIter returns an iterator that is unpositioned (Iterator.Valid() will
    1393              : // return false). The iterator can be positioned via a call to SeekGE, SeekLT,
    1394              : // First or Last. The iterator provides a point-in-time view of the current DB
    1395              : // state. This view is maintained by preventing file deletions and preventing
    1396              : // memtables referenced by the iterator from being deleted. Using an iterator
    1397              : // to maintain a long-lived point-in-time view of the DB state can lead to an
    1398              : // apparent memory and disk usage leak. Use snapshots (see NewSnapshot) for
    1399              : // point-in-time snapshots which avoids these problems.
    1400            1 : func (d *DB) NewIter(o *IterOptions) (*Iterator, error) {
    1401            1 :         return d.NewIterWithContext(context.Background(), o)
    1402            1 : }
    1403              : 
    1404              : // NewIterWithContext is like NewIter, and additionally accepts a context for
    1405              : // tracing.
    1406            1 : func (d *DB) NewIterWithContext(ctx context.Context, o *IterOptions) (*Iterator, error) {
    1407            1 :         return d.newIter(ctx, nil /* batch */, newIterOpts{}, o), nil
    1408            1 : }
    1409              : 
    1410              : // NewSnapshot returns a point-in-time view of the current DB state. Iterators
    1411              : // created with this handle will all observe a stable snapshot of the current
    1412              : // DB state. The caller must call Snapshot.Close() when the snapshot is no
    1413              : // longer needed. Snapshots are not persisted across DB restarts (close ->
    1414              : // open). Unlike the implicit snapshot maintained by an iterator, a snapshot
    1415              : // will not prevent memtables from being released or sstables from being
    1416              : // deleted. Instead, a snapshot prevents deletion of sequence numbers
    1417              : // referenced by the snapshot.
    1418              : //
    1419              : // There exists one violation of a Snapshot's point-in-time guarantee: An excise
    1420              : // (see DB.Excise and DB.IngestAndExcise) that occurs after the snapshot's
    1421              : // creation will be observed by iterators created from the snapshot after the
    1422              : // excise. See NewEventuallyFileOnlySnapshot for a variant of NewSnapshot that
    1423              : // provides a full point-in-time guarantee.
    1424            1 : func (d *DB) NewSnapshot() *Snapshot {
    1425            1 :         // TODO(jackson): Consider removal of regular, non-eventually-file-only
    1426            1 :         // snapshots given they no longer provide a true point-in-time snapshot of
    1427            1 :         // the database due to excises. If we had a mechanism to construct a maximal
    1428            1 :         // key range, we could implement NewSnapshot in terms of
    1429            1 :         // NewEventuallyFileOnlySnapshot and provide a true point-in-time guarantee.
    1430            1 :         if err := d.closed.Load(); err != nil {
    1431            1 :                 panic(err)
    1432              :         }
    1433            1 :         d.mu.Lock()
    1434            1 :         s := &Snapshot{
    1435            1 :                 db:     d,
    1436            1 :                 seqNum: d.mu.versions.visibleSeqNum.Load(),
    1437            1 :         }
    1438            1 :         d.mu.snapshots.pushBack(s)
    1439            1 :         d.mu.Unlock()
    1440            1 :         return s
    1441              : }
    1442              : 
    1443              : // NewEventuallyFileOnlySnapshot returns a point-in-time view of the current DB
    1444              : // state, similar to NewSnapshot, but with consistency constrained to the
    1445              : // provided set of key ranges. See the comment at EventuallyFileOnlySnapshot for
    1446              : // its semantics.
    1447            1 : func (d *DB) NewEventuallyFileOnlySnapshot(keyRanges []KeyRange) *EventuallyFileOnlySnapshot {
    1448            1 :         if err := d.closed.Load(); err != nil {
    1449            0 :                 panic(err)
    1450              :         }
    1451            1 :         for i := range keyRanges {
    1452            1 :                 if i > 0 && d.cmp(keyRanges[i-1].End, keyRanges[i].Start) > 0 {
    1453            0 :                         panic("pebble: key ranges for eventually-file-only-snapshot not in order")
    1454              :                 }
    1455              :         }
    1456            1 :         return d.makeEventuallyFileOnlySnapshot(keyRanges)
    1457              : }
    1458              : 
    1459              : // Close closes the DB.
    1460              : //
    1461              : // It is not safe to close a DB until all outstanding iterators are closed
    1462              : // or to call Close concurrently with any other DB method. It is not valid
    1463              : // to call any of a DB's methods after the DB has been closed.
    1464            1 : func (d *DB) Close() error {
    1465            1 :         if err := d.closed.Load(); err != nil {
    1466            1 :                 panic(err)
    1467              :         }
    1468            1 :         d.compactionSchedulers.Wait()
    1469            1 :         // Compactions can be asynchronously started by the CompactionScheduler
    1470            1 :         // calling d.Schedule. When this Unregister returns, we know that the
    1471            1 :         // CompactionScheduler will never again call a method on the DB. Note that
    1472            1 :         // this must be called without holding d.mu.
    1473            1 :         d.compactionScheduler.Unregister()
    1474            1 :         // Lock the commit pipeline for the duration of Close. This prevents a race
    1475            1 :         // with makeRoomForWrite. Rotating the WAL in makeRoomForWrite requires
    1476            1 :         // dropping d.mu several times for I/O. If Close only holds d.mu, an
    1477            1 :         // in-progress WAL rotation may re-acquire d.mu only once the database is
    1478            1 :         // closed.
    1479            1 :         //
    1480            1 :         // Additionally, locking the commit pipeline makes it more likely that
    1481            1 :         // (illegal) concurrent writes will observe d.closed.Load() != nil, creating
    1482            1 :         // more understable panics if the database is improperly used concurrently
    1483            1 :         // during Close.
    1484            1 :         d.commit.mu.Lock()
    1485            1 :         defer d.commit.mu.Unlock()
    1486            1 :         d.mu.Lock()
    1487            1 :         defer d.mu.Unlock()
    1488            1 :         // Check that the DB is not closed again. If there are two concurrent calls
    1489            1 :         // to DB.Close, the best-effort check at the top of DB.Close may not fire.
    1490            1 :         // But since this second check happens after mutex acquisition, the two
    1491            1 :         // concurrent calls will get serialized and the second one will see the
    1492            1 :         // effect of the d.closed.Store below.
    1493            1 :         if err := d.closed.Load(); err != nil {
    1494            0 :                 panic(err)
    1495              :         }
    1496              :         // Clear the finalizer that is used to check that an unreferenced DB has been
    1497              :         // closed. We're closing the DB here, so the check performed by that
    1498              :         // finalizer isn't necessary.
    1499              :         //
    1500              :         // Note: this is a no-op if invariants are disabled or race is enabled.
    1501            1 :         invariants.SetFinalizer(d.closed, nil)
    1502            1 : 
    1503            1 :         d.closed.Store(errors.WithStack(ErrClosed))
    1504            1 :         close(d.closedCh)
    1505            1 : 
    1506            1 :         defer d.cacheHandle.Close()
    1507            1 : 
    1508            1 :         for d.mu.compact.compactingCount > 0 || d.mu.compact.downloadingCount > 0 || d.mu.compact.flushing {
    1509            1 :                 d.mu.compact.cond.Wait()
    1510            1 :         }
    1511            1 :         for d.mu.tableStats.loading {
    1512            1 :                 d.mu.tableStats.cond.Wait()
    1513            1 :         }
    1514            1 :         for d.mu.tableValidation.validating {
    1515            0 :                 d.mu.tableValidation.cond.Wait()
    1516            0 :         }
    1517              : 
    1518            1 :         var err error
    1519            1 :         if n := len(d.mu.compact.inProgress); n > 0 {
    1520            1 :                 err = errors.Errorf("pebble: %d unexpected in-progress compactions", errors.Safe(n))
    1521            1 :         }
    1522            1 :         err = firstError(err, d.mu.formatVers.marker.Close())
    1523            1 :         if !d.opts.ReadOnly {
    1524            1 :                 if d.mu.log.writer != nil {
    1525            1 :                         _, err2 := d.mu.log.writer.Close()
    1526            1 :                         err = firstError(err, err2)
    1527            1 :                 }
    1528            1 :         } else if d.mu.log.writer != nil {
    1529            0 :                 panic("pebble: log-writer should be nil in read-only mode")
    1530              :         }
    1531            1 :         err = firstError(err, d.mu.log.manager.Close())
    1532            1 :         err = firstError(err, d.dataDirLock.Close())
    1533            1 : 
    1534            1 :         // Note that versionSet.close() only closes the MANIFEST. The versions list
    1535            1 :         // is still valid for the checks below.
    1536            1 :         err = firstError(err, d.mu.versions.close())
    1537            1 : 
    1538            1 :         err = firstError(err, d.dataDir.Close())
    1539            1 : 
    1540            1 :         d.readState.val.unrefLocked()
    1541            1 : 
    1542            1 :         current := d.mu.versions.currentVersion()
    1543            1 :         for v := d.mu.versions.versions.Front(); true; v = v.Next() {
    1544            1 :                 refs := v.Refs()
    1545            1 :                 if v == current {
    1546            1 :                         if refs != 1 {
    1547            1 :                                 err = firstError(err, errors.Errorf("leaked iterators: current\n%s", v))
    1548            1 :                         }
    1549            1 :                         break
    1550              :                 }
    1551            0 :                 if refs != 0 {
    1552            0 :                         err = firstError(err, errors.Errorf("leaked iterators:\n%s", v))
    1553            0 :                 }
    1554              :         }
    1555              : 
    1556            1 :         for _, mem := range d.mu.mem.queue {
    1557            1 :                 // Usually, we'd want to delete the files returned by readerUnref. But
    1558            1 :                 // in this case, even if we're unreferencing the flushables, the
    1559            1 :                 // flushables aren't obsolete. They will be reconstructed during WAL
    1560            1 :                 // replay.
    1561            1 :                 mem.readerUnrefLocked(false)
    1562            1 :         }
    1563              :         // If there's an unused, recycled memtable, we need to release its memory.
    1564            1 :         if obsoleteMemTable := d.memTableRecycle.Swap(nil); obsoleteMemTable != nil {
    1565            1 :                 d.freeMemTable(obsoleteMemTable)
    1566            1 :         }
    1567            1 :         if reserved := d.memTableReserved.Load(); reserved != 0 {
    1568            1 :                 err = firstError(err, errors.Errorf("leaked memtable reservation: %d", errors.Safe(reserved)))
    1569            1 :         }
    1570              : 
    1571              :         // Since we called d.readState.val.unrefLocked() above, we are expected to
    1572              :         // manually schedule deletion of obsolete files.
    1573            1 :         if len(d.mu.versions.obsoleteTables) > 0 || len(d.mu.versions.obsoleteBlobs) > 0 {
    1574            1 :                 d.deleteObsoleteFiles(d.newJobIDLocked())
    1575            1 :         }
    1576              : 
    1577            1 :         d.mu.Unlock()
    1578            1 : 
    1579            1 :         // Wait for all cleaning jobs to finish.
    1580            1 :         d.cleanupManager.Close()
    1581            1 : 
    1582            1 :         d.mu.Lock()
    1583            1 :         // Sanity check compaction metrics.
    1584            1 :         if invariants.Enabled {
    1585            1 :                 if d.mu.compact.compactingCount > 0 || d.mu.compact.downloadingCount > 0 || d.mu.versions.atomicInProgressBytes.Load() > 0 {
    1586            0 :                         panic("compacting counts not 0 on close")
    1587              :                 }
    1588              :         }
    1589              : 
    1590              :         // As a sanity check, ensure that there are no zombie tables or blob files.
    1591              :         // A non-zero count hints at a reference count leak.
    1592            1 :         if ztbls := d.mu.versions.zombieTables.Count(); ztbls > 0 {
    1593            0 :                 err = firstError(err, errors.Errorf("non-zero zombie file count: %d", ztbls))
    1594            0 :         }
    1595            1 :         if zblobs := d.mu.versions.zombieBlobs.Count(); zblobs > 0 {
    1596            0 :                 err = firstError(err, errors.Errorf("non-zero zombie blob count: %d", zblobs))
    1597            0 :         }
    1598              : 
    1599            1 :         err = firstError(err, d.fileCache.Close())
    1600            1 : 
    1601            1 :         err = firstError(err, d.objProvider.Close())
    1602            1 : 
    1603            1 :         // If the options include a closer to 'close' the filesystem, close it.
    1604            1 :         if d.opts.private.fsCloser != nil {
    1605            1 :                 d.opts.private.fsCloser.Close()
    1606            1 :         }
    1607              : 
    1608              :         // Return an error if the user failed to close all open snapshots.
    1609            1 :         if v := d.mu.snapshots.count(); v > 0 {
    1610            0 :                 err = firstError(err, errors.Errorf("leaked snapshots: %d open snapshots on DB %p", v, d))
    1611            0 :         }
    1612              : 
    1613            1 :         return err
    1614              : }
    1615              : 
    1616              : // Compact the specified range of keys in the database.
    1617            1 : func (d *DB) Compact(ctx context.Context, start, end []byte, parallelize bool) error {
    1618            1 :         if err := d.closed.Load(); err != nil {
    1619            1 :                 panic(err)
    1620              :         }
    1621            1 :         if d.opts.ReadOnly {
    1622            1 :                 return ErrReadOnly
    1623            1 :         }
    1624            1 :         if d.cmp(start, end) >= 0 {
    1625            1 :                 return errors.Errorf("Compact start %s is not less than end %s",
    1626            1 :                         d.opts.Comparer.FormatKey(start), d.opts.Comparer.FormatKey(end))
    1627            1 :         }
    1628              : 
    1629            1 :         d.mu.Lock()
    1630            1 :         maxLevelWithFiles := 1
    1631            1 :         cur := d.mu.versions.currentVersion()
    1632            1 :         for level := 0; level < numLevels; level++ {
    1633            1 :                 overlaps := cur.Overlaps(level, base.UserKeyBoundsInclusive(start, end))
    1634            1 :                 if !overlaps.Empty() {
    1635            1 :                         maxLevelWithFiles = level + 1
    1636            1 :                 }
    1637              :         }
    1638              : 
    1639              :         // Determine if any memtable overlaps with the compaction range. We wait for
    1640              :         // any such overlap to flush (initiating a flush if necessary).
    1641            1 :         mem, err := func() (*flushableEntry, error) {
    1642            1 :                 // Check to see if any files overlap with any of the memtables. The queue
    1643            1 :                 // is ordered from oldest to newest with the mutable memtable being the
    1644            1 :                 // last element in the slice. We want to wait for the newest table that
    1645            1 :                 // overlaps.
    1646            1 :                 for i := len(d.mu.mem.queue) - 1; i >= 0; i-- {
    1647            1 :                         mem := d.mu.mem.queue[i]
    1648            1 :                         var anyOverlaps bool
    1649            1 :                         mem.computePossibleOverlaps(func(b bounded) shouldContinue {
    1650            1 :                                 anyOverlaps = true
    1651            1 :                                 return stopIteration
    1652            1 :                         }, KeyRange{Start: start, End: end})
    1653            1 :                         if !anyOverlaps {
    1654            1 :                                 continue
    1655              :                         }
    1656            1 :                         var err error
    1657            1 :                         if mem.flushable == d.mu.mem.mutable {
    1658            1 :                                 // We have to hold both commitPipeline.mu and DB.mu when calling
    1659            1 :                                 // makeRoomForWrite(). Lock order requirements elsewhere force us to
    1660            1 :                                 // unlock DB.mu in order to grab commitPipeline.mu first.
    1661            1 :                                 d.mu.Unlock()
    1662            1 :                                 d.commit.mu.Lock()
    1663            1 :                                 d.mu.Lock()
    1664            1 :                                 defer d.commit.mu.Unlock() //nolint:deferloop
    1665            1 :                                 if mem.flushable == d.mu.mem.mutable {
    1666            1 :                                         // Only flush if the active memtable is unchanged.
    1667            1 :                                         err = d.makeRoomForWrite(nil)
    1668            1 :                                 }
    1669              :                         }
    1670            1 :                         mem.flushForced = true
    1671            1 :                         d.maybeScheduleFlush()
    1672            1 :                         return mem, err
    1673              :                 }
    1674            1 :                 return nil, nil
    1675              :         }()
    1676              : 
    1677            1 :         d.mu.Unlock()
    1678            1 : 
    1679            1 :         if err != nil {
    1680            0 :                 return err
    1681            0 :         }
    1682            1 :         if mem != nil {
    1683            1 :                 select {
    1684            1 :                 case <-mem.flushed:
    1685            0 :                 case <-ctx.Done():
    1686            0 :                         return ctx.Err()
    1687              :                 }
    1688              :         }
    1689              : 
    1690            1 :         for level := 0; level < maxLevelWithFiles; {
    1691            1 :                 for {
    1692            1 :                         if err := d.manualCompact(
    1693            1 :                                 ctx, start, end, level, parallelize); err != nil {
    1694            1 :                                 if errors.Is(err, ErrCancelledCompaction) {
    1695            1 :                                         continue
    1696              :                                 }
    1697            1 :                                 return err
    1698              :                         }
    1699            1 :                         break
    1700              :                 }
    1701            1 :                 level++
    1702            1 :                 if level == numLevels-1 {
    1703            1 :                         // A manual compaction of the bottommost level occurred.
    1704            1 :                         // There is no next level to try and compact.
    1705            1 :                         break
    1706              :                 }
    1707              :         }
    1708            1 :         return nil
    1709              : }
    1710              : 
    1711              : func (d *DB) manualCompact(
    1712              :         ctx context.Context, start, end []byte, level int, parallelize bool,
    1713            1 : ) error {
    1714            1 :         d.mu.Lock()
    1715            1 :         curr := d.mu.versions.currentVersion()
    1716            1 :         files := curr.Overlaps(level, base.UserKeyBoundsInclusive(start, end))
    1717            1 :         if files.Empty() {
    1718            1 :                 d.mu.Unlock()
    1719            1 :                 return nil
    1720            1 :         }
    1721              : 
    1722            1 :         var compactions []*manualCompaction
    1723            1 :         if parallelize {
    1724            1 :                 compactions = append(compactions, d.splitManualCompaction(start, end, level)...)
    1725            1 :         } else {
    1726            1 :                 compactions = append(compactions, &manualCompaction{
    1727            1 :                         level: level,
    1728            1 :                         done:  make(chan error, 1),
    1729            1 :                         start: start,
    1730            1 :                         end:   end,
    1731            1 :                 })
    1732            1 :         }
    1733            1 :         n := len(compactions)
    1734            1 :         if n == 0 {
    1735            0 :                 d.mu.Unlock()
    1736            0 :                 return nil
    1737            0 :         }
    1738            1 :         for i := range compactions {
    1739            1 :                 d.mu.compact.manualID++
    1740            1 :                 compactions[i].id = d.mu.compact.manualID
    1741            1 :         }
    1742              :         // [manualIDStart, manualIDEnd] are the compactions that have been added to
    1743              :         // d.mu.compact.manual.
    1744            1 :         manualIDStart := compactions[0].id
    1745            1 :         manualIDEnd := compactions[n-1].id
    1746            1 :         d.mu.compact.manual = append(d.mu.compact.manual, compactions...)
    1747            1 :         d.mu.compact.manualLen.Store(int32(len(d.mu.compact.manual)))
    1748            1 :         d.maybeScheduleCompaction()
    1749            1 :         d.mu.Unlock()
    1750            1 : 
    1751            1 :         // On context cancellation, we only cancel the compactions that have not yet
    1752            1 :         // started. The assumption is that it is relatively harmless to have the
    1753            1 :         // already started compactions run to completion. We don't wait for the
    1754            1 :         // ongoing compactions to finish, since the assumption is that the caller
    1755            1 :         // has already given up on the operation (and the cancellation error is
    1756            1 :         // going to be returned anyway).
    1757            1 :         //
    1758            1 :         // An alternative would be to store the context in each *manualCompaction,
    1759            1 :         // and have the goroutine that retrieves the *manualCompaction for running
    1760            1 :         // notice the cancellation and write the cancellation error to
    1761            1 :         // manualCompaction.done. That approach would require this method to wait
    1762            1 :         // for all the *manualCompactions it has enqueued to finish before returning
    1763            1 :         // (to not leak a context). Since there is no timeliness guarantee on when a
    1764            1 :         // *manualCompaction will be retrieved for running, the wait until a
    1765            1 :         // cancelled context causes this method to return is not bounded. Hence, we
    1766            1 :         // don't adopt that approach.
    1767            1 :         cancelPendingCompactions := func() {
    1768            1 :                 d.mu.Lock()
    1769            1 :                 for i := 0; i < len(d.mu.compact.manual); {
    1770            1 :                         if d.mu.compact.manual[i].id >= manualIDStart && d.mu.compact.manual[i].id <= manualIDEnd {
    1771            1 :                                 d.mu.compact.manual = slices.Delete(d.mu.compact.manual, i, i+1)
    1772            1 :                                 d.mu.compact.manualLen.Store(int32(len(d.mu.compact.manual)))
    1773            1 :                         } else {
    1774            0 :                                 i++
    1775            0 :                         }
    1776              :                 }
    1777            1 :                 d.mu.Unlock()
    1778              :         }
    1779              :         // Each of the channels is guaranteed to be eventually sent to once. After a
    1780              :         // compaction is possibly picked in d.maybeScheduleCompaction(), either the
    1781              :         // compaction is dropped, executed after being scheduled, or retried later.
    1782              :         // Assuming eventual progress when a compaction is retried, all outcomes send
    1783              :         // a value to the done channel. Since the channels are buffered, it is not
    1784              :         // necessary to read from each channel, and so we can exit early in the event
    1785              :         // of an error.
    1786            1 :         for _, compaction := range compactions {
    1787            1 :                 select {
    1788            1 :                 case <-ctx.Done():
    1789            1 :                         cancelPendingCompactions()
    1790            1 :                         return ctx.Err()
    1791            1 :                 case err := <-compaction.done:
    1792            1 :                         if err != nil {
    1793            1 :                                 cancelPendingCompactions()
    1794            1 :                                 return err
    1795            1 :                         }
    1796              :                 }
    1797              :         }
    1798            1 :         return nil
    1799              : }
    1800              : 
    1801              : // splitManualCompaction splits a manual compaction over [start,end] on level
    1802              : // such that the resulting compactions have no key overlap.
    1803              : func (d *DB) splitManualCompaction(
    1804              :         start, end []byte, level int,
    1805            1 : ) (splitCompactions []*manualCompaction) {
    1806            1 :         curr := d.mu.versions.currentVersion()
    1807            1 :         endLevel := level + 1
    1808            1 :         baseLevel := d.mu.versions.picker.getBaseLevel()
    1809            1 :         if level == 0 {
    1810            1 :                 endLevel = baseLevel
    1811            1 :         }
    1812            1 :         keyRanges := curr.CalculateInuseKeyRanges(d.mu.versions.latest.l0Organizer, level, endLevel, start, end)
    1813            1 :         for _, keyRange := range keyRanges {
    1814            1 :                 splitCompactions = append(splitCompactions, &manualCompaction{
    1815            1 :                         level: level,
    1816            1 :                         done:  make(chan error, 1),
    1817            1 :                         start: keyRange.Start,
    1818            1 :                         end:   keyRange.End.Key,
    1819            1 :                         split: true,
    1820            1 :                 })
    1821            1 :         }
    1822            1 :         return splitCompactions
    1823              : }
    1824              : 
    1825              : // Flush the memtable to stable storage.
    1826            1 : func (d *DB) Flush() error {
    1827            1 :         flushDone, err := d.AsyncFlush()
    1828            1 :         if err != nil {
    1829            1 :                 return err
    1830            1 :         }
    1831            1 :         <-flushDone
    1832            1 :         return nil
    1833              : }
    1834              : 
    1835              : // AsyncFlush asynchronously flushes the memtable to stable storage.
    1836              : //
    1837              : // If no error is returned, the caller can receive from the returned channel in
    1838              : // order to wait for the flush to complete.
    1839            1 : func (d *DB) AsyncFlush() (<-chan struct{}, error) {
    1840            1 :         if err := d.closed.Load(); err != nil {
    1841            1 :                 panic(err)
    1842              :         }
    1843            1 :         if d.opts.ReadOnly {
    1844            1 :                 return nil, ErrReadOnly
    1845            1 :         }
    1846              : 
    1847            1 :         d.commit.mu.Lock()
    1848            1 :         defer d.commit.mu.Unlock()
    1849            1 :         d.mu.Lock()
    1850            1 :         defer d.mu.Unlock()
    1851            1 :         flushed := d.mu.mem.queue[len(d.mu.mem.queue)-1].flushed
    1852            1 :         err := d.makeRoomForWrite(nil)
    1853            1 :         if err != nil {
    1854            0 :                 return nil, err
    1855            0 :         }
    1856            1 :         return flushed, nil
    1857              : }
    1858              : 
    1859              : // Metrics returns metrics about the database.
    1860            1 : func (d *DB) Metrics() *Metrics {
    1861            1 :         metrics := &Metrics{}
    1862            1 :         walStats := d.mu.log.manager.Stats()
    1863            1 :         completedObsoleteFileStats := d.cleanupManager.CompletedStats()
    1864            1 : 
    1865            1 :         d.mu.Lock()
    1866            1 :         vers := d.mu.versions.currentVersion()
    1867            1 :         vers.Ref()
    1868            1 :         defer vers.Unref()
    1869            1 : 
    1870            1 :         *metrics = d.mu.versions.metrics
    1871            1 :         metrics.Compact.EstimatedDebt = d.mu.versions.picker.estimatedCompactionDebt()
    1872            1 :         metrics.Compact.InProgressBytes = d.mu.versions.atomicInProgressBytes.Load()
    1873            1 :         // TODO(radu): split this to separate the download compactions.
    1874            1 :         metrics.Compact.NumInProgress = int64(d.mu.compact.compactingCount + d.mu.compact.downloadingCount)
    1875            1 :         metrics.Compact.MarkedFiles = vers.MarkedForCompaction.Count()
    1876            1 :         metrics.Compact.Duration = d.mu.compact.duration
    1877            1 :         for c := range d.mu.compact.inProgress {
    1878            1 :                 if !c.IsFlush() {
    1879            1 :                         metrics.Compact.Duration += d.timeNow().Sub(c.BeganAt())
    1880            1 :                 }
    1881              :         }
    1882            1 :         metrics.Compact.NumProblemSpans = d.problemSpans.Len()
    1883            1 : 
    1884            1 :         for _, m := range d.mu.mem.queue {
    1885            1 :                 metrics.MemTable.Size += m.totalBytes()
    1886            1 :         }
    1887            1 :         metrics.Snapshots.Count = d.mu.snapshots.count()
    1888            1 :         if metrics.Snapshots.Count > 0 {
    1889            0 :                 metrics.Snapshots.EarliestSeqNum = d.mu.snapshots.earliest()
    1890            0 :         }
    1891            1 :         metrics.Snapshots.PinnedKeys = d.mu.snapshots.cumulativePinnedCount
    1892            1 :         metrics.Snapshots.PinnedSize = d.mu.snapshots.cumulativePinnedSize
    1893            1 :         metrics.MemTable.Count = int64(len(d.mu.mem.queue))
    1894            1 :         metrics.MemTable.ZombieCount = d.memTableCount.Load() - metrics.MemTable.Count
    1895            1 :         metrics.MemTable.ZombieSize = uint64(d.memTableReserved.Load()) - metrics.MemTable.Size
    1896            1 :         metrics.WAL.ObsoleteFiles = int64(walStats.ObsoleteFileCount)
    1897            1 :         metrics.WAL.ObsoletePhysicalSize = walStats.ObsoleteFileSize
    1898            1 :         metrics.WAL.Files = int64(walStats.LiveFileCount)
    1899            1 :         // The current WAL's size (d.logSize) is the logical size, which may be less
    1900            1 :         // than the WAL's physical size if it was recycled. walStats.LiveFileSize
    1901            1 :         // includes the physical size of all live WALs, but for the current WAL it
    1902            1 :         // reflects the physical size when it was opened. So it is possible that
    1903            1 :         // d.atomic.logSize has exceeded that physical size. We allow for this
    1904            1 :         // anomaly.
    1905            1 :         metrics.WAL.PhysicalSize = walStats.LiveFileSize
    1906            1 :         metrics.WAL.BytesIn = d.logBytesIn.Load()
    1907            1 :         metrics.WAL.Size = d.logSize.Load()
    1908            1 :         for i, n := 0, len(d.mu.mem.queue)-1; i < n; i++ {
    1909            1 :                 metrics.WAL.Size += d.mu.mem.queue[i].logSize
    1910            1 :         }
    1911            1 :         metrics.WAL.BytesWritten = metrics.Levels[0].TableBytesIn + metrics.WAL.Size
    1912            1 :         metrics.WAL.Failover = walStats.Failover
    1913            1 : 
    1914            1 :         if p := d.mu.versions.picker; p != nil {
    1915            1 :                 compactions := d.getInProgressCompactionInfoLocked(nil)
    1916            1 :                 m := p.getMetrics(compactions)
    1917            1 :                 for level, lm := range m.levels {
    1918            1 :                         metrics.Levels[level].Score = lm.score
    1919            1 :                         metrics.Levels[level].FillFactor = lm.fillFactor
    1920            1 :                         metrics.Levels[level].CompensatedFillFactor = lm.compensatedFillFactor
    1921            1 :                 }
    1922              :         }
    1923            1 :         metrics.Table.ZombieCount = int64(d.mu.versions.zombieTables.Count())
    1924            1 :         metrics.Table.ZombieSize = d.mu.versions.zombieTables.TotalSize()
    1925            1 :         metrics.Table.Local.ZombieCount, metrics.Table.Local.ZombieSize = d.mu.versions.zombieTables.LocalStats()
    1926            1 : 
    1927            1 :         // The obsolete blob/table metrics have a subtle calculation:
    1928            1 :         //
    1929            1 :         // (A) The vs.metrics.{Table,BlobFiles}.[Local.]{ObsoleteCount,ObsoleteSize}
    1930            1 :         // fields reflect the set of files currently sitting in
    1931            1 :         // vs.obsolete{Tables,Blobs} but not yet enqueued to the cleanup manager.
    1932            1 :         //
    1933            1 :         // (B) The d.mu.fileDeletions.queuedStats field holds the set of files that have
    1934            1 :         // been queued for deletion by the cleanup manager.
    1935            1 :         //
    1936            1 :         // (C) The cleanup manager also maintains cumulative stats for the set of
    1937            1 :         // files that have been deleted.
    1938            1 :         //
    1939            1 :         // The value of currently pending obsolete files is (A) + (B) - (C).
    1940            1 :         pendingObsoleteFileStats := d.mu.fileDeletions.queuedStats
    1941            1 :         pendingObsoleteFileStats.Sub(completedObsoleteFileStats)
    1942            1 :         metrics.Table.Local.ObsoleteCount += pendingObsoleteFileStats.tablesLocal.count
    1943            1 :         metrics.Table.Local.ObsoleteSize += pendingObsoleteFileStats.tablesLocal.size
    1944            1 :         metrics.Table.ObsoleteCount += int64(pendingObsoleteFileStats.tablesAll.count)
    1945            1 :         metrics.Table.ObsoleteSize += pendingObsoleteFileStats.tablesAll.size
    1946            1 :         metrics.BlobFiles.Local.ObsoleteCount += pendingObsoleteFileStats.blobFilesLocal.count
    1947            1 :         metrics.BlobFiles.Local.ObsoleteSize += pendingObsoleteFileStats.blobFilesLocal.size
    1948            1 :         metrics.BlobFiles.ObsoleteCount += pendingObsoleteFileStats.blobFilesAll.count
    1949            1 :         metrics.BlobFiles.ObsoleteSize += pendingObsoleteFileStats.blobFilesAll.size
    1950            1 :         metrics.private.optionsFileSize = d.optionsFileSize
    1951            1 : 
    1952            1 :         d.mu.versions.logLock()
    1953            1 :         metrics.private.manifestFileSize = uint64(d.mu.versions.manifest.Size())
    1954            1 :         backingCount, backingTotalSize := d.mu.versions.latest.virtualBackings.Stats()
    1955            1 :         metrics.Table.BackingTableCount = uint64(backingCount)
    1956            1 :         metrics.Table.BackingTableSize = backingTotalSize
    1957            1 :         blobStats, _ := d.mu.versions.latest.blobFiles.Stats()
    1958            1 :         d.mu.versions.logUnlock()
    1959            1 :         metrics.BlobFiles.LiveCount = blobStats.Count
    1960            1 :         metrics.BlobFiles.LiveSize = blobStats.PhysicalSize
    1961            1 :         metrics.BlobFiles.ValueSize = blobStats.ValueSize
    1962            1 :         metrics.BlobFiles.ReferencedValueSize = blobStats.ReferencedValueSize
    1963            1 :         metrics.BlobFiles.ReferencedBackingValueSize = blobStats.ReferencedBackingValueSize
    1964            1 : 
    1965            1 :         metrics.LogWriter.FsyncLatency = d.mu.log.metrics.fsyncLatency
    1966            1 :         if err := metrics.LogWriter.Merge(&d.mu.log.metrics.LogWriterMetrics); err != nil {
    1967            0 :                 d.opts.Logger.Errorf("metrics error: %s", err)
    1968            0 :         }
    1969            1 :         metrics.Flush.WriteThroughput = d.mu.compact.flushWriteThroughput
    1970            1 :         if d.mu.compact.flushing {
    1971            1 :                 metrics.Flush.NumInProgress = 1
    1972            1 :         }
    1973              : 
    1974            1 :         metrics.Table.PendingStatsCollectionCount = int64(len(d.mu.tableStats.pending))
    1975            1 :         metrics.Table.InitialStatsCollectionComplete = d.mu.tableStats.loadedInitial
    1976            1 : 
    1977            1 :         d.mu.Unlock()
    1978            1 : 
    1979            1 :         // TODO(jackson): Consider making these metrics optional.
    1980            1 :         aggProps := tablePropsAnnotator.MultiLevelAnnotation(vers.Levels[:])
    1981            1 :         metrics.Keys.RangeKeySetsCount = aggProps.NumRangeKeySets
    1982            1 :         metrics.Keys.TombstoneCount = aggProps.NumDeletions
    1983            1 : 
    1984            1 :         delBytes := deletionBytesAnnotator.MultiLevelAnnotation(vers.Levels[:])
    1985            1 :         metrics.Table.Garbage.PointDeletionsBytesEstimate = delBytes.PointDels
    1986            1 :         metrics.Table.Garbage.RangeDeletionsBytesEstimate = delBytes.RangeDels
    1987            1 : 
    1988            1 :         for i := 0; i < numLevels; i++ {
    1989            1 :                 aggProps := tablePropsAnnotator.LevelAnnotation(vers.Levels[i])
    1990            1 :                 metrics.Levels[i].Additional.ValueBlocksSize = aggProps.ValueBlocksSize
    1991            1 :                 metrics.Table.Compression.MergeWith(&aggProps.CompressionMetrics)
    1992            1 :         }
    1993              : 
    1994            1 :         blobCompressionMetrics := blobCompressionStatsAnnotator.Annotation(&vers.BlobFiles)
    1995            1 :         metrics.BlobFiles.Compression.MergeWith(&blobCompressionMetrics)
    1996            1 : 
    1997            1 :         metrics.BlockCache = d.opts.Cache.Metrics()
    1998            1 :         metrics.FileCache, metrics.Filter = d.fileCache.Metrics()
    1999            1 :         metrics.TableIters = d.fileCache.IterCount()
    2000            1 :         metrics.CategoryStats = d.fileCache.SSTStatsCollector().GetStats()
    2001            1 : 
    2002            1 :         metrics.SecondaryCacheMetrics = d.objProvider.Metrics()
    2003            1 : 
    2004            1 :         metrics.Uptime = d.timeNow().Sub(d.openedAt)
    2005            1 : 
    2006            1 :         metrics.manualMemory = manual.GetMetrics()
    2007            1 : 
    2008            1 :         return metrics
    2009              : }
    2010              : 
    2011              : // sstablesOptions hold the optional parameters to retrieve TableInfo for all sstables.
    2012              : type sstablesOptions struct {
    2013              :         // set to true will return the sstable properties in TableInfo
    2014              :         withProperties bool
    2015              : 
    2016              :         // if set, return sstables that overlap the key range (end-exclusive)
    2017              :         start []byte
    2018              :         end   []byte
    2019              : 
    2020              :         withApproximateSpanBytes bool
    2021              : }
    2022              : 
    2023              : // SSTablesOption set optional parameter used by `DB.SSTables`.
    2024              : type SSTablesOption func(*sstablesOptions)
    2025              : 
    2026              : // WithProperties enable return sstable properties in each TableInfo.
    2027              : //
    2028              : // NOTE: if most of the sstable properties need to be read from disk,
    2029              : // this options may make method `SSTables` quite slow.
    2030            1 : func WithProperties() SSTablesOption {
    2031            1 :         return func(opt *sstablesOptions) {
    2032            1 :                 opt.withProperties = true
    2033            1 :         }
    2034              : }
    2035              : 
    2036              : // WithKeyRangeFilter ensures returned sstables overlap start and end (end-exclusive)
    2037              : // if start and end are both nil these properties have no effect.
    2038            1 : func WithKeyRangeFilter(start, end []byte) SSTablesOption {
    2039            1 :         return func(opt *sstablesOptions) {
    2040            1 :                 opt.end = end
    2041            1 :                 opt.start = start
    2042            1 :         }
    2043              : }
    2044              : 
    2045              : // WithApproximateSpanBytes enables capturing the approximate number of bytes that
    2046              : // overlap the provided key span for each sstable.
    2047              : // NOTE: This option requires WithKeyRangeFilter.
    2048            1 : func WithApproximateSpanBytes() SSTablesOption {
    2049            1 :         return func(opt *sstablesOptions) {
    2050            1 :                 opt.withApproximateSpanBytes = true
    2051            1 :         }
    2052              : }
    2053              : 
    2054              : // BackingType denotes the type of storage backing a given sstable.
    2055              : type BackingType int
    2056              : 
    2057              : const (
    2058              :         // BackingTypeLocal denotes an sstable stored on local disk according to the
    2059              :         // objprovider. This file is completely owned by us.
    2060              :         BackingTypeLocal BackingType = iota
    2061              :         // BackingTypeShared denotes an sstable stored on shared storage, created
    2062              :         // by this Pebble instance and possibly shared by other Pebble instances.
    2063              :         // These types of files have lifecycle managed by Pebble.
    2064              :         BackingTypeShared
    2065              :         // BackingTypeSharedForeign denotes an sstable stored on shared storage,
    2066              :         // created by a Pebble instance other than this one. These types of files have
    2067              :         // lifecycle managed by Pebble.
    2068              :         BackingTypeSharedForeign
    2069              :         // BackingTypeExternal denotes an sstable stored on external storage,
    2070              :         // not owned by any Pebble instance and with no refcounting/cleanup methods
    2071              :         // or lifecycle management. An example of an external file is a file restored
    2072              :         // from a backup.
    2073              :         BackingTypeExternal
    2074              :         backingTypeCount
    2075              : )
    2076              : 
    2077              : var backingTypeToString = [backingTypeCount]string{
    2078              :         BackingTypeLocal:         "local",
    2079              :         BackingTypeShared:        "shared",
    2080              :         BackingTypeSharedForeign: "shared-foreign",
    2081              :         BackingTypeExternal:      "external",
    2082              : }
    2083              : 
    2084              : // String implements fmt.Stringer.
    2085            0 : func (b BackingType) String() string {
    2086            0 :         return backingTypeToString[b]
    2087            0 : }
    2088              : 
    2089              : // SSTableInfo export manifest.TableInfo with sstable.Properties alongside
    2090              : // other file backing info.
    2091              : type SSTableInfo struct {
    2092              :         manifest.TableInfo
    2093              :         TableStats manifest.TableStats
    2094              :         // Virtual indicates whether the sstable is virtual.
    2095              :         Virtual bool
    2096              :         // BackingSSTNum is the disk file number associated with the backing sstable.
    2097              :         // If Virtual is false, BackingSSTNum == PhysicalTableDiskFileNum(TableNum).
    2098              :         BackingSSTNum base.DiskFileNum
    2099              :         // BackingSize is the size of the backing sstable. This is the same with
    2100              :         // TableInfo.Size when the table is not virtual.
    2101              :         BackingSize uint64
    2102              :         // BackingType is the type of storage backing this sstable.
    2103              :         BackingType BackingType
    2104              :         // Locator is the remote.Locator backing this sstable, if the backing type is
    2105              :         // not BackingTypeLocal.
    2106              :         Locator remote.Locator
    2107              :         // ApproximateSpanBytes describes the approximate number of bytes within the
    2108              :         // sstable that fall within a particular span. It's populated only when the
    2109              :         // ApproximateSpanBytes option is passed into DB.SSTables.
    2110              :         ApproximateSpanBytes uint64 `json:"ApproximateSpanBytes,omitempty"`
    2111              : 
    2112              :         // Properties is the sstable properties of this table. If Virtual is true,
    2113              :         // then the Properties are associated with the backing sst.
    2114              :         Properties *sstable.Properties
    2115              : }
    2116              : 
    2117              : // SSTables retrieves the current sstables. The returned slice is indexed by
    2118              : // level and each level is indexed by the position of the sstable within the
    2119              : // level. Note that this information may be out of date due to concurrent
    2120              : // flushes and compactions.
    2121            1 : func (d *DB) SSTables(opts ...SSTablesOption) ([][]SSTableInfo, error) {
    2122            1 :         opt := &sstablesOptions{}
    2123            1 :         for _, fn := range opts {
    2124            1 :                 fn(opt)
    2125            1 :         }
    2126              : 
    2127            1 :         if opt.withApproximateSpanBytes && (opt.start == nil || opt.end == nil) {
    2128            1 :                 return nil, errors.Errorf("cannot use WithApproximateSpanBytes without WithKeyRangeFilter option")
    2129            1 :         }
    2130              : 
    2131              :         // Grab and reference the current readState.
    2132            1 :         readState := d.loadReadState()
    2133            1 :         defer readState.unref()
    2134            1 : 
    2135            1 :         // TODO(peter): This is somewhat expensive, especially on a large
    2136            1 :         // database. It might be worthwhile to unify TableInfo and TableMetadata and
    2137            1 :         // then we could simply return current.Files. Note that RocksDB is doing
    2138            1 :         // something similar to the current code, so perhaps it isn't too bad.
    2139            1 :         srcLevels := readState.current.Levels
    2140            1 :         var totalTables int
    2141            1 :         for i := range srcLevels {
    2142            1 :                 totalTables += srcLevels[i].Len()
    2143            1 :         }
    2144              : 
    2145            1 :         destTables := make([]SSTableInfo, totalTables)
    2146            1 :         destLevels := make([][]SSTableInfo, len(srcLevels))
    2147            1 :         for i := range destLevels {
    2148            1 :                 j := 0
    2149            1 :                 for m := range srcLevels[i].All() {
    2150            1 :                         if opt.start != nil && opt.end != nil {
    2151            1 :                                 b := base.UserKeyBoundsEndExclusive(opt.start, opt.end)
    2152            1 :                                 if !m.Overlaps(d.opts.Comparer.Compare, &b) {
    2153            1 :                                         continue
    2154              :                                 }
    2155              :                         }
    2156            1 :                         destTables[j] = SSTableInfo{
    2157            1 :                                 TableInfo: m.TableInfo(),
    2158            1 :                         }
    2159            1 :                         if stats, ok := m.Stats(); ok {
    2160            1 :                                 destTables[j].TableStats = *stats
    2161            1 :                         }
    2162            1 :                         if opt.withProperties {
    2163            1 :                                 p, err := d.fileCache.getTableProperties(
    2164            1 :                                         m,
    2165            1 :                                 )
    2166            1 :                                 if err != nil {
    2167            0 :                                         return nil, err
    2168            0 :                                 }
    2169            1 :                                 destTables[j].Properties = p
    2170              :                         }
    2171            1 :                         destTables[j].Virtual = m.Virtual
    2172            1 :                         destTables[j].BackingSSTNum = m.TableBacking.DiskFileNum
    2173            1 :                         destTables[j].BackingSize = m.TableBacking.Size
    2174            1 :                         objMeta, err := d.objProvider.Lookup(base.FileTypeTable, m.TableBacking.DiskFileNum)
    2175            1 :                         if err != nil {
    2176            0 :                                 return nil, err
    2177            0 :                         }
    2178            1 :                         if objMeta.IsRemote() {
    2179            0 :                                 if objMeta.IsShared() {
    2180            0 :                                         if d.objProvider.IsSharedForeign(objMeta) {
    2181            0 :                                                 destTables[j].BackingType = BackingTypeSharedForeign
    2182            0 :                                         } else {
    2183            0 :                                                 destTables[j].BackingType = BackingTypeShared
    2184            0 :                                         }
    2185            0 :                                 } else {
    2186            0 :                                         destTables[j].BackingType = BackingTypeExternal
    2187            0 :                                 }
    2188            0 :                                 destTables[j].Locator = objMeta.Remote.Locator
    2189            1 :                         } else {
    2190            1 :                                 destTables[j].BackingType = BackingTypeLocal
    2191            1 :                         }
    2192              : 
    2193            1 :                         if opt.withApproximateSpanBytes {
    2194            1 :                                 if m.ContainedWithinSpan(d.opts.Comparer.Compare, opt.start, opt.end) {
    2195            0 :                                         destTables[j].ApproximateSpanBytes = m.Size
    2196            1 :                                 } else {
    2197            1 :                                         size, err := d.fileCache.estimateSize(m, opt.start, opt.end)
    2198            1 :                                         if err != nil {
    2199            0 :                                                 return nil, err
    2200            0 :                                         }
    2201            1 :                                         destTables[j].ApproximateSpanBytes = size
    2202              :                                 }
    2203              :                         }
    2204            1 :                         j++
    2205              :                 }
    2206            1 :                 destLevels[i] = destTables[:j]
    2207            1 :                 destTables = destTables[j:]
    2208              :         }
    2209              : 
    2210            1 :         return destLevels, nil
    2211              : }
    2212              : 
    2213            1 : func (d *DB) walPreallocateSize() int {
    2214            1 :         // Set the WAL preallocate size to 110% of the memtable size. Note that there
    2215            1 :         // is a bit of apples and oranges in units here as the memtabls size
    2216            1 :         // corresponds to the memory usage of the memtable while the WAL size is the
    2217            1 :         // size of the batches (plus overhead) stored in the WAL.
    2218            1 :         //
    2219            1 :         // TODO(peter): 110% of the memtable size is quite hefty for a block
    2220            1 :         // size. This logic is taken from GetWalPreallocateBlockSize in
    2221            1 :         // RocksDB. Could a smaller preallocation block size be used?
    2222            1 :         size := d.opts.MemTableSize
    2223            1 :         size = (size / 10) + size
    2224            1 :         return int(size)
    2225            1 : }
    2226              : 
    2227              : func (d *DB) newMemTable(
    2228              :         logNum base.DiskFileNum, logSeqNum base.SeqNum, minSize uint64,
    2229            1 : ) (*memTable, *flushableEntry) {
    2230            1 :         targetSize := minSize + uint64(memTableEmptySize)
    2231            1 :         // The targetSize should be less than MemTableSize, because any batch >=
    2232            1 :         // MemTableSize/2 should be treated as a large flushable batch.
    2233            1 :         if targetSize > d.opts.MemTableSize {
    2234            0 :                 panic(errors.AssertionFailedf("attempting to allocate memtable larger than MemTableSize"))
    2235              :         }
    2236              :         // Double until the next memtable size is at least large enough to fit
    2237              :         // minSize.
    2238            1 :         for d.mu.mem.nextSize < targetSize {
    2239            1 :                 d.mu.mem.nextSize = min(2*d.mu.mem.nextSize, d.opts.MemTableSize)
    2240            1 :         }
    2241            1 :         size := d.mu.mem.nextSize
    2242            1 :         // The next memtable should be double the size, up to Options.MemTableSize.
    2243            1 :         if d.mu.mem.nextSize < d.opts.MemTableSize {
    2244            1 :                 d.mu.mem.nextSize = min(2*d.mu.mem.nextSize, d.opts.MemTableSize)
    2245            1 :         }
    2246              : 
    2247            1 :         memtblOpts := memTableOptions{
    2248            1 :                 Options:   d.opts,
    2249            1 :                 logSeqNum: logSeqNum,
    2250            1 :         }
    2251            1 : 
    2252            1 :         // Before attempting to allocate a new memtable, check if there's one
    2253            1 :         // available for recycling in memTableRecycle. Large contiguous allocations
    2254            1 :         // can be costly as fragmentation makes it more difficult to find a large
    2255            1 :         // contiguous free space. We've observed 64MB allocations taking 10ms+.
    2256            1 :         //
    2257            1 :         // To reduce these costly allocations, up to 1 obsolete memtable is stashed
    2258            1 :         // in `d.memTableRecycle` to allow a future memtable rotation to reuse
    2259            1 :         // existing memory.
    2260            1 :         var mem *memTable
    2261            1 :         mem = d.memTableRecycle.Swap(nil)
    2262            1 :         if mem != nil && uint64(mem.arenaBuf.Len()) != size {
    2263            1 :                 d.freeMemTable(mem)
    2264            1 :                 mem = nil
    2265            1 :         }
    2266            1 :         if mem != nil {
    2267            1 :                 // Carry through the existing buffer and memory reservation.
    2268            1 :                 memtblOpts.arenaBuf = mem.arenaBuf
    2269            1 :                 memtblOpts.releaseAccountingReservation = mem.releaseAccountingReservation
    2270            1 :         } else {
    2271            1 :                 mem = new(memTable)
    2272            1 :                 memtblOpts.arenaBuf = manual.New(manual.MemTable, uintptr(size))
    2273            1 :                 memtblOpts.releaseAccountingReservation = d.opts.Cache.Reserve(int(size))
    2274            1 :                 d.memTableCount.Add(1)
    2275            1 :                 d.memTableReserved.Add(int64(size))
    2276            1 : 
    2277            1 :                 // Note: this is a no-op if invariants are disabled or race is enabled.
    2278            1 :                 invariants.SetFinalizer(mem, checkMemTable)
    2279            1 :         }
    2280            1 :         mem.init(memtblOpts)
    2281            1 : 
    2282            1 :         entry := d.newFlushableEntry(mem, logNum, logSeqNum)
    2283            1 :         entry.releaseMemAccounting = func() {
    2284            1 :                 // If the user leaks iterators, we may be releasing the memtable after
    2285            1 :                 // the DB is already closed. In this case, we want to just release the
    2286            1 :                 // memory because DB.Close won't come along to free it for us.
    2287            1 :                 if err := d.closed.Load(); err != nil {
    2288            1 :                         d.freeMemTable(mem)
    2289            1 :                         return
    2290            1 :                 }
    2291              : 
    2292              :                 // The next memtable allocation might be able to reuse this memtable.
    2293              :                 // Stash it on d.memTableRecycle.
    2294            1 :                 if unusedMem := d.memTableRecycle.Swap(mem); unusedMem != nil {
    2295            1 :                         // There was already a memtable waiting to be recycled. We're now
    2296            1 :                         // responsible for freeing it.
    2297            1 :                         d.freeMemTable(unusedMem)
    2298            1 :                 }
    2299              :         }
    2300            1 :         return mem, entry
    2301              : }
    2302              : 
    2303            1 : func (d *DB) freeMemTable(m *memTable) {
    2304            1 :         d.memTableCount.Add(-1)
    2305            1 :         d.memTableReserved.Add(-int64(m.arenaBuf.Len()))
    2306            1 :         m.free()
    2307            1 : }
    2308              : 
    2309              : func (d *DB) newFlushableEntry(
    2310              :         f flushable, logNum base.DiskFileNum, logSeqNum base.SeqNum,
    2311            1 : ) *flushableEntry {
    2312            1 :         fe := &flushableEntry{
    2313            1 :                 flushable:      f,
    2314            1 :                 flushed:        make(chan struct{}),
    2315            1 :                 logNum:         logNum,
    2316            1 :                 logSeqNum:      logSeqNum,
    2317            1 :                 deleteFn:       d.mu.versions.addObsolete,
    2318            1 :                 deleteFnLocked: d.mu.versions.addObsoleteLocked,
    2319            1 :         }
    2320            1 :         fe.readerRefs.Store(1)
    2321            1 :         return fe
    2322            1 : }
    2323              : 
    2324              : // maybeInduceWriteStall is called before performing a memtable rotation in
    2325              : // makeRoomForWrite. In some conditions, we prefer to stall the user's write
    2326              : // workload rather than continuing to accept writes that may result in resource
    2327              : // exhaustion or prohibitively slow reads.
    2328              : //
    2329              : // There are a couple reasons we might wait to rotate the memtable and
    2330              : // instead induce a write stall:
    2331              : //  1. If too many memtables have queued, we wait for a flush to finish before
    2332              : //     creating another memtable.
    2333              : //  2. If L0 read amplification has grown too high, we wait for compactions
    2334              : //     to reduce the read amplification before accepting more writes that will
    2335              : //     increase write pressure.
    2336              : //
    2337              : // maybeInduceWriteStall checks these stall conditions, and if present, waits
    2338              : // for them to abate.
    2339            1 : func (d *DB) maybeInduceWriteStall(b *Batch) {
    2340            1 :         stalled := false
    2341            1 :         // This function will call EventListener.WriteStallBegin at most once.  If
    2342            1 :         // it does call it, it will call EventListener.WriteStallEnd once before
    2343            1 :         // returning.
    2344            1 :         var timer *time.Timer
    2345            1 :         for {
    2346            1 :                 var size uint64
    2347            1 :                 for i := range d.mu.mem.queue {
    2348            1 :                         size += d.mu.mem.queue[i].totalBytes()
    2349            1 :                 }
    2350            1 :                 if size >= uint64(d.opts.MemTableStopWritesThreshold)*d.opts.MemTableSize &&
    2351            1 :                         !d.mu.log.manager.ElevateWriteStallThresholdForFailover() {
    2352            1 :                         // We have filled up the current memtable, but already queued memtables
    2353            1 :                         // are still flushing, so we wait.
    2354            1 :                         if !stalled {
    2355            1 :                                 stalled = true
    2356            1 :                                 d.opts.EventListener.WriteStallBegin(WriteStallBeginInfo{
    2357            1 :                                         Reason: "memtable count limit reached",
    2358            1 :                                 })
    2359            1 :                         }
    2360            1 :                         beforeWait := crtime.NowMono()
    2361            1 :                         // NB: In a rare case, we can start a write stall, and then the system
    2362            1 :                         // may detect WAL failover, resulting in
    2363            1 :                         // ElevateWriteStallThresholdForFailover returning true. So we want to
    2364            1 :                         // recheck the predicate periodically, which we do by signaling the
    2365            1 :                         // condition variable.
    2366            1 :                         if timer == nil {
    2367            1 :                                 timer = time.AfterFunc(time.Second, d.mu.compact.cond.Broadcast)
    2368            1 :                         } else {
    2369            1 :                                 timer.Reset(time.Second)
    2370            1 :                         }
    2371            1 :                         d.mu.compact.cond.Wait()
    2372            1 :                         timer.Stop()
    2373            1 :                         if b != nil {
    2374            1 :                                 b.commitStats.MemTableWriteStallDuration += beforeWait.Elapsed()
    2375            1 :                         }
    2376            1 :                         continue
    2377              :                 }
    2378            1 :                 l0ReadAmp := d.mu.versions.latest.l0Organizer.ReadAmplification()
    2379            1 :                 if l0ReadAmp >= d.opts.L0StopWritesThreshold {
    2380            1 :                         // There are too many level-0 files, so we wait.
    2381            1 :                         if !stalled {
    2382            1 :                                 stalled = true
    2383            1 :                                 d.opts.EventListener.WriteStallBegin(WriteStallBeginInfo{
    2384            1 :                                         Reason: "L0 file count limit exceeded",
    2385            1 :                                 })
    2386            1 :                         }
    2387            1 :                         beforeWait := crtime.NowMono()
    2388            1 :                         d.mu.compact.cond.Wait()
    2389            1 :                         if b != nil {
    2390            1 :                                 b.commitStats.L0ReadAmpWriteStallDuration += beforeWait.Elapsed()
    2391            1 :                         }
    2392            1 :                         continue
    2393              :                 }
    2394              :                 // Not stalled.
    2395            1 :                 if stalled {
    2396            1 :                         d.opts.EventListener.WriteStallEnd()
    2397            1 :                 }
    2398            1 :                 return
    2399              :         }
    2400              : }
    2401              : 
    2402              : // makeRoomForWrite rotates the current mutable memtable, ensuring that the
    2403              : // resulting mutable memtable has room to hold the contents of the provided
    2404              : // Batch. The current memtable is rotated (marked as immutable) and a new
    2405              : // mutable memtable is allocated. It reserves space in the new memtable and adds
    2406              : // a reference to the memtable. The caller must later ensure that the memtable
    2407              : // is unreferenced. This memtable rotation also causes a log rotation.
    2408              : //
    2409              : // If the current memtable is not full but the caller wishes to trigger a
    2410              : // rotation regardless, the caller may pass a nil Batch, and no space in the
    2411              : // resulting mutable memtable will be reserved.
    2412              : //
    2413              : // Both DB.mu and commitPipeline.mu must be held by the caller. Note that DB.mu
    2414              : // may be released and reacquired.
    2415            1 : func (d *DB) makeRoomForWrite(b *Batch) error {
    2416            1 :         if b != nil && b.ingestedSSTBatch {
    2417            0 :                 panic("pebble: invalid function call")
    2418              :         }
    2419            1 :         d.maybeInduceWriteStall(b)
    2420            1 : 
    2421            1 :         var newLogNum base.DiskFileNum
    2422            1 :         var prevLogSize uint64
    2423            1 :         if !d.opts.DisableWAL {
    2424            1 :                 beforeRotate := crtime.NowMono()
    2425            1 :                 newLogNum, prevLogSize = d.rotateWAL()
    2426            1 :                 if b != nil {
    2427            1 :                         b.commitStats.WALRotationDuration += beforeRotate.Elapsed()
    2428            1 :                 }
    2429              :         }
    2430            1 :         immMem := d.mu.mem.mutable
    2431            1 :         imm := d.mu.mem.queue[len(d.mu.mem.queue)-1]
    2432            1 :         imm.logSize = prevLogSize
    2433            1 : 
    2434            1 :         var logSeqNum base.SeqNum
    2435            1 :         var minSize uint64
    2436            1 :         if b != nil {
    2437            1 :                 logSeqNum = b.SeqNum()
    2438            1 :                 if b.flushable != nil {
    2439            1 :                         logSeqNum += base.SeqNum(b.Count())
    2440            1 :                         // The batch is too large to fit in the memtable so add it directly to
    2441            1 :                         // the immutable queue. The flushable batch is associated with the same
    2442            1 :                         // log as the immutable memtable, but logically occurs after it in
    2443            1 :                         // seqnum space. We ensure while flushing that the flushable batch
    2444            1 :                         // is flushed along with the previous memtable in the flushable
    2445            1 :                         // queue. See the top level comment in DB.flush1 to learn how this
    2446            1 :                         // is ensured.
    2447            1 :                         //
    2448            1 :                         // See DB.commitWrite for the special handling of log writes for large
    2449            1 :                         // batches. In particular, the large batch has already written to
    2450            1 :                         // imm.logNum.
    2451            1 :                         entry := d.newFlushableEntry(b.flushable, imm.logNum, b.SeqNum())
    2452            1 :                         // The large batch is by definition large. Reserve space from the cache
    2453            1 :                         // for it until it is flushed.
    2454            1 :                         entry.releaseMemAccounting = d.opts.Cache.Reserve(int(b.flushable.totalBytes()))
    2455            1 :                         d.mu.mem.queue = append(d.mu.mem.queue, entry)
    2456            1 :                 } else {
    2457            1 :                         minSize = b.memTableSize
    2458            1 :                 }
    2459            1 :         } else {
    2460            1 :                 // b == nil
    2461            1 :                 //
    2462            1 :                 // This is a manual forced flush.
    2463            1 :                 logSeqNum = base.SeqNum(d.mu.versions.logSeqNum.Load())
    2464            1 :                 imm.flushForced = true
    2465            1 :                 // If we are manually flushing and we used less than half of the bytes in
    2466            1 :                 // the memtable, don't increase the size for the next memtable. This
    2467            1 :                 // reduces memtable memory pressure when an application is frequently
    2468            1 :                 // manually flushing.
    2469            1 :                 if uint64(immMem.availBytes()) > immMem.totalBytes()/2 {
    2470            1 :                         d.mu.mem.nextSize = immMem.totalBytes()
    2471            1 :                 }
    2472              :         }
    2473            1 :         d.rotateMemtable(newLogNum, logSeqNum, immMem, minSize)
    2474            1 :         if b != nil && b.flushable == nil {
    2475            1 :                 err := d.mu.mem.mutable.prepare(b)
    2476            1 :                 // Reserving enough space for the batch after rotation must never fail.
    2477            1 :                 // We pass in a minSize that's equal to b.memtableSize to ensure that
    2478            1 :                 // memtable rotation allocates a memtable sufficiently large. We also
    2479            1 :                 // held d.commit.mu for the entirety of this function, ensuring that no
    2480            1 :                 // other committers may have reserved memory in the new memtable yet.
    2481            1 :                 if err == arenaskl.ErrArenaFull {
    2482            0 :                         panic(errors.AssertionFailedf("memtable still full after rotation"))
    2483              :                 }
    2484            1 :                 return err
    2485              :         }
    2486            1 :         return nil
    2487              : }
    2488              : 
    2489              : // Both DB.mu and commitPipeline.mu must be held by the caller.
    2490              : func (d *DB) rotateMemtable(
    2491              :         newLogNum base.DiskFileNum, logSeqNum base.SeqNum, prev *memTable, minSize uint64,
    2492            1 : ) {
    2493            1 :         // Create a new memtable, scheduling the previous one for flushing. We do
    2494            1 :         // this even if the previous memtable was empty because the DB.Flush
    2495            1 :         // mechanism is dependent on being able to wait for the empty memtable to
    2496            1 :         // flush. We can't just mark the empty memtable as flushed here because we
    2497            1 :         // also have to wait for all previous immutable tables to
    2498            1 :         // flush. Additionally, the memtable is tied to particular WAL file and we
    2499            1 :         // want to go through the flush path in order to recycle that WAL file.
    2500            1 :         //
    2501            1 :         // NB: newLogNum corresponds to the WAL that contains mutations that are
    2502            1 :         // present in the new memtable. When immutable memtables are flushed to
    2503            1 :         // disk, a VersionEdit will be created telling the manifest the minimum
    2504            1 :         // unflushed log number (which will be the next one in d.mu.mem.mutable
    2505            1 :         // that was not flushed).
    2506            1 :         //
    2507            1 :         // NB: prev should be the current mutable memtable.
    2508            1 :         var entry *flushableEntry
    2509            1 :         d.mu.mem.mutable, entry = d.newMemTable(newLogNum, logSeqNum, minSize)
    2510            1 :         d.mu.mem.queue = append(d.mu.mem.queue, entry)
    2511            1 :         // d.logSize tracks the log size of the WAL file corresponding to the most
    2512            1 :         // recent flushable. The log size of the previous mutable memtable no longer
    2513            1 :         // applies to the current mutable memtable.
    2514            1 :         //
    2515            1 :         // It's tempting to perform this update in rotateWAL, but that would not be
    2516            1 :         // atomic with the enqueue of the new flushable. A call to DB.Metrics()
    2517            1 :         // could acquire DB.mu after the WAL has been rotated but before the new
    2518            1 :         // memtable has been appended; this would result in omitting the log size of
    2519            1 :         // the most recent flushable.
    2520            1 :         d.logSize.Store(0)
    2521            1 :         d.updateReadStateLocked(nil)
    2522            1 :         if prev.writerUnref() {
    2523            1 :                 d.maybeScheduleFlush()
    2524            1 :         }
    2525              : }
    2526              : 
    2527              : // rotateWAL creates a new write-ahead log, possibly recycling a previous WAL's
    2528              : // files. It returns the file number assigned to the new WAL, and the size of
    2529              : // the previous WAL file.
    2530              : //
    2531              : // Both DB.mu and commitPipeline.mu must be held by the caller. Note that DB.mu
    2532              : // may be released and reacquired.
    2533            1 : func (d *DB) rotateWAL() (newLogNum base.DiskFileNum, prevLogSize uint64) {
    2534            1 :         if d.opts.DisableWAL {
    2535            0 :                 panic("pebble: invalid function call")
    2536              :         }
    2537            1 :         jobID := d.newJobIDLocked()
    2538            1 :         newLogNum = d.mu.versions.getNextDiskFileNum()
    2539            1 : 
    2540            1 :         d.mu.Unlock()
    2541            1 :         // Close the previous log first. This writes an EOF trailer
    2542            1 :         // signifying the end of the file and syncs it to disk. We must
    2543            1 :         // close the previous log before linking the new log file,
    2544            1 :         // otherwise a crash could leave both logs with unclean tails, and
    2545            1 :         // Open will treat the previous log as corrupt.
    2546            1 :         offset, err := d.mu.log.writer.Close()
    2547            1 :         if err != nil {
    2548            0 :                 // What to do here? Stumbling on doesn't seem worthwhile. If we failed to
    2549            0 :                 // close the previous log it is possible we lost a write.
    2550            0 :                 d.opts.Logger.Fatalf("pebble: error closing WAL; data loss possible if we continue: %s", err)
    2551            0 :         }
    2552            1 :         prevLogSize = uint64(offset)
    2553            1 :         metrics := d.mu.log.writer.Metrics()
    2554            1 : 
    2555            1 :         d.mu.Lock()
    2556            1 :         if err := d.mu.log.metrics.LogWriterMetrics.Merge(&metrics); err != nil {
    2557            0 :                 d.opts.Logger.Errorf("metrics error: %s", err)
    2558            0 :         }
    2559              : 
    2560            1 :         d.mu.Unlock()
    2561            1 :         writer, err := d.mu.log.manager.Create(wal.NumWAL(newLogNum), int(jobID))
    2562            1 :         if err != nil {
    2563            0 :                 panic(err)
    2564              :         }
    2565              : 
    2566            1 :         d.mu.Lock()
    2567            1 :         d.mu.log.writer = writer
    2568            1 :         return newLogNum, prevLogSize
    2569              : }
    2570              : 
    2571            1 : func (d *DB) getEarliestUnflushedSeqNumLocked() base.SeqNum {
    2572            1 :         seqNum := base.SeqNumMax
    2573            1 :         for i := range d.mu.mem.queue {
    2574            1 :                 logSeqNum := d.mu.mem.queue[i].logSeqNum
    2575            1 :                 if seqNum > logSeqNum {
    2576            1 :                         seqNum = logSeqNum
    2577            1 :                 }
    2578              :         }
    2579            1 :         return seqNum
    2580              : }
    2581              : 
    2582            1 : func (d *DB) getInProgressCompactionInfoLocked(finishing compaction) (rv []compactionInfo) {
    2583            1 :         for c := range d.mu.compact.inProgress {
    2584            1 :                 if !c.IsFlush() && (finishing == nil || c != finishing) {
    2585            1 :                         rv = append(rv, c.Info())
    2586            1 :                 }
    2587              :         }
    2588            1 :         return
    2589              : }
    2590              : 
    2591            1 : func inProgressL0Compactions(inProgress []compactionInfo) []manifest.L0Compaction {
    2592            1 :         var compactions []manifest.L0Compaction
    2593            1 :         for _, info := range inProgress {
    2594            1 :                 // Skip in-progress compactions that have already committed; the L0
    2595            1 :                 // sublevels initialization code requires the set of in-progress
    2596            1 :                 // compactions to be consistent with the current version. Compactions
    2597            1 :                 // with versionEditApplied=true are already applied to the current
    2598            1 :                 // version and but are performing cleanup without the database mutex.
    2599            1 :                 if info.versionEditApplied {
    2600            1 :                         continue
    2601              :                 }
    2602            1 :                 l0 := false
    2603            1 :                 for _, cl := range info.inputs {
    2604            1 :                         l0 = l0 || cl.level == 0
    2605            1 :                 }
    2606            1 :                 if !l0 {
    2607            1 :                         continue
    2608              :                 }
    2609            1 :                 compactions = append(compactions, manifest.L0Compaction{
    2610            1 :                         Bounds:    *info.bounds,
    2611            1 :                         IsIntraL0: info.outputLevel == 0,
    2612            1 :                 })
    2613              :         }
    2614            1 :         return compactions
    2615              : }
    2616              : 
    2617              : // firstError returns the first non-nil error of err0 and err1, or nil if both
    2618              : // are nil.
    2619            1 : func firstError(err0, err1 error) error {
    2620            1 :         if err0 != nil {
    2621            1 :                 return err0
    2622            1 :         }
    2623            1 :         return err1
    2624              : }
    2625              : 
    2626              : // SetCreatorID sets the CreatorID which is needed in order to use shared objects.
    2627              : // Remote object usage is disabled until this method is called the first time.
    2628              : // Once set, the Creator ID is persisted and cannot change.
    2629              : //
    2630              : // Does nothing if SharedStorage was not set in the options when the DB was
    2631              : // opened or if the DB is in read-only mode.
    2632            1 : func (d *DB) SetCreatorID(creatorID uint64) error {
    2633            1 :         if d.opts.Experimental.RemoteStorage == nil || d.opts.ReadOnly {
    2634            0 :                 return nil
    2635            0 :         }
    2636            1 :         return d.objProvider.SetCreatorID(objstorage.CreatorID(creatorID))
    2637              : }
    2638              : 
    2639              : // KeyStatistics keeps track of the number of keys that have been pinned by a
    2640              : // snapshot as well as counts of the different key kinds in the lsm.
    2641              : //
    2642              : // One way of using the accumulated stats, when we only have sets and dels,
    2643              : // and say the counts are represented as del_count, set_count,
    2644              : // del_latest_count, set_latest_count, snapshot_pinned_count.
    2645              : //
    2646              : //   - del_latest_count + set_latest_count is the set of unique user keys
    2647              : //     (unique).
    2648              : //
    2649              : //   - set_latest_count is the set of live unique user keys (live_unique).
    2650              : //
    2651              : //   - Garbage is del_count + set_count - live_unique.
    2652              : //
    2653              : //   - If everything were in the LSM, del_count+set_count-snapshot_pinned_count
    2654              : //     would also be the set of unique user keys (note that
    2655              : //     snapshot_pinned_count is counting something different -- see comment below).
    2656              : //     But snapshot_pinned_count only counts keys in the LSM so the excess here
    2657              : //     must be keys in memtables.
    2658              : type KeyStatistics struct {
    2659              :         // TODO(sumeer): the SnapshotPinned* are incorrect in that these older
    2660              :         // versions can be in a different level. Either fix the accounting or
    2661              :         // rename these fields.
    2662              : 
    2663              :         // SnapshotPinnedKeys represents obsolete keys that cannot be elided during
    2664              :         // a compaction, because they are required by an open snapshot.
    2665              :         SnapshotPinnedKeys int
    2666              :         // SnapshotPinnedKeysBytes is the total number of bytes of all snapshot
    2667              :         // pinned keys.
    2668              :         SnapshotPinnedKeysBytes uint64
    2669              :         // KindsCount is the count for each kind of key. It includes point keys,
    2670              :         // range deletes and range keys.
    2671              :         KindsCount [InternalKeyKindMax + 1]int
    2672              :         // LatestKindsCount is the count for each kind of key when it is the latest
    2673              :         // kind for a user key. It is only populated for point keys.
    2674              :         LatestKindsCount [InternalKeyKindMax + 1]int
    2675              : }
    2676              : 
    2677              : // LSMKeyStatistics is used by DB.ScanStatistics.
    2678              : type LSMKeyStatistics struct {
    2679              :         Accumulated KeyStatistics
    2680              :         // Levels contains statistics only for point keys. Range deletions and range keys will
    2681              :         // appear in Accumulated but not Levels.
    2682              :         Levels [numLevels]KeyStatistics
    2683              :         // BytesRead represents the logical, pre-compression size of keys and values read
    2684              :         BytesRead uint64
    2685              : }
    2686              : 
    2687              : // ScanStatisticsOptions is used by DB.ScanStatistics.
    2688              : type ScanStatisticsOptions struct {
    2689              :         // LimitBytesPerSecond indicates the number of bytes that are able to be read
    2690              :         // per second using ScanInternal.
    2691              :         // A value of 0 indicates that there is no limit set.
    2692              :         LimitBytesPerSecond int64
    2693              : }
    2694              : 
    2695              : // ScanStatistics returns the count of different key kinds within the lsm for a
    2696              : // key span [lower, upper) as well as the number of snapshot keys.
    2697              : func (d *DB) ScanStatistics(
    2698              :         ctx context.Context, lower, upper []byte, opts ScanStatisticsOptions,
    2699            1 : ) (stats LSMKeyStatistics, err error) {
    2700            1 :         var prevKey InternalKey
    2701            1 :         var rateLimitFunc func(key *InternalKey, val LazyValue) error
    2702            1 :         tb := tokenbucket.TokenBucket{}
    2703            1 : 
    2704            1 :         if opts.LimitBytesPerSecond != 0 {
    2705            0 :                 const minBytesPerSec = 100 * 1024
    2706            0 :                 if opts.LimitBytesPerSecond < minBytesPerSec {
    2707            0 :                         return stats, errors.Newf("pebble: ScanStatistics read bandwidth limit %d is below minimum %d", opts.LimitBytesPerSecond, minBytesPerSec)
    2708            0 :                 }
    2709              :                 // Each "token" roughly corresponds to a byte that was read.
    2710            0 :                 tb.Init(tokenbucket.TokensPerSecond(opts.LimitBytesPerSecond), tokenbucket.Tokens(1024))
    2711            0 :                 rateLimitFunc = func(key *InternalKey, val LazyValue) error {
    2712            0 :                         return tb.WaitCtx(ctx, tokenbucket.Tokens(key.Size()+val.Len()))
    2713            0 :                 }
    2714              :         }
    2715              : 
    2716            1 :         scanInternalOpts := &ScanInternalOptions{
    2717            1 :                 VisitPointKey: func(key *InternalKey, value LazyValue, iterInfo IteratorLevel) error {
    2718            1 :                         // If the previous key is equal to the current point key, the current key was
    2719            1 :                         // pinned by a snapshot.
    2720            1 :                         size := uint64(key.Size())
    2721            1 :                         kind := key.Kind()
    2722            1 :                         sameKey := d.equal(prevKey.UserKey, key.UserKey)
    2723            1 :                         if iterInfo.Kind == IteratorLevelLSM && sameKey {
    2724            1 :                                 stats.Levels[iterInfo.Level].SnapshotPinnedKeys++
    2725            1 :                                 stats.Levels[iterInfo.Level].SnapshotPinnedKeysBytes += size
    2726            1 :                                 stats.Accumulated.SnapshotPinnedKeys++
    2727            1 :                                 stats.Accumulated.SnapshotPinnedKeysBytes += size
    2728            1 :                         }
    2729            1 :                         if iterInfo.Kind == IteratorLevelLSM {
    2730            1 :                                 stats.Levels[iterInfo.Level].KindsCount[kind]++
    2731            1 :                         }
    2732            1 :                         if !sameKey {
    2733            1 :                                 if iterInfo.Kind == IteratorLevelLSM {
    2734            1 :                                         stats.Levels[iterInfo.Level].LatestKindsCount[kind]++
    2735            1 :                                 }
    2736            1 :                                 stats.Accumulated.LatestKindsCount[kind]++
    2737              :                         }
    2738              : 
    2739            1 :                         stats.Accumulated.KindsCount[kind]++
    2740            1 :                         prevKey.CopyFrom(*key)
    2741            1 :                         stats.BytesRead += uint64(key.Size() + value.Len())
    2742            1 :                         return nil
    2743              :                 },
    2744            0 :                 VisitRangeDel: func(start, end []byte, seqNum base.SeqNum) error {
    2745            0 :                         stats.Accumulated.KindsCount[InternalKeyKindRangeDelete]++
    2746            0 :                         stats.BytesRead += uint64(len(start) + len(end))
    2747            0 :                         return nil
    2748            0 :                 },
    2749            0 :                 VisitRangeKey: func(start, end []byte, keys []rangekey.Key) error {
    2750            0 :                         stats.BytesRead += uint64(len(start) + len(end))
    2751            0 :                         for _, key := range keys {
    2752            0 :                                 stats.Accumulated.KindsCount[key.Kind()]++
    2753            0 :                                 stats.BytesRead += uint64(len(key.Value) + len(key.Suffix))
    2754            0 :                         }
    2755            0 :                         return nil
    2756              :                 },
    2757              :                 IncludeObsoleteKeys: true,
    2758              :                 IterOptions: IterOptions{
    2759              :                         KeyTypes:   IterKeyTypePointsAndRanges,
    2760              :                         LowerBound: lower,
    2761              :                         UpperBound: upper,
    2762              :                 },
    2763              :                 RateLimitFunc: rateLimitFunc,
    2764              :         }
    2765            1 :         iter, err := d.newInternalIter(ctx, snapshotIterOpts{}, scanInternalOpts)
    2766            1 :         if err != nil {
    2767            0 :                 return LSMKeyStatistics{}, err
    2768            0 :         }
    2769            1 :         defer func() { err = errors.CombineErrors(err, iter.Close()) }()
    2770              : 
    2771            1 :         err = scanInternalImpl(ctx, iter, scanInternalOpts)
    2772            1 :         if err != nil {
    2773            0 :                 return LSMKeyStatistics{}, err
    2774            0 :         }
    2775            1 :         return stats, nil
    2776              : }
    2777              : 
    2778              : // ObjProvider returns the objstorage.Provider for this database. Meant to be
    2779              : // used for internal purposes only.
    2780            1 : func (d *DB) ObjProvider() objstorage.Provider {
    2781            1 :         return d.objProvider
    2782            1 : }
    2783              : 
    2784              : // DebugString returns a debugging string describing the LSM.
    2785            0 : func (d *DB) DebugString() string {
    2786            0 :         return d.DebugCurrentVersion().DebugString()
    2787            0 : }
    2788              : 
    2789              : // DebugCurrentVersion returns the current LSM tree metadata. Should only be
    2790              : // used for testing/debugging.
    2791            1 : func (d *DB) DebugCurrentVersion() *manifest.Version {
    2792            1 :         d.mu.Lock()
    2793            1 :         defer d.mu.Unlock()
    2794            1 :         return d.mu.versions.currentVersion()
    2795            1 : }
        

Generated by: LCOV version 2.0-1