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

Generated by: LCOV version 2.0-1