LCOV - code coverage report
Current view: top level - pebble - version_set.go (source / functions) Coverage Total Hit
Test: 2025-10-15 08:18Z f213f584 - tests only.lcov Lines: 90.1 % 826 744
Test Date: 2025-10-15 08:19:53 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
       6              : 
       7              : import (
       8              :         "fmt"
       9              :         "io"
      10              :         "slices"
      11              :         "sync"
      12              :         "sync/atomic"
      13              :         "time"
      14              : 
      15              :         "github.com/cockroachdb/crlib/crtime"
      16              :         "github.com/cockroachdb/errors"
      17              :         "github.com/cockroachdb/pebble/internal/base"
      18              :         "github.com/cockroachdb/pebble/internal/invariants"
      19              :         "github.com/cockroachdb/pebble/internal/manifest"
      20              :         "github.com/cockroachdb/pebble/objstorage"
      21              :         "github.com/cockroachdb/pebble/record"
      22              :         "github.com/cockroachdb/pebble/vfs"
      23              :         "github.com/cockroachdb/pebble/vfs/atomicfs"
      24              : )
      25              : 
      26              : const numLevels = manifest.NumLevels
      27              : 
      28              : const manifestMarkerName = `manifest`
      29              : 
      30              : // versionSet manages a collection of immutable versions, and manages the
      31              : // creation of a new version from the most recent version. A new version is
      32              : // created from an existing version by applying a version edit which is just
      33              : // like it sounds: a delta from the previous version. Version edits are logged
      34              : // to the MANIFEST file, which is replayed at startup.
      35              : type versionSet struct {
      36              :         // Next seqNum to use for WAL writes.
      37              :         logSeqNum base.AtomicSeqNum
      38              : 
      39              :         // The upper bound on sequence numbers that have been assigned so far. A
      40              :         // suffix of these sequence numbers may not have been written to a WAL. Both
      41              :         // logSeqNum and visibleSeqNum are atomically updated by the commitPipeline.
      42              :         // visibleSeqNum is <= logSeqNum.
      43              :         visibleSeqNum base.AtomicSeqNum
      44              : 
      45              :         // Number of bytes present in sstables being written by in-progress
      46              :         // compactions. This value will be zero if there are no in-progress
      47              :         // compactions. Updated and read atomically.
      48              :         atomicInProgressBytes atomic.Int64
      49              : 
      50              :         // Immutable fields.
      51              :         dirname  string
      52              :         provider objstorage.Provider
      53              :         // Set to DB.mu.
      54              :         mu   *sync.Mutex
      55              :         opts *Options
      56              :         fs   vfs.FS
      57              :         cmp  *base.Comparer
      58              :         // Dynamic base level allows the dynamic base level computation to be
      59              :         // disabled. Used by tests which want to create specific LSM structures.
      60              :         dynamicBaseLevel bool
      61              : 
      62              :         // Mutable fields.
      63              :         versions manifest.VersionList
      64              :         latest   latestVersionState
      65              :         picker   compactionPicker
      66              :         // curCompactionConcurrency is updated whenever picker is updated.
      67              :         // INVARIANT: >= 1.
      68              :         curCompactionConcurrency atomic.Int32
      69              : 
      70              :         // Not all metrics are kept here. See DB.Metrics().
      71              :         metrics Metrics
      72              : 
      73              :         // A pointer to versionSet.addObsoleteLocked. Avoids allocating a new closure
      74              :         // on the creation of every version.
      75              :         obsoleteFn func(manifest.ObsoleteFiles)
      76              :         // obsolete{Tables,Blobs,Manifests,Options} are sorted by file number ascending.
      77              :         obsoleteTables    []obsoleteFile
      78              :         obsoleteBlobs     []obsoleteFile
      79              :         obsoleteManifests []obsoleteFile
      80              :         obsoleteOptions   []obsoleteFile
      81              : 
      82              :         // Zombie tables which have been removed from the current version but are
      83              :         // still referenced by an inuse iterator.
      84              :         zombieTables zombieObjects
      85              :         // Zombie blobs which have been removed from the current version but are
      86              :         // still referenced by an inuse iterator.
      87              :         zombieBlobs zombieObjects
      88              : 
      89              :         // minUnflushedLogNum is the smallest WAL log file number corresponding to
      90              :         // mutations that have not been flushed to an sstable.
      91              :         minUnflushedLogNum base.DiskFileNum
      92              : 
      93              :         // The next file number. A single counter is used to assign file
      94              :         // numbers for the WAL, MANIFEST, sstable, and OPTIONS files.
      95              :         nextFileNum atomic.Uint64
      96              : 
      97              :         // The current manifest file number.
      98              :         manifestFileNum base.DiskFileNum
      99              :         manifestMarker  *atomicfs.Marker
     100              : 
     101              :         manifestFile          vfs.File
     102              :         manifest              *record.Writer
     103              :         getFormatMajorVersion func() FormatMajorVersion
     104              : 
     105              :         writing    bool
     106              :         writerCond sync.Cond
     107              :         // State for deciding when to write a snapshot. Protected by mu.
     108              :         rotationHelper record.RotationHelper
     109              : 
     110              :         pickedCompactionCache pickedCompactionCache
     111              : }
     112              : 
     113              : // latestVersionState maintains mutable state describing only the most recent
     114              : // version. Unlike a *Version, the state within this struct is updated as new
     115              : // version edits are applied.
     116              : type latestVersionState struct {
     117              :         l0Organizer *manifest.L0Organizer
     118              :         // blobFiles is the set of blob files referenced by the current version.
     119              :         // blobFiles is protected by the manifest logLock (not vs.mu).
     120              :         blobFiles manifest.CurrentBlobFileSet
     121              :         // virtualBackings contains information about the FileBackings which support
     122              :         // virtual sstables in the latest version. It is mainly used to determine when
     123              :         // a backing is no longer in use by the tables in the latest version; this is
     124              :         // not a trivial problem because compactions and other operations can happen
     125              :         // in parallel (and they can finish in unpredictable order).
     126              :         //
     127              :         // This mechanism is complementary to the backing Ref/Unref mechanism, which
     128              :         // determines when a backing is no longer used by *any* live version and can
     129              :         // be removed.
     130              :         //
     131              :         // In principle this should have been a copy-on-write structure, with each
     132              :         // Version having its own record of its virtual backings (similar to the
     133              :         // B-tree that holds the tables). However, in practice we only need it for the
     134              :         // latest version, so we use a simpler structure and store it in the
     135              :         // versionSet instead.
     136              :         //
     137              :         // virtualBackings is modified under DB.mu and the log lock. If it is accessed
     138              :         // under DB.mu and a version update is in progress, it reflects the state of
     139              :         // the next version.
     140              :         virtualBackings manifest.VirtualBackings
     141              : }
     142              : 
     143              : func (vs *versionSet) init(
     144              :         dirname string,
     145              :         provider objstorage.Provider,
     146              :         opts *Options,
     147              :         marker *atomicfs.Marker,
     148              :         getFMV func() FormatMajorVersion,
     149              :         mu *sync.Mutex,
     150            1 : ) {
     151            1 :         vs.dirname = dirname
     152            1 :         vs.provider = provider
     153            1 :         vs.mu = mu
     154            1 :         vs.writerCond.L = mu
     155            1 :         vs.opts = opts
     156            1 :         vs.fs = opts.FS
     157            1 :         vs.cmp = opts.Comparer
     158            1 :         vs.dynamicBaseLevel = true
     159            1 :         vs.versions.Init(mu)
     160            1 :         vs.latest.l0Organizer = manifest.NewL0Organizer(opts.Comparer, opts.FlushSplitBytes)
     161            1 :         vs.latest.virtualBackings = manifest.MakeVirtualBackings()
     162            1 :         vs.obsoleteFn = vs.addObsoleteLocked
     163            1 :         vs.zombieTables = makeZombieObjects()
     164            1 :         vs.zombieBlobs = makeZombieObjects()
     165            1 :         vs.nextFileNum.Store(1)
     166            1 :         vs.manifestMarker = marker
     167            1 :         vs.getFormatMajorVersion = getFMV
     168            1 : }
     169              : 
     170              : // create creates a version set for a fresh DB.
     171              : func (vs *versionSet) create(
     172              :         jobID JobID,
     173              :         dirname string,
     174              :         provider objstorage.Provider,
     175              :         opts *Options,
     176              :         marker *atomicfs.Marker,
     177              :         getFormatMajorVersion func() FormatMajorVersion,
     178              :         blobRewriteHeuristic manifest.BlobRewriteHeuristic,
     179              :         mu *sync.Mutex,
     180            1 : ) error {
     181            1 :         vs.init(dirname, provider, opts, marker, getFormatMajorVersion, mu)
     182            1 :         vs.latest.blobFiles.Init(nil, blobRewriteHeuristic)
     183            1 :         emptyVersion := manifest.NewInitialVersion(opts.Comparer)
     184            1 :         vs.append(emptyVersion)
     185            1 : 
     186            1 :         vs.setCompactionPicker(
     187            1 :                 newCompactionPickerByScore(emptyVersion, &vs.latest, vs.opts, nil))
     188            1 :         // Note that a "snapshot" version edit is written to the manifest when it is
     189            1 :         // created.
     190            1 :         vs.manifestFileNum = vs.getNextDiskFileNum()
     191            1 :         err := vs.createManifest(vs.dirname, vs.manifestFileNum, vs.minUnflushedLogNum, vs.nextFileNum.Load(), nil /* virtualBackings */)
     192            1 :         if err == nil {
     193            1 :                 if err = vs.manifest.Flush(); err != nil {
     194            1 :                         vs.opts.Logger.Fatalf("MANIFEST flush failed: %v", err)
     195            1 :                 }
     196              :         }
     197            1 :         if err == nil {
     198            1 :                 if err = vs.manifestFile.Sync(); err != nil {
     199            1 :                         vs.opts.Logger.Fatalf("MANIFEST sync failed: %v", err)
     200            1 :                 }
     201              :         }
     202            1 :         if err == nil {
     203            1 :                 // NB: Move() is responsible for syncing the data directory.
     204            1 :                 if err = vs.manifestMarker.Move(base.MakeFilename(base.FileTypeManifest, vs.manifestFileNum)); err != nil {
     205            1 :                         vs.opts.Logger.Fatalf("MANIFEST set current failed: %v", err)
     206            1 :                 }
     207              :         }
     208              : 
     209            1 :         vs.opts.EventListener.ManifestCreated(ManifestCreateInfo{
     210            1 :                 JobID:   int(jobID),
     211            1 :                 Path:    base.MakeFilepath(vs.fs, vs.dirname, base.FileTypeManifest, vs.manifestFileNum),
     212            1 :                 FileNum: vs.manifestFileNum,
     213            1 :                 Err:     err,
     214            1 :         })
     215            1 :         if err != nil {
     216            1 :                 return err
     217            1 :         }
     218            1 :         return nil
     219              : }
     220              : 
     221              : // load loads the version set from the manifest file.
     222              : func (vs *versionSet) load(
     223              :         dirname string,
     224              :         provider objstorage.Provider,
     225              :         opts *Options,
     226              :         manifestFileNum base.DiskFileNum,
     227              :         marker *atomicfs.Marker,
     228              :         getFormatMajorVersion func() FormatMajorVersion,
     229              :         blobRewriteHeuristic manifest.BlobRewriteHeuristic,
     230              :         mu *sync.Mutex,
     231            1 : ) error {
     232            1 :         vs.init(dirname, provider, opts, marker, getFormatMajorVersion, mu)
     233            1 : 
     234            1 :         vs.manifestFileNum = manifestFileNum
     235            1 :         manifestPath := base.MakeFilepath(opts.FS, dirname, base.FileTypeManifest, vs.manifestFileNum)
     236            1 :         manifestFilename := opts.FS.PathBase(manifestPath)
     237            1 : 
     238            1 :         // Read the versionEdits in the manifest file.
     239            1 :         var bve manifest.BulkVersionEdit
     240            1 :         bve.AllAddedTables = make(map[base.TableNum]*manifest.TableMetadata)
     241            1 :         manifestFile, err := vs.fs.Open(manifestPath)
     242            1 :         if err != nil {
     243            0 :                 return errors.Wrapf(err, "pebble: could not open manifest file %q for DB %q",
     244            0 :                         errors.Safe(manifestFilename), dirname)
     245            0 :         }
     246            1 :         defer manifestFile.Close()
     247            1 :         rr := record.NewReader(manifestFile, 0 /* logNum */)
     248            1 :         for {
     249            1 :                 r, err := rr.Next()
     250            1 :                 if err == io.EOF || record.IsInvalidRecord(err) {
     251            1 :                         break
     252              :                 }
     253            1 :                 if err != nil {
     254            0 :                         return errors.Wrapf(err, "pebble: error when loading manifest file %q",
     255            0 :                                 errors.Safe(manifestFilename))
     256            0 :                 }
     257            1 :                 var ve manifest.VersionEdit
     258            1 :                 err = ve.Decode(r)
     259            1 :                 if err != nil {
     260            0 :                         // Break instead of returning an error if the record is corrupted
     261            0 :                         // or invalid.
     262            0 :                         if err == io.EOF || record.IsInvalidRecord(err) {
     263            0 :                                 break
     264              :                         }
     265            0 :                         return err
     266              :                 }
     267            1 :                 if ve.ComparerName != "" {
     268            1 :                         if ve.ComparerName != vs.cmp.Name {
     269            1 :                                 return errors.Errorf("pebble: manifest file %q for DB %q: "+
     270            1 :                                         "comparer name from file %q != comparer name from Options %q",
     271            1 :                                         errors.Safe(manifestFilename), dirname, errors.Safe(ve.ComparerName), errors.Safe(vs.cmp.Name))
     272            1 :                         }
     273              :                 }
     274            1 :                 if err := bve.Accumulate(&ve); err != nil {
     275            0 :                         return err
     276            0 :                 }
     277            1 :                 if ve.MinUnflushedLogNum != 0 {
     278            1 :                         vs.minUnflushedLogNum = ve.MinUnflushedLogNum
     279            1 :                 }
     280            1 :                 if ve.NextFileNum != 0 {
     281            1 :                         vs.nextFileNum.Store(ve.NextFileNum)
     282            1 :                 }
     283            1 :                 if ve.LastSeqNum != 0 {
     284            1 :                         // logSeqNum is the _next_ sequence number that will be assigned,
     285            1 :                         // while LastSeqNum is the last assigned sequence number. Note that
     286            1 :                         // this behaviour mimics that in RocksDB; the first sequence number
     287            1 :                         // assigned is one greater than the one present in the manifest
     288            1 :                         // (assuming no WALs contain higher sequence numbers than the
     289            1 :                         // manifest's LastSeqNum). Increment LastSeqNum by 1 to get the
     290            1 :                         // next sequence number that will be assigned.
     291            1 :                         //
     292            1 :                         // If LastSeqNum is less than SeqNumStart, increase it to at least
     293            1 :                         // SeqNumStart to leave ample room for reserved sequence numbers.
     294            1 :                         if ve.LastSeqNum+1 < base.SeqNumStart {
     295            0 :                                 vs.logSeqNum.Store(base.SeqNumStart)
     296            1 :                         } else {
     297            1 :                                 vs.logSeqNum.Store(ve.LastSeqNum + 1)
     298            1 :                         }
     299              :                 }
     300              :         }
     301              :         // We have already set vs.nextFileNum = 2 at the beginning of the
     302              :         // function and could have only updated it to some other non-zero value,
     303              :         // so it cannot be 0 here.
     304            1 :         if vs.minUnflushedLogNum == 0 {
     305            1 :                 if vs.nextFileNum.Load() >= 2 {
     306            1 :                         // We either have a freshly created DB, or a DB created by RocksDB
     307            1 :                         // that has not had a single flushed SSTable yet. This is because
     308            1 :                         // RocksDB bumps up nextFileNum in this case without bumping up
     309            1 :                         // minUnflushedLogNum, even if WALs with non-zero file numbers are
     310            1 :                         // present in the directory.
     311            1 :                 } else {
     312            0 :                         return base.CorruptionErrorf("pebble: malformed manifest file %q for DB %q",
     313            0 :                                 errors.Safe(manifestFilename), dirname)
     314            0 :                 }
     315              :         }
     316            1 :         vs.markFileNumUsed(vs.minUnflushedLogNum)
     317            1 : 
     318            1 :         // Populate the virtual backings for virtual sstables since we have finished
     319            1 :         // version edit accumulation.
     320            1 :         for _, b := range bve.AddedFileBacking {
     321            1 :                 isLocal := objstorage.IsLocalTable(provider, b.DiskFileNum)
     322            1 :                 vs.latest.virtualBackings.AddAndRef(b, isLocal)
     323            1 :         }
     324              : 
     325            1 :         for l, addedLevel := range bve.AddedTables {
     326            1 :                 for _, m := range addedLevel {
     327            1 :                         if m.Virtual {
     328            1 :                                 vs.latest.virtualBackings.AddTable(m, l)
     329            1 :                         }
     330              :                 }
     331              :         }
     332              : 
     333            1 :         if invariants.Enabled {
     334            1 :                 // There should be no deleted tables or backings, since we're starting from
     335            1 :                 // an empty state.
     336            1 :                 for _, deletedLevel := range bve.DeletedTables {
     337            1 :                         if len(deletedLevel) != 0 {
     338            0 :                                 panic("deleted files after manifest replay")
     339              :                         }
     340              :                 }
     341            1 :                 if len(bve.RemovedFileBacking) > 0 {
     342            0 :                         panic("deleted backings after manifest replay")
     343              :                 }
     344              :         }
     345              : 
     346            1 :         emptyVersion := manifest.NewInitialVersion(opts.Comparer)
     347            1 :         newVersion, err := bve.Apply(emptyVersion, opts.Experimental.ReadCompactionRate)
     348            1 :         if err != nil {
     349            0 :                 return err
     350            0 :         }
     351            1 :         vs.latest.l0Organizer.PerformUpdate(vs.latest.l0Organizer.PrepareUpdate(&bve, newVersion), newVersion)
     352            1 :         vs.latest.l0Organizer.InitCompactingFileInfo(nil /* in-progress compactions */)
     353            1 :         vs.latest.blobFiles.Init(&bve, blobRewriteHeuristic)
     354            1 :         vs.append(newVersion)
     355            1 : 
     356            1 :         for i := range vs.metrics.Levels {
     357            1 :                 l := &vs.metrics.Levels[i]
     358            1 :                 l.TablesCount = int64(newVersion.Levels[i].Len())
     359            1 :                 files := newVersion.Levels[i].Slice()
     360            1 :                 l.TablesSize = int64(files.TableSizeSum())
     361            1 :         }
     362            1 :         for _, l := range newVersion.Levels {
     363            1 :                 for f := range l.All() {
     364            1 :                         if !f.Virtual {
     365            1 :                                 isLocal, localSize := sizeIfLocal(f.TableBacking, vs.provider)
     366            1 :                                 vs.metrics.Table.Local.LiveSize = uint64(int64(vs.metrics.Table.Local.LiveSize) + localSize)
     367            1 :                                 if isLocal {
     368            1 :                                         vs.metrics.Table.Local.LiveCount++
     369            1 :                                 }
     370              :                         }
     371              :                 }
     372              :         }
     373            1 :         for backing := range vs.latest.virtualBackings.All() {
     374            1 :                 isLocal, localSize := sizeIfLocal(backing, vs.provider)
     375            1 :                 vs.metrics.Table.Local.LiveSize = uint64(int64(vs.metrics.Table.Local.LiveSize) + localSize)
     376            1 :                 if isLocal {
     377            1 :                         vs.metrics.Table.Local.LiveCount++
     378            1 :                 }
     379              :         }
     380              : 
     381            1 :         vs.setCompactionPicker(newCompactionPickerByScore(newVersion, &vs.latest, vs.opts, nil))
     382            1 :         return nil
     383              : }
     384              : 
     385            1 : func (vs *versionSet) close() error {
     386            1 :         if vs.manifestFile != nil {
     387            1 :                 if err := vs.manifestFile.Close(); err != nil {
     388            0 :                         return err
     389            0 :                 }
     390              :         }
     391            1 :         if vs.manifestMarker != nil {
     392            1 :                 if err := vs.manifestMarker.Close(); err != nil {
     393            0 :                         return err
     394            0 :                 }
     395              :         }
     396            1 :         return nil
     397              : }
     398              : 
     399              : // logLock locks the manifest for writing. The lock must be released by
     400              : // a call to logUnlock.
     401              : //
     402              : // DB.mu must be held when calling this method, but the mutex may be dropped and
     403              : // re-acquired during the course of this method.
     404            1 : func (vs *versionSet) logLock() {
     405            1 :         // Wait for any existing writing to the manifest to complete, then mark the
     406            1 :         // manifest as busy.
     407            1 :         for vs.writing {
     408            1 :                 // Note: writerCond.L is DB.mu, so we unlock it while we wait.
     409            1 :                 vs.writerCond.Wait()
     410            1 :         }
     411            1 :         vs.writing = true
     412              : }
     413              : 
     414              : // logUnlock releases the lock for manifest writing.
     415              : //
     416              : // DB.mu must be held when calling this method.
     417            1 : func (vs *versionSet) logUnlock() {
     418            1 :         if !vs.writing {
     419            0 :                 vs.opts.Logger.Fatalf("MANIFEST not locked for writing")
     420            0 :         }
     421            1 :         vs.writing = false
     422            1 :         vs.writerCond.Signal()
     423              : }
     424              : 
     425            1 : func (vs *versionSet) logUnlockAndInvalidatePickedCompactionCache() {
     426            1 :         vs.pickedCompactionCache.invalidate()
     427            1 :         vs.logUnlock()
     428            1 : }
     429              : 
     430              : // versionUpdate is returned by the function passed to UpdateVersionLocked.
     431              : //
     432              : // If VE is nil, there is no update to apply (but it is not an error).
     433              : type versionUpdate struct {
     434              :         VE      *manifest.VersionEdit
     435              :         JobID   JobID
     436              :         Metrics levelMetricsDelta
     437              :         // InProgressCompactionFn is called while DB.mu is held after the I/O part of
     438              :         // the update was performed. It should return any compactions that are
     439              :         // in-progress (excluding than the one that is being applied).
     440              :         InProgressCompactionsFn func() []compactionInfo
     441              :         ForceManifestRotation   bool
     442              : }
     443              : 
     444              : // UpdateVersionLocked is used to update the current version, returning the
     445              : // duration of the manifest update. If the manifest update is unsuccessful, the
     446              : // duration will be unset (0).
     447              : //
     448              : // DB.mu must be held. UpdateVersionLocked first waits for any other version
     449              : // update to complete, releasing and reacquiring DB.mu.
     450              : //
     451              : // UpdateVersionLocked then calls updateFn which builds a versionUpdate, while
     452              : // holding DB.mu. The updateFn can release and reacquire DB.mu (it should
     453              : // attempt to do as much work as possible outside of the lock).
     454              : //
     455              : // UpdateVersionLocked fills in the following fields of the VersionEdit:
     456              : // NextFileNum, LastSeqNum, RemovedBackingTables. The removed backing tables are
     457              : // those backings that are no longer used (in the new version) after applying
     458              : // the edit (as per vs.virtualBackings). Other than these fields, the
     459              : // VersionEdit must be complete.
     460              : //
     461              : // New table backing references (TableBacking.Ref) are taken as part of applying
     462              : // the version edit. The state of the virtual backings (vs.virtualBackings) is
     463              : // updated before logging to the manifest and installing the latest version;
     464              : // this is ok because any failure in those steps is fatal.
     465              : //
     466              : // If updateFn returns an error, no update is applied and that same error is returned.
     467              : // If versionUpdate.VE is nil, the no update is applied (and no error is returned).
     468              : func (vs *versionSet) UpdateVersionLocked(
     469              :         updateFn func() (versionUpdate, error),
     470            1 : ) (time.Duration, error) {
     471            1 :         vs.logLock()
     472            1 :         defer vs.logUnlockAndInvalidatePickedCompactionCache()
     473            1 : 
     474            1 :         vu, err := updateFn()
     475            1 :         if err != nil || vu.VE == nil {
     476            1 :                 return 0, err
     477            1 :         }
     478              : 
     479            1 :         if !vs.writing {
     480            0 :                 vs.opts.Logger.Fatalf("MANIFEST not locked for writing")
     481            0 :         }
     482              : 
     483            1 :         updateManifestStart := crtime.NowMono()
     484            1 :         ve := vu.VE
     485            1 :         if ve.MinUnflushedLogNum != 0 {
     486            1 :                 if ve.MinUnflushedLogNum < vs.minUnflushedLogNum ||
     487            1 :                         vs.nextFileNum.Load() <= uint64(ve.MinUnflushedLogNum) {
     488            0 :                         panic(fmt.Sprintf("pebble: inconsistent versionEdit minUnflushedLogNum %d",
     489            0 :                                 ve.MinUnflushedLogNum))
     490              :                 }
     491              :         }
     492              : 
     493              :         // This is the next manifest filenum, but if the current file is too big we
     494              :         // will write this ve to the next file which means what ve encodes is the
     495              :         // current filenum and not the next one.
     496              :         //
     497              :         // TODO(sbhola): figure out why this is correct and update comment.
     498            1 :         ve.NextFileNum = vs.nextFileNum.Load()
     499            1 : 
     500            1 :         // LastSeqNum is set to the current upper bound on the assigned sequence
     501            1 :         // numbers. Note that this is exactly the behavior of RocksDB. LastSeqNum is
     502            1 :         // used to initialize versionSet.logSeqNum and versionSet.visibleSeqNum on
     503            1 :         // replay. It must be higher than or equal to any than any sequence number
     504            1 :         // written to an sstable, including sequence numbers in ingested files.
     505            1 :         // Note that LastSeqNum is not (and cannot be) the minimum unflushed sequence
     506            1 :         // number. This is fallout from ingestion which allows a sequence number X to
     507            1 :         // be assigned to an ingested sstable even though sequence number X-1 resides
     508            1 :         // in an unflushed memtable. logSeqNum is the _next_ sequence number that
     509            1 :         // will be assigned, so subtract that by 1 to get the upper bound on the
     510            1 :         // last assigned sequence number.
     511            1 :         logSeqNum := vs.logSeqNum.Load()
     512            1 :         ve.LastSeqNum = logSeqNum - 1
     513            1 :         if logSeqNum == 0 {
     514            0 :                 // logSeqNum is initialized to 1 in Open() if there are no previous WAL
     515            0 :                 // or manifest records, so this case should never happen.
     516            0 :                 vs.opts.Logger.Fatalf("logSeqNum must be a positive integer: %d", logSeqNum)
     517            0 :         }
     518              : 
     519            1 :         currentVersion := vs.currentVersion()
     520            1 :         var newVersion *manifest.Version
     521            1 : 
     522            1 :         // Generate a new manifest if we don't currently have one, or forceRotation
     523            1 :         // is true, or the current one is too large.
     524            1 :         //
     525            1 :         // For largeness, we do not exclusively use MaxManifestFileSize size
     526            1 :         // threshold since we have had incidents where due to either large keys or
     527            1 :         // large numbers of files, each edit results in a snapshot + write of the
     528            1 :         // edit. This slows the system down since each flush or compaction is
     529            1 :         // writing a new manifest snapshot. The primary goal of the size-based
     530            1 :         // rollover logic is to ensure that when reopening a DB, the number of edits
     531            1 :         // that need to be replayed on top of the snapshot is "sane". Rolling over
     532            1 :         // to a new manifest after each edit is not relevant to that goal.
     533            1 :         //
     534            1 :         // Consider the following cases:
     535            1 :         // - The number of live files F in the DB is roughly stable: after writing
     536            1 :         //   the snapshot (with F files), say we require that there be enough edits
     537            1 :         //   such that the cumulative number of files in those edits, E, be greater
     538            1 :         //   than F. This will ensure that the total amount of time in
     539            1 :         //   UpdateVersionLocked that is spent in snapshot writing is ~50%.
     540            1 :         //
     541            1 :         // - The number of live files F in the DB is shrinking drastically, say from
     542            1 :         //   F to F/10: This can happen for various reasons, like wide range
     543            1 :         //   tombstones, or large numbers of smaller than usual files that are being
     544            1 :         //   merged together into larger files. And say the new files generated
     545            1 :         //   during this shrinkage is insignificant compared to F/10, and so for
     546            1 :         //   this example we will assume it is effectively 0. After this shrinking,
     547            1 :         //   E = 0.9F, and so if we used the previous snapshot file count, F, as the
     548            1 :         //   threshold that needs to be exceeded, we will further delay the snapshot
     549            1 :         //   writing. Which means on DB reopen we will need to replay 0.9F edits to
     550            1 :         //   get to a version with 0.1F files. It would be better to create a new
     551            1 :         //   snapshot when E exceeds the number of files in the current version.
     552            1 :         //
     553            1 :         // - The number of live files F in the DB is growing via perfect ingests
     554            1 :         //   into L6: Say we wrote the snapshot when there were F files and now we
     555            1 :         //   have 10F files, so E = 9F. We will further delay writing a new
     556            1 :         //   snapshot. This case can be critiqued as contrived, but we consider it
     557            1 :         //   nonetheless.
     558            1 :         //
     559            1 :         // The logic below uses the min of the last snapshot file count and the file
     560            1 :         // count in the current version.
     561            1 :         vs.rotationHelper.AddRecord(int64(len(ve.DeletedTables) + len(ve.NewTables)))
     562            1 :         sizeExceeded := vs.manifest.Size() >= vs.opts.MaxManifestFileSize
     563            1 :         requireRotation := vu.ForceManifestRotation || vs.manifest == nil
     564            1 : 
     565            1 :         var nextSnapshotFilecount int64
     566            1 :         for i := range vs.metrics.Levels {
     567            1 :                 nextSnapshotFilecount += vs.metrics.Levels[i].TablesCount
     568            1 :         }
     569            1 :         if sizeExceeded && !requireRotation {
     570            1 :                 requireRotation = vs.rotationHelper.ShouldRotate(nextSnapshotFilecount)
     571            1 :         }
     572            1 :         var newManifestFileNum base.DiskFileNum
     573            1 :         var prevManifestFileSize uint64
     574            1 :         var newManifestVirtualBackings []*manifest.TableBacking
     575            1 :         if requireRotation {
     576            1 :                 newManifestFileNum = vs.getNextDiskFileNum()
     577            1 :                 prevManifestFileSize = uint64(vs.manifest.Size())
     578            1 : 
     579            1 :                 // We want the virtual backings *before* applying the version edit, because
     580            1 :                 // the new manifest will contain the pre-apply version plus the last version
     581            1 :                 // edit.
     582            1 :                 newManifestVirtualBackings = slices.Collect(vs.latest.virtualBackings.All())
     583            1 :         }
     584              : 
     585              :         // Grab certain values before releasing vs.mu, in case createManifest() needs
     586              :         // to be called.
     587            1 :         minUnflushedLogNum := vs.minUnflushedLogNum
     588            1 :         nextFileNum := vs.nextFileNum.Load()
     589            1 : 
     590            1 :         // Note: this call populates ve.RemovedBackingTables.
     591            1 :         zombieBackings, removedVirtualBackings, localTablesLiveDelta :=
     592            1 :                 getZombieTablesAndUpdateVirtualBackings(ve, &vs.latest.virtualBackings, vs.provider)
     593            1 : 
     594            1 :         var l0Update manifest.L0PreparedUpdate
     595            1 :         if err := func() error {
     596            1 :                 vs.mu.Unlock()
     597            1 :                 defer vs.mu.Lock()
     598            1 : 
     599            1 :                 if vs.getFormatMajorVersion() < FormatVirtualSSTables && len(ve.CreatedBackingTables) > 0 {
     600            0 :                         return base.AssertionFailedf("MANIFEST cannot contain virtual sstable records due to format major version")
     601            0 :                 }
     602              : 
     603              :                 // Rotate the manifest if necessary. Rotating the manifest involves
     604              :                 // creating a new file and writing an initial version edit containing a
     605              :                 // snapshot of the current version. This initial version edit will
     606              :                 // reflect the Version prior to the pending version edit (`ve`). Once
     607              :                 // we've created the new manifest with the previous version state, we'll
     608              :                 // append the version edit `ve` to the tail of the new manifest.
     609            1 :                 if newManifestFileNum != 0 {
     610            1 :                         if err := vs.createManifest(vs.dirname, newManifestFileNum, minUnflushedLogNum, nextFileNum, newManifestVirtualBackings); err != nil {
     611            1 :                                 vs.opts.EventListener.ManifestCreated(ManifestCreateInfo{
     612            1 :                                         JobID:   int(vu.JobID),
     613            1 :                                         Path:    base.MakeFilepath(vs.fs, vs.dirname, base.FileTypeManifest, newManifestFileNum),
     614            1 :                                         FileNum: newManifestFileNum,
     615            1 :                                         Err:     err,
     616            1 :                                 })
     617            1 :                                 return errors.Wrap(err, "MANIFEST create failed")
     618            1 :                         }
     619              :                 }
     620              : 
     621              :                 // Call ApplyAndUpdateVersionEdit before accumulating the version edit.
     622              :                 // If any blob files are no longer referenced, the version edit will be
     623              :                 // updated to explicitly record the deletion of the blob files. This can
     624              :                 // happen here because vs.blobFiles is protected by the manifest logLock
     625              :                 // (NOT vs.mu). We only read or write vs.blobFiles while holding the
     626              :                 // manifest lock.
     627            1 :                 if err := vs.latest.blobFiles.ApplyAndUpdateVersionEdit(ve); err != nil {
     628            0 :                         return errors.Wrap(err, "MANIFEST blob files apply and update failed")
     629            0 :                 }
     630              : 
     631            1 :                 var bulkEdit manifest.BulkVersionEdit
     632            1 :                 err := bulkEdit.Accumulate(ve)
     633            1 :                 if err != nil {
     634            0 :                         return errors.Wrap(err, "MANIFEST accumulate failed")
     635            0 :                 }
     636            1 :                 newVersion, err = bulkEdit.Apply(currentVersion, vs.opts.Experimental.ReadCompactionRate)
     637            1 :                 if err != nil {
     638            0 :                         return errors.Wrap(err, "MANIFEST apply failed")
     639            0 :                 }
     640            1 :                 l0Update = vs.latest.l0Organizer.PrepareUpdate(&bulkEdit, newVersion)
     641            1 : 
     642            1 :                 w, err := vs.manifest.Next()
     643            1 :                 if err != nil {
     644            0 :                         return errors.Wrap(err, "MANIFEST next record write failed")
     645            0 :                 }
     646              : 
     647              :                 // NB: Any error from this point on is considered fatal as we don't know if
     648              :                 // the MANIFEST write occurred or not. Trying to determine that is
     649              :                 // fraught. Instead we rely on the standard recovery mechanism run when a
     650              :                 // database is open. In particular, that mechanism generates a new MANIFEST
     651              :                 // and ensures it is synced.
     652            1 :                 if err := ve.Encode(w); err != nil {
     653            0 :                         return errors.Wrap(err, "MANIFEST write failed")
     654            0 :                 }
     655            1 :                 if err := vs.manifest.Flush(); err != nil {
     656            1 :                         return errors.Wrap(err, "MANIFEST flush failed")
     657            1 :                 }
     658            1 :                 if err := vs.manifestFile.Sync(); err != nil {
     659            1 :                         return errors.Wrap(err, "MANIFEST sync failed")
     660            1 :                 }
     661            1 :                 if newManifestFileNum != 0 {
     662            1 :                         // NB: Move() is responsible for syncing the data directory.
     663            1 :                         if err := vs.manifestMarker.Move(base.MakeFilename(base.FileTypeManifest, newManifestFileNum)); err != nil {
     664            0 :                                 return errors.Wrap(err, "MANIFEST set current failed")
     665            0 :                         }
     666            1 :                         vs.opts.EventListener.ManifestCreated(ManifestCreateInfo{
     667            1 :                                 JobID:   int(vu.JobID),
     668            1 :                                 Path:    base.MakeFilepath(vs.fs, vs.dirname, base.FileTypeManifest, newManifestFileNum),
     669            1 :                                 FileNum: newManifestFileNum,
     670            1 :                         })
     671              :                 }
     672            1 :                 return nil
     673            1 :         }(); err != nil {
     674            1 :                 // Any error encountered during any of the operations in the previous
     675            1 :                 // closure are considered fatal. Treating such errors as fatal is preferred
     676            1 :                 // to attempting to unwind various file and b-tree reference counts, and
     677            1 :                 // re-generating L0 sublevel metadata. This may change in the future, if
     678            1 :                 // certain manifest / WAL operations become retryable. For more context, see
     679            1 :                 // #1159 and #1792.
     680            1 :                 vs.opts.Logger.Fatalf("%s", err)
     681            1 :                 return 0, err
     682            1 :         }
     683              : 
     684            1 :         if requireRotation {
     685            1 :                 // Successfully rotated.
     686            1 :                 vs.rotationHelper.Rotate(nextSnapshotFilecount)
     687            1 :         }
     688              :         // Now that DB.mu is held again, initialize compacting file info in
     689              :         // L0Sublevels.
     690            1 :         inProgress := vu.InProgressCompactionsFn()
     691            1 : 
     692            1 :         zombieBlobs, localBlobLiveDelta := getZombieBlobFilesAndComputeLocalMetrics(ve, vs.provider)
     693            1 :         vs.latest.l0Organizer.PerformUpdate(l0Update, newVersion)
     694            1 :         vs.latest.l0Organizer.InitCompactingFileInfo(inProgressL0Compactions(inProgress))
     695            1 : 
     696            1 :         // Update the zombie objects sets first, as installation of the new version
     697            1 :         // will unref the previous version which could result in addObsoleteLocked
     698            1 :         // being called.
     699            1 :         for _, b := range zombieBackings {
     700            1 :                 vs.zombieTables.Add(objectInfo{
     701            1 :                         fileInfo: fileInfo{
     702            1 :                                 FileNum:  b.backing.DiskFileNum,
     703            1 :                                 FileSize: b.backing.Size,
     704            1 :                         },
     705            1 :                         isLocal: b.isLocal,
     706            1 :                 })
     707            1 :         }
     708            1 :         for _, zb := range zombieBlobs {
     709            1 :                 vs.zombieBlobs.Add(zb)
     710            1 :         }
     711              :         // Unref the removed backings and report those that already became obsolete.
     712              :         // Note that the only case where we report obsolete tables here is when
     713              :         // VirtualBackings.Protect/Unprotect was used to keep a backing alive without
     714              :         // it being used in the current version.
     715            1 :         var obsoleteVirtualBackings manifest.ObsoleteFiles
     716            1 :         for _, b := range removedVirtualBackings {
     717            1 :                 if b.backing.Unref() == 0 {
     718            1 :                         obsoleteVirtualBackings.TableBackings = append(obsoleteVirtualBackings.TableBackings, b.backing)
     719            1 :                 }
     720              :         }
     721            1 :         vs.addObsoleteLocked(obsoleteVirtualBackings)
     722            1 : 
     723            1 :         // Install the new version.
     724            1 :         vs.append(newVersion)
     725            1 : 
     726            1 :         if ve.MinUnflushedLogNum != 0 {
     727            1 :                 vs.minUnflushedLogNum = ve.MinUnflushedLogNum
     728            1 :         }
     729            1 :         if newManifestFileNum != 0 {
     730            1 :                 if vs.manifestFileNum != 0 {
     731            1 :                         vs.obsoleteManifests = append(vs.obsoleteManifests, obsoleteFile{
     732            1 :                                 fileType: base.FileTypeManifest,
     733            1 :                                 fs:       vs.fs,
     734            1 :                                 path:     base.MakeFilepath(vs.fs, vs.dirname, base.FileTypeManifest, vs.manifestFileNum),
     735            1 :                                 fileNum:  vs.manifestFileNum,
     736            1 :                                 fileSize: prevManifestFileSize,
     737            1 :                                 isLocal:  true,
     738            1 :                         })
     739            1 :                 }
     740            1 :                 vs.manifestFileNum = newManifestFileNum
     741              :         }
     742              : 
     743            1 :         vs.metrics.updateLevelMetrics(vu.Metrics)
     744            1 :         for i := range vs.metrics.Levels {
     745            1 :                 l := &vs.metrics.Levels[i]
     746            1 :                 l.TablesCount = int64(newVersion.Levels[i].Len())
     747            1 :                 l.VirtualTablesCount = newVersion.Levels[i].NumVirtual
     748            1 :                 l.VirtualTablesSize = newVersion.Levels[i].VirtualTableSize
     749            1 :                 l.TablesSize = int64(newVersion.Levels[i].TableSize())
     750            1 :                 l.EstimatedReferencesSize = newVersion.Levels[i].EstimatedReferenceSize()
     751            1 :                 l.Sublevels = 0
     752            1 :                 if l.TablesCount > 0 {
     753            1 :                         l.Sublevels = 1
     754            1 :                 }
     755            1 :                 if invariants.Enabled {
     756            1 :                         levelFiles := newVersion.Levels[i].Slice()
     757            1 :                         if size := int64(levelFiles.TableSizeSum()); l.TablesSize != size {
     758            0 :                                 vs.opts.Logger.Fatalf("versionSet metrics L%d Size = %d, actual size = %d", i, l.TablesSize, size)
     759            0 :                         }
     760            1 :                         refSize := uint64(0)
     761            1 :                         for f := range levelFiles.All() {
     762            1 :                                 refSize += f.EstimatedReferenceSize()
     763            1 :                         }
     764            1 :                         if refSize != l.EstimatedReferencesSize {
     765            0 :                                 vs.opts.Logger.Fatalf("versionSet metrics L%d EstimatedReferencesSize = %d, recomputed size = %d", i, l.EstimatedReferencesSize, refSize)
     766            0 :                         }
     767              : 
     768            1 :                         if nVirtual := levelFiles.NumVirtual(); nVirtual != l.VirtualTablesCount {
     769            0 :                                 vs.opts.Logger.Fatalf(
     770            0 :                                         "versionSet metrics L%d NumVirtual = %d, actual NumVirtual = %d",
     771            0 :                                         i, l.VirtualTablesCount, nVirtual,
     772            0 :                                 )
     773            0 :                         }
     774            1 :                         if vSize := levelFiles.VirtualTableSizeSum(); vSize != l.VirtualTablesSize {
     775            0 :                                 vs.opts.Logger.Fatalf(
     776            0 :                                         "versionSet metrics L%d Virtual size = %d, actual size = %d",
     777            0 :                                         i, l.VirtualTablesSize, vSize,
     778            0 :                                 )
     779            0 :                         }
     780              :                 }
     781              :         }
     782            1 :         vs.metrics.Levels[0].Sublevels = int32(len(newVersion.L0SublevelFiles))
     783            1 :         vs.metrics.Table.Local.LiveSize = uint64(int64(vs.metrics.Table.Local.LiveSize) + localTablesLiveDelta.size)
     784            1 :         vs.metrics.Table.Local.LiveCount = uint64(int64(vs.metrics.Table.Local.LiveCount) + localTablesLiveDelta.count)
     785            1 :         vs.metrics.BlobFiles.Local.LiveSize = uint64(int64(vs.metrics.BlobFiles.Local.LiveSize) + localBlobLiveDelta.size)
     786            1 :         vs.metrics.BlobFiles.Local.LiveCount = uint64(int64(vs.metrics.BlobFiles.Local.LiveCount) + localBlobLiveDelta.count)
     787            1 : 
     788            1 :         vs.setCompactionPicker(newCompactionPickerByScore(newVersion, &vs.latest, vs.opts, inProgress))
     789            1 :         if !vs.dynamicBaseLevel {
     790            1 :                 vs.picker.forceBaseLevel1()
     791            1 :         }
     792              : 
     793            1 :         return updateManifestStart.Elapsed(), nil
     794              : }
     795              : 
     796            1 : func (vs *versionSet) setCompactionPicker(picker *compactionPickerByScore) {
     797            1 :         vs.picker = picker
     798            1 :         vs.curCompactionConcurrency.Store(int32(picker.getCompactionConcurrency()))
     799            1 : }
     800              : 
     801              : type tableBackingInfo struct {
     802              :         backing *manifest.TableBacking
     803              :         isLocal bool
     804              : }
     805              : 
     806              : type fileMetricDelta struct {
     807              :         count int64
     808              :         size  int64
     809              : }
     810              : 
     811              : // getZombieTablesAndUpdateVirtualBackings updates the virtual backings with the
     812              : // changes in the versionEdit and populates ve.RemovedBackingTables.
     813              : // Returns:
     814              : //   - zombieBackings: all backings (physical and virtual) that will no longer be
     815              : //     needed when we apply ve.
     816              : //   - removedVirtualBackings: the virtual backings that will be removed by the
     817              : //     VersionEdit and which must be Unref()ed by the caller. These backings
     818              : //     match ve.RemovedBackingTables.
     819              : //   - localLiveSizeDelta: the delta in local live bytes.
     820              : func getZombieTablesAndUpdateVirtualBackings(
     821              :         ve *manifest.VersionEdit, virtualBackings *manifest.VirtualBackings, provider objstorage.Provider,
     822            1 : ) (zombieBackings, removedVirtualBackings []tableBackingInfo, localLiveDelta fileMetricDelta) {
     823            1 :         // First, deal with the physical tables.
     824            1 :         //
     825            1 :         // A physical backing has become unused if it is in DeletedFiles but not in
     826            1 :         // NewFiles or CreatedBackingTables.
     827            1 :         //
     828            1 :         // Note that for the common case where there are very few elements, the map
     829            1 :         // will stay on the stack.
     830            1 :         stillUsed := make(map[base.DiskFileNum]struct{})
     831            1 :         for _, nf := range ve.NewTables {
     832            1 :                 if !nf.Meta.Virtual {
     833            1 :                         stillUsed[nf.Meta.TableBacking.DiskFileNum] = struct{}{}
     834            1 :                         isLocal, localFileDelta := sizeIfLocal(nf.Meta.TableBacking, provider)
     835            1 :                         localLiveDelta.size += localFileDelta
     836            1 :                         if isLocal {
     837            1 :                                 localLiveDelta.count++
     838            1 :                         }
     839              :                 }
     840              :         }
     841            1 :         for _, b := range ve.CreatedBackingTables {
     842            1 :                 stillUsed[b.DiskFileNum] = struct{}{}
     843            1 :         }
     844            1 :         for _, m := range ve.DeletedTables {
     845            1 :                 if !m.Virtual {
     846            1 :                         // NB: this deleted file may also be in NewFiles or
     847            1 :                         // CreatedBackingTables, due to a file moving between levels, or
     848            1 :                         // becoming virtualized. In which case there is no change due to this
     849            1 :                         // file in the localLiveSizeDelta -- the subtraction below compensates
     850            1 :                         // for the addition.
     851            1 :                         isLocal, localFileDelta := sizeIfLocal(m.TableBacking, provider)
     852            1 :                         localLiveDelta.size -= localFileDelta
     853            1 :                         if isLocal {
     854            1 :                                 localLiveDelta.count--
     855            1 :                         }
     856            1 :                         if _, ok := stillUsed[m.TableBacking.DiskFileNum]; !ok {
     857            1 :                                 zombieBackings = append(zombieBackings, tableBackingInfo{
     858            1 :                                         backing: m.TableBacking,
     859            1 :                                         isLocal: isLocal,
     860            1 :                                 })
     861            1 :                         }
     862              :                 }
     863              :         }
     864              : 
     865              :         // Now deal with virtual tables.
     866              :         //
     867              :         // When a virtual table moves between levels we RemoveTable() then AddTable(),
     868              :         // which works out.
     869            1 :         for _, b := range ve.CreatedBackingTables {
     870            1 :                 isLocal, localFileDelta := sizeIfLocal(b, provider)
     871            1 :                 virtualBackings.AddAndRef(b, isLocal)
     872            1 :                 localLiveDelta.size += localFileDelta
     873            1 :                 if isLocal {
     874            1 :                         localLiveDelta.count++
     875            1 :                 }
     876              :         }
     877            1 :         for _, m := range ve.DeletedTables {
     878            1 :                 if m.Virtual {
     879            1 :                         virtualBackings.RemoveTable(m.TableBacking.DiskFileNum, m.TableNum)
     880            1 :                 }
     881              :         }
     882            1 :         for _, nf := range ve.NewTables {
     883            1 :                 if nf.Meta.Virtual {
     884            1 :                         virtualBackings.AddTable(nf.Meta, nf.Level)
     885            1 :                 }
     886              :         }
     887              : 
     888            1 :         if unused := virtualBackings.Unused(); len(unused) > 0 {
     889            1 :                 // Virtual backings that are no longer used are zombies and are also added
     890            1 :                 // to RemovedBackingTables (before the version edit is written to disk).
     891            1 :                 ve.RemovedBackingTables = make([]base.DiskFileNum, len(unused))
     892            1 :                 for i, b := range unused {
     893            1 :                         isLocal, localFileDelta := sizeIfLocal(b, provider)
     894            1 :                         localLiveDelta.size -= localFileDelta
     895            1 :                         if isLocal {
     896            1 :                                 localLiveDelta.count--
     897            1 :                         }
     898            1 :                         ve.RemovedBackingTables[i] = b.DiskFileNum
     899            1 :                         zombieBackings = append(zombieBackings, tableBackingInfo{
     900            1 :                                 backing: b,
     901            1 :                                 isLocal: isLocal,
     902            1 :                         })
     903            1 :                         virtualBackings.Remove(b.DiskFileNum)
     904              :                 }
     905            1 :                 removedVirtualBackings = zombieBackings[len(zombieBackings)-len(unused):]
     906              :         }
     907            1 :         return zombieBackings, removedVirtualBackings, localLiveDelta
     908              : }
     909              : 
     910              : // getZombieBlobFilesAndComputeLocalMetrics constructs objectInfos for all
     911              : // zombie blob files, and computes the metric deltas for live files overall and
     912              : // locally.
     913              : func getZombieBlobFilesAndComputeLocalMetrics(
     914              :         ve *manifest.VersionEdit, provider objstorage.Provider,
     915            1 : ) (zombieBlobFiles []objectInfo, localLiveDelta fileMetricDelta) {
     916            1 :         for _, b := range ve.NewBlobFiles {
     917            1 :                 if objstorage.IsLocalBlobFile(provider, b.Physical.FileNum) {
     918            1 :                         localLiveDelta.count++
     919            1 :                         localLiveDelta.size += int64(b.Physical.Size)
     920            1 :                 }
     921              :         }
     922            1 :         zombieBlobFiles = make([]objectInfo, 0, len(ve.DeletedBlobFiles))
     923            1 :         for _, physical := range ve.DeletedBlobFiles {
     924            1 :                 isLocal := objstorage.IsLocalBlobFile(provider, physical.FileNum)
     925            1 :                 if isLocal {
     926            1 :                         localLiveDelta.count--
     927            1 :                         localLiveDelta.size -= int64(physical.Size)
     928            1 :                 }
     929            1 :                 zombieBlobFiles = append(zombieBlobFiles, objectInfo{
     930            1 :                         fileInfo: fileInfo{
     931            1 :                                 FileNum:  physical.FileNum,
     932            1 :                                 FileSize: physical.Size,
     933            1 :                         },
     934            1 :                         isLocal: isLocal,
     935            1 :                 })
     936              :         }
     937            1 :         return zombieBlobFiles, localLiveDelta
     938              : }
     939              : 
     940              : // sizeIfLocal returns backing.Size if the backing is a local file, else 0.
     941              : func sizeIfLocal(
     942              :         backing *manifest.TableBacking, provider objstorage.Provider,
     943            1 : ) (isLocal bool, localSize int64) {
     944            1 :         isLocal = objstorage.IsLocalTable(provider, backing.DiskFileNum)
     945            1 :         if isLocal {
     946            1 :                 return true, int64(backing.Size)
     947            1 :         }
     948            1 :         return false, 0
     949              : }
     950              : 
     951              : func (vs *versionSet) incrementCompactions(
     952              :         kind compactionKind, extraLevels []*compactionLevel, bytesWritten int64, compactionErr error,
     953            1 : ) {
     954            1 :         if kind == compactionKindFlush || kind == compactionKindIngestedFlushable {
     955            1 :                 vs.metrics.Flush.Count++
     956            1 :         } else {
     957            1 :                 vs.metrics.Compact.Count++
     958            1 :                 if compactionErr != nil {
     959            1 :                         if errors.Is(compactionErr, ErrCancelledCompaction) {
     960            1 :                                 vs.metrics.Compact.CancelledCount++
     961            1 :                                 vs.metrics.Compact.CancelledBytes += bytesWritten
     962            1 :                         } else {
     963            1 :                                 vs.metrics.Compact.FailedCount++
     964            1 :                         }
     965              :                 }
     966              :         }
     967              : 
     968            1 :         switch kind {
     969            1 :         case compactionKindDefault:
     970            1 :                 vs.metrics.Compact.DefaultCount++
     971              : 
     972            1 :         case compactionKindFlush, compactionKindIngestedFlushable:
     973              : 
     974            1 :         case compactionKindMove:
     975            1 :                 vs.metrics.Compact.MoveCount++
     976              : 
     977            1 :         case compactionKindDeleteOnly:
     978            1 :                 vs.metrics.Compact.DeleteOnlyCount++
     979              : 
     980            1 :         case compactionKindElisionOnly:
     981            1 :                 vs.metrics.Compact.ElisionOnlyCount++
     982              : 
     983            1 :         case compactionKindRead:
     984            1 :                 vs.metrics.Compact.ReadCount++
     985              : 
     986            1 :         case compactionKindTombstoneDensity:
     987            1 :                 vs.metrics.Compact.TombstoneDensityCount++
     988              : 
     989            1 :         case compactionKindRewrite:
     990            1 :                 vs.metrics.Compact.RewriteCount++
     991              : 
     992            1 :         case compactionKindCopy:
     993            1 :                 vs.metrics.Compact.CopyCount++
     994              : 
     995            1 :         case compactionKindBlobFileRewrite:
     996            1 :                 vs.metrics.Compact.BlobFileRewriteCount++
     997              : 
     998            1 :         case compactionKindVirtualRewrite:
     999            1 :                 vs.metrics.Compact.VirtualRewriteCount++
    1000              : 
    1001            0 :         default:
    1002            0 :                 if invariants.Enabled {
    1003            0 :                         panic("unhandled compaction kind")
    1004              :                 }
    1005              : 
    1006              :         }
    1007            1 :         if len(extraLevels) > 0 {
    1008            1 :                 vs.metrics.Compact.MultiLevelCount++
    1009            1 :         }
    1010              : }
    1011              : 
    1012            1 : func (vs *versionSet) incrementCompactionBytes(numBytes int64) {
    1013            1 :         vs.atomicInProgressBytes.Add(numBytes)
    1014            1 : }
    1015              : 
    1016              : // createManifest creates a manifest file that contains a snapshot of vs.
    1017              : func (vs *versionSet) createManifest(
    1018              :         dirname string,
    1019              :         fileNum, minUnflushedLogNum base.DiskFileNum,
    1020              :         nextFileNum uint64,
    1021              :         virtualBackings []*manifest.TableBacking,
    1022            1 : ) (err error) {
    1023            1 :         var (
    1024            1 :                 filename       = base.MakeFilepath(vs.fs, dirname, base.FileTypeManifest, fileNum)
    1025            1 :                 manifestFile   vfs.File
    1026            1 :                 manifestWriter *record.Writer
    1027            1 :         )
    1028            1 :         defer func() {
    1029            1 :                 if manifestWriter != nil {
    1030            0 :                         _ = manifestWriter.Close()
    1031            0 :                 }
    1032            1 :                 if manifestFile != nil {
    1033            0 :                         _ = manifestFile.Close()
    1034            0 :                 }
    1035            1 :                 if err != nil {
    1036            1 :                         _ = vs.fs.Remove(filename)
    1037            1 :                 }
    1038              :         }()
    1039            1 :         manifestFile, err = vs.fs.Create(filename, "pebble-manifest")
    1040            1 :         if err != nil {
    1041            1 :                 return err
    1042            1 :         }
    1043            1 :         manifestWriter = record.NewWriter(manifestFile)
    1044            1 : 
    1045            1 :         snapshot := manifest.VersionEdit{
    1046            1 :                 ComparerName: vs.cmp.Name,
    1047            1 :                 // When creating a version snapshot for an existing DB, this snapshot
    1048            1 :                 // VersionEdit will be immediately followed by another VersionEdit
    1049            1 :                 // (being written in UpdateVersionLocked()). That VersionEdit always
    1050            1 :                 // contains a LastSeqNum, so we don't need to include that in the
    1051            1 :                 // snapshot.  But it does not necessarily include MinUnflushedLogNum,
    1052            1 :                 // NextFileNum, so we initialize those using the corresponding fields in
    1053            1 :                 // the versionSet (which came from the latest preceding VersionEdit that
    1054            1 :                 // had those fields).
    1055            1 :                 MinUnflushedLogNum:   minUnflushedLogNum,
    1056            1 :                 NextFileNum:          nextFileNum,
    1057            1 :                 CreatedBackingTables: virtualBackings,
    1058            1 :                 NewBlobFiles:         vs.latest.blobFiles.Metadatas(),
    1059            1 :         }
    1060            1 : 
    1061            1 :         // Add all extant sstables in the current version.
    1062            1 :         for level, levelMetadata := range vs.currentVersion().Levels {
    1063            1 :                 for meta := range levelMetadata.All() {
    1064            1 :                         snapshot.NewTables = append(snapshot.NewTables, manifest.NewTableEntry{
    1065            1 :                                 Level: level,
    1066            1 :                                 Meta:  meta,
    1067            1 :                         })
    1068            1 :                 }
    1069              :         }
    1070              : 
    1071              :         // Add all tables marked for compaction.
    1072            1 :         if vs.getFormatMajorVersion() >= FormatMarkForCompactionInVersionEdit {
    1073            1 :                 for meta, level := range vs.currentVersion().MarkedForCompaction.Ascending() {
    1074            1 :                         snapshot.TablesMarkedForCompaction = append(snapshot.TablesMarkedForCompaction, manifest.TableMarkedForCompactionEntry{
    1075            1 :                                 Level:    level,
    1076            1 :                                 TableNum: meta.TableNum,
    1077            1 :                         })
    1078            1 :                 }
    1079              :         }
    1080              : 
    1081            1 :         w, err1 := manifestWriter.Next()
    1082            1 :         if err1 != nil {
    1083            0 :                 return err1
    1084            0 :         }
    1085            1 :         if err := snapshot.Encode(w); err != nil {
    1086            0 :                 return err
    1087            0 :         }
    1088              : 
    1089            1 :         if vs.manifest != nil {
    1090            1 :                 if err := vs.manifest.Close(); err != nil {
    1091            0 :                         return err
    1092            0 :                 }
    1093            1 :                 vs.manifest = nil
    1094              :         }
    1095            1 :         if vs.manifestFile != nil {
    1096            1 :                 if err := vs.manifestFile.Close(); err != nil {
    1097            0 :                         return err
    1098            0 :                 }
    1099            1 :                 vs.manifestFile = nil
    1100              :         }
    1101              : 
    1102            1 :         vs.manifest, manifestWriter = manifestWriter, nil
    1103            1 :         vs.manifestFile, manifestFile = manifestFile, nil
    1104            1 :         return nil
    1105              : }
    1106              : 
    1107              : // NB: This method is not safe for concurrent use. It is only safe
    1108              : // to be called when concurrent changes to nextFileNum are not expected.
    1109            1 : func (vs *versionSet) markFileNumUsed(fileNum base.DiskFileNum) {
    1110            1 :         if vs.nextFileNum.Load() <= uint64(fileNum) {
    1111            1 :                 vs.nextFileNum.Store(uint64(fileNum + 1))
    1112            1 :         }
    1113              : }
    1114              : 
    1115              : // getNextTableNum returns a new table number.
    1116              : //
    1117              : // Can be called without the versionSet's mutex being held.
    1118            1 : func (vs *versionSet) getNextTableNum() base.TableNum {
    1119            1 :         x := vs.nextFileNum.Add(1) - 1
    1120            1 :         return base.TableNum(x)
    1121            1 : }
    1122              : 
    1123              : // Can be called without the versionSet's mutex being held.
    1124            1 : func (vs *versionSet) getNextDiskFileNum() base.DiskFileNum {
    1125            1 :         x := vs.nextFileNum.Add(1) - 1
    1126            1 :         return base.DiskFileNum(x)
    1127            1 : }
    1128              : 
    1129            1 : func (vs *versionSet) append(v *manifest.Version) {
    1130            1 :         if v.Refs() != 0 {
    1131            0 :                 panic("pebble: version should be unreferenced")
    1132              :         }
    1133            1 :         if !vs.versions.Empty() {
    1134            1 :                 vs.versions.Back().UnrefLocked()
    1135            1 :         }
    1136            1 :         v.Deleted = vs.obsoleteFn
    1137            1 :         v.Ref()
    1138            1 :         vs.versions.PushBack(v)
    1139            1 :         if invariants.Enabled {
    1140            1 :                 // Verify that the virtualBackings contains all the backings referenced by
    1141            1 :                 // the version.
    1142            1 :                 for _, l := range v.Levels {
    1143            1 :                         for f := range l.All() {
    1144            1 :                                 if f.Virtual {
    1145            1 :                                         if _, ok := vs.latest.virtualBackings.Get(f.TableBacking.DiskFileNum); !ok {
    1146            0 :                                                 panic(fmt.Sprintf("%s is not in virtualBackings", f.TableBacking.DiskFileNum))
    1147              :                                         }
    1148              :                                 }
    1149              :                         }
    1150              :                 }
    1151              :         }
    1152              : }
    1153              : 
    1154            1 : func (vs *versionSet) currentVersion() *manifest.Version {
    1155            1 :         return vs.versions.Back()
    1156            1 : }
    1157              : 
    1158            1 : func (vs *versionSet) addLiveFileNums(m map[base.DiskFileNum]struct{}) {
    1159            1 :         current := vs.currentVersion()
    1160            1 :         for v := vs.versions.Front(); true; v = v.Next() {
    1161            1 :                 for _, lm := range v.Levels {
    1162            1 :                         for f := range lm.All() {
    1163            1 :                                 m[f.TableBacking.DiskFileNum] = struct{}{}
    1164            1 :                         }
    1165              :                 }
    1166            1 :                 for bf := range v.BlobFiles.All() {
    1167            1 :                         m[bf.Physical.FileNum] = struct{}{}
    1168            1 :                 }
    1169            1 :                 if v == current {
    1170            1 :                         break
    1171              :                 }
    1172              :         }
    1173              :         // virtualBackings contains backings that are referenced by some virtual
    1174              :         // tables in the latest version (which are handled above), and backings that
    1175              :         // are not but are still alive because of the protection mechanism (see
    1176              :         // manifset.VirtualBackings). This loop ensures the latter get added to the
    1177              :         // map.
    1178            1 :         for b := range vs.latest.virtualBackings.All() {
    1179            1 :                 m[b.DiskFileNum] = struct{}{}
    1180            1 :         }
    1181              : }
    1182              : 
    1183              : // addObsoleteLocked will add the fileInfo associated with obsolete backing
    1184              : // sstables to the obsolete tables list.
    1185              : //
    1186              : // The file backings in the obsolete list must not appear more than once.
    1187              : //
    1188              : // DB.mu must be held when addObsoleteLocked is called.
    1189            1 : func (vs *versionSet) addObsoleteLocked(obsolete manifest.ObsoleteFiles) {
    1190            1 :         if obsolete.Count() == 0 {
    1191            1 :                 return
    1192            1 :         }
    1193              : 
    1194              :         // Note that the zombie objects transition from zombie *to* obsolete, and
    1195              :         // will no longer be considered zombie.
    1196              : 
    1197            1 :         newlyObsoleteTables := make([]obsoleteFile, len(obsolete.TableBackings))
    1198            1 :         for i, bs := range obsolete.TableBackings {
    1199            1 :                 newlyObsoleteTables[i] = vs.zombieTables.Extract(bs.DiskFileNum).
    1200            1 :                         asObsoleteFile(vs.fs, base.FileTypeTable, vs.dirname)
    1201            1 :         }
    1202            1 :         vs.obsoleteTables = mergeObsoleteFiles(vs.obsoleteTables, newlyObsoleteTables)
    1203            1 : 
    1204            1 :         newlyObsoleteBlobFiles := make([]obsoleteFile, len(obsolete.BlobFiles))
    1205            1 :         for i, bf := range obsolete.BlobFiles {
    1206            1 :                 newlyObsoleteBlobFiles[i] = vs.zombieBlobs.Extract(bf.FileNum).
    1207            1 :                         asObsoleteFile(vs.fs, base.FileTypeBlob, vs.dirname)
    1208            1 :         }
    1209            1 :         vs.obsoleteBlobs = mergeObsoleteFiles(vs.obsoleteBlobs, newlyObsoleteBlobFiles)
    1210            1 :         vs.updateObsoleteObjectMetricsLocked()
    1211              : }
    1212              : 
    1213              : // addObsolete will acquire DB.mu, so DB.mu must not be held when this is
    1214              : // called.
    1215            1 : func (vs *versionSet) addObsolete(obsolete manifest.ObsoleteFiles) {
    1216            1 :         vs.mu.Lock()
    1217            1 :         defer vs.mu.Unlock()
    1218            1 :         vs.addObsoleteLocked(obsolete)
    1219            1 : }
    1220              : 
    1221            1 : func (vs *versionSet) updateObsoleteObjectMetricsLocked() {
    1222            1 :         // TODO(jackson): Ideally we would update vs.fileDeletions.queuedStats to
    1223            1 :         // include the files on vs.obsolete{Tables,Blobs}, but there's subtlety in
    1224            1 :         // deduplicating the files before computing the stats. It might also be
    1225            1 :         // possible to refactor to remove the vs.obsolete{Tables,Blobs} intermediary
    1226            1 :         // step. Revisit this.
    1227            1 :         vs.metrics.Table.ObsoleteCount = int64(len(vs.obsoleteTables))
    1228            1 :         vs.metrics.Table.ObsoleteSize = 0
    1229            1 :         vs.metrics.Table.Local.ObsoleteSize = 0
    1230            1 :         vs.metrics.Table.Local.ObsoleteCount = 0
    1231            1 :         for _, fi := range vs.obsoleteTables {
    1232            1 :                 vs.metrics.Table.ObsoleteSize += fi.fileSize
    1233            1 :                 if fi.isLocal {
    1234            1 :                         vs.metrics.Table.Local.ObsoleteSize += fi.fileSize
    1235            1 :                         vs.metrics.Table.Local.ObsoleteCount++
    1236            1 :                 }
    1237              :         }
    1238            1 :         vs.metrics.BlobFiles.ObsoleteCount = uint64(len(vs.obsoleteBlobs))
    1239            1 :         vs.metrics.BlobFiles.ObsoleteSize = 0
    1240            1 :         vs.metrics.BlobFiles.Local.ObsoleteSize = 0
    1241            1 :         vs.metrics.BlobFiles.Local.ObsoleteCount = 0
    1242            1 :         for _, fi := range vs.obsoleteBlobs {
    1243            1 :                 vs.metrics.BlobFiles.ObsoleteSize += fi.fileSize
    1244            1 :                 if fi.isLocal {
    1245            1 :                         vs.metrics.BlobFiles.Local.ObsoleteSize += fi.fileSize
    1246            1 :                         vs.metrics.BlobFiles.Local.ObsoleteCount++
    1247            1 :                 }
    1248              :         }
    1249              : }
    1250              : 
    1251              : func findCurrentManifest(
    1252              :         fs vfs.FS, dirname string, ls []string,
    1253            1 : ) (marker *atomicfs.Marker, manifestNum base.DiskFileNum, exists bool, err error) {
    1254            1 :         // Locating a marker should succeed even if the marker has never been placed.
    1255            1 :         var filename string
    1256            1 :         marker, filename, err = atomicfs.LocateMarkerInListing(fs, dirname, manifestMarkerName, ls)
    1257            1 :         if err != nil {
    1258            1 :                 return nil, 0, false, err
    1259            1 :         }
    1260              : 
    1261            1 :         if filename == "" {
    1262            1 :                 // The marker hasn't been set yet. This database doesn't exist.
    1263            1 :                 return marker, 0, false, nil
    1264            1 :         }
    1265              : 
    1266            1 :         var ok bool
    1267            1 :         _, manifestNum, ok = base.ParseFilename(fs, filename)
    1268            1 :         if !ok {
    1269            0 :                 return marker, 0, false, base.CorruptionErrorf("pebble: MANIFEST name %q is malformed", errors.Safe(filename))
    1270            0 :         }
    1271            1 :         return marker, manifestNum, true, nil
    1272              : }
    1273              : 
    1274            1 : func newFileMetrics(newFiles []manifest.NewTableEntry) levelMetricsDelta {
    1275            1 :         var m levelMetricsDelta
    1276            1 :         for _, nf := range newFiles {
    1277            1 :                 lm := m[nf.Level]
    1278            1 :                 if lm == nil {
    1279            1 :                         lm = &LevelMetrics{}
    1280            1 :                         m[nf.Level] = lm
    1281            1 :                 }
    1282            1 :                 lm.TablesCount++
    1283            1 :                 lm.TablesSize += int64(nf.Meta.Size)
    1284            1 :                 lm.EstimatedReferencesSize += nf.Meta.EstimatedReferenceSize()
    1285              :         }
    1286            1 :         return m
    1287              : }
        

Generated by: LCOV version 2.0-1