Line data Source code
1 : // Copyright 2013 The LevelDB-Go and Pebble Authors. All rights reserved. Use
2 : // of this source code is governed by a BSD-style license that can be found in
3 : // the LICENSE file.
4 :
5 : package pebble
6 :
7 : import (
8 : "bytes"
9 : "context"
10 : "fmt"
11 : "iter"
12 : "math"
13 : "runtime/pprof"
14 : "slices"
15 : "sort"
16 : "sync/atomic"
17 : "time"
18 : "unsafe"
19 :
20 : "github.com/cockroachdb/crlib/crtime"
21 : "github.com/cockroachdb/errors"
22 : "github.com/cockroachdb/pebble/internal/base"
23 : "github.com/cockroachdb/pebble/internal/compact"
24 : "github.com/cockroachdb/pebble/internal/keyspan"
25 : "github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
26 : "github.com/cockroachdb/pebble/internal/manifest"
27 : "github.com/cockroachdb/pebble/internal/sstableinternal"
28 : "github.com/cockroachdb/pebble/objstorage"
29 : "github.com/cockroachdb/pebble/objstorage/objstorageprovider/objiotracing"
30 : "github.com/cockroachdb/pebble/objstorage/remote"
31 : "github.com/cockroachdb/pebble/sstable"
32 : "github.com/cockroachdb/pebble/sstable/blob"
33 : "github.com/cockroachdb/pebble/sstable/block"
34 : "github.com/cockroachdb/pebble/vfs"
35 : )
36 :
37 : var errEmptyTable = errors.New("pebble: empty table")
38 :
39 : // ErrCancelledCompaction is returned if a compaction is cancelled by a
40 : // concurrent excise or ingest-split operation.
41 : var ErrCancelledCompaction = errors.New("pebble: compaction cancelled by a concurrent operation, will retry compaction")
42 :
43 : var flushLabels = pprof.Labels("pebble", "flush", "output-level", "L0")
44 : var gcLabels = pprof.Labels("pebble", "gc")
45 :
46 : // expandedCompactionByteSizeLimit is the maximum number of bytes in all
47 : // compacted files. We avoid expanding the lower level file set of a compaction
48 : // if it would make the total compaction cover more than this many bytes.
49 1 : func expandedCompactionByteSizeLimit(opts *Options, level int, availBytes uint64) uint64 {
50 1 : v := uint64(25 * opts.Levels[level].TargetFileSize)
51 1 :
52 1 : // Never expand a compaction beyond half the available capacity, divided
53 1 : // by the maximum number of concurrent compactions. Each of the concurrent
54 1 : // compactions may expand up to this limit, so this attempts to limit
55 1 : // compactions to half of available disk space. Note that this will not
56 1 : // prevent compaction picking from pursuing compactions that are larger
57 1 : // than this threshold before expansion.
58 1 : //
59 1 : // NB: this heuristic is an approximation since we may run more compactions
60 1 : // than the upper concurrency limit.
61 1 : _, maxConcurrency := opts.CompactionConcurrencyRange()
62 1 : diskMax := (availBytes / 2) / uint64(maxConcurrency)
63 1 : if v > diskMax {
64 1 : v = diskMax
65 1 : }
66 1 : return v
67 : }
68 :
69 : // maxGrandparentOverlapBytes is the maximum bytes of overlap with level+1
70 : // before we stop building a single file in a level-1 to level compaction.
71 1 : func maxGrandparentOverlapBytes(opts *Options, level int) uint64 {
72 1 : return uint64(10 * opts.Levels[level].TargetFileSize)
73 1 : }
74 :
75 : // maxReadCompactionBytes is used to prevent read compactions which
76 : // are too wide.
77 1 : func maxReadCompactionBytes(opts *Options, level int) uint64 {
78 1 : return uint64(10 * opts.Levels[level].TargetFileSize)
79 1 : }
80 :
81 : // noCloseIter wraps around a FragmentIterator, intercepting and eliding
82 : // calls to Close. It is used during compaction to ensure that rangeDelIters
83 : // are not closed prematurely.
84 : type noCloseIter struct {
85 : keyspan.FragmentIterator
86 : }
87 :
88 1 : func (i *noCloseIter) Close() {}
89 :
90 : type compactionLevel struct {
91 : level int
92 : files manifest.LevelSlice
93 : // l0SublevelInfo contains information about L0 sublevels being compacted.
94 : // It's only set for the start level of a compaction starting out of L0 and
95 : // is nil for all other compactions.
96 : l0SublevelInfo []sublevelInfo
97 : }
98 :
99 1 : func (cl compactionLevel) Clone() compactionLevel {
100 1 : newCL := compactionLevel{
101 1 : level: cl.level,
102 1 : files: cl.files,
103 1 : }
104 1 : return newCL
105 1 : }
106 1 : func (cl compactionLevel) String() string {
107 1 : return fmt.Sprintf(`Level %d, Files %s`, cl.level, cl.files)
108 1 : }
109 :
110 : // compactionWritable is a objstorage.Writable wrapper that, on every write,
111 : // updates a metric in `versions` on bytes written by in-progress compactions so
112 : // far. It also increments a per-compaction `written` atomic int.
113 : type compactionWritable struct {
114 : objstorage.Writable
115 :
116 : versions *versionSet
117 : written *atomic.Int64
118 : }
119 :
120 : // Write is part of the objstorage.Writable interface.
121 1 : func (c *compactionWritable) Write(p []byte) error {
122 1 : if err := c.Writable.Write(p); err != nil {
123 0 : return err
124 0 : }
125 :
126 1 : c.written.Add(int64(len(p)))
127 1 : c.versions.incrementCompactionBytes(int64(len(p)))
128 1 : return nil
129 : }
130 :
131 : type compactionKind int
132 :
133 : const (
134 : compactionKindDefault compactionKind = iota
135 : compactionKindFlush
136 : // compactionKindMove denotes a move compaction where the input file is
137 : // retained and linked in a new level without being obsoleted.
138 : compactionKindMove
139 : // compactionKindCopy denotes a copy compaction where the input file is
140 : // copied byte-by-byte into a new file with a new TableNum in the output level.
141 : compactionKindCopy
142 : // compactionKindDeleteOnly denotes a compaction that only deletes input
143 : // files. It can occur when wide range tombstones completely contain sstables.
144 : compactionKindDeleteOnly
145 : compactionKindElisionOnly
146 : compactionKindRead
147 : compactionKindTombstoneDensity
148 : compactionKindRewrite
149 : compactionKindIngestedFlushable
150 : )
151 :
152 1 : func (k compactionKind) String() string {
153 1 : switch k {
154 1 : case compactionKindDefault:
155 1 : return "default"
156 0 : case compactionKindFlush:
157 0 : return "flush"
158 1 : case compactionKindMove:
159 1 : return "move"
160 1 : case compactionKindDeleteOnly:
161 1 : return "delete-only"
162 1 : case compactionKindElisionOnly:
163 1 : return "elision-only"
164 1 : case compactionKindRead:
165 1 : return "read"
166 1 : case compactionKindTombstoneDensity:
167 1 : return "tombstone-density"
168 1 : case compactionKindRewrite:
169 1 : return "rewrite"
170 0 : case compactionKindIngestedFlushable:
171 0 : return "ingested-flushable"
172 1 : case compactionKindCopy:
173 1 : return "copy"
174 : }
175 0 : return "?"
176 : }
177 :
178 : // compactingOrFlushing returns "flushing" if the compaction kind is a flush,
179 : // otherwise it returns "compacting".
180 1 : func (k compactionKind) compactingOrFlushing() string {
181 1 : if k == compactionKindFlush {
182 1 : return "flushing"
183 1 : }
184 1 : return "compacting"
185 : }
186 :
187 : // compaction is a table compaction from one level to the next, starting from a
188 : // given version.
189 : type compaction struct {
190 : // cancel is a bool that can be used by other goroutines to signal a compaction
191 : // to cancel, such as if a conflicting excise operation raced it to manifest
192 : // application. Only holders of the manifest lock will write to this atomic.
193 : cancel atomic.Bool
194 :
195 : kind compactionKind
196 : // isDownload is true if this compaction was started as part of a Download
197 : // operation. In this case kind is compactionKindCopy or
198 : // compactionKindRewrite.
199 : isDownload bool
200 :
201 : cmp Compare
202 : equal Equal
203 : comparer *base.Comparer
204 : formatKey base.FormatKey
205 : logger Logger
206 : version *manifest.Version
207 : stats base.InternalIteratorStats
208 : beganAt time.Time
209 : // versionEditApplied is set to true when a compaction has completed and the
210 : // resulting version has been installed (if successful), but the compaction
211 : // goroutine is still cleaning up (eg, deleting obsolete files).
212 : versionEditApplied bool
213 : bufferPool sstable.BufferPool
214 : // getValueSeparation constructs a compact.ValueSeparation for use in a
215 : // compaction. It implements heuristics around choosing whether a compaction
216 : // should:
217 : //
218 : // a) preserve existing blob references: The compaction does not write any
219 : // new blob files, but propagates existing references to blob files.This
220 : // conserves write bandwidth by avoiding rewriting the referenced values. It
221 : // also reduces the locality of the referenced values which can reduce scan
222 : // performance because a scan must load values from more unique blob files.
223 : // It can also delay reclamation of disk space if some of the references to
224 : // blob values are elided by the compaction, increasing space amplification.
225 : //
226 : // b) rewrite blob files: The compaction will write eligible values to new
227 : // blob files. This consumes more write bandwidth because all values are
228 : // rewritten. However it restores locality.
229 : getValueSeparation func(JobID, *compaction, sstable.TableFormat) compact.ValueSeparation
230 : // valueFetcher is used to fetch values from blob files. It's propagated
231 : // down the iterator tree through the internal iterator options.
232 : valueFetcher blob.ValueFetcher
233 :
234 : // startLevel is the level that is being compacted. Inputs from startLevel
235 : // and outputLevel will be merged to produce a set of outputLevel files.
236 : startLevel *compactionLevel
237 :
238 : // outputLevel is the level that files are being produced in. outputLevel is
239 : // equal to startLevel+1 except when:
240 : // - if startLevel is 0, the output level equals compactionPicker.baseLevel().
241 : // - in multilevel compaction, the output level is the lowest level involved in
242 : // the compaction
243 : // A compaction's outputLevel is nil for delete-only compactions.
244 : outputLevel *compactionLevel
245 :
246 : // extraLevels point to additional levels in between the input and output
247 : // levels that get compacted in multilevel compactions
248 : extraLevels []*compactionLevel
249 :
250 : inputs []compactionLevel
251 :
252 : // maxOutputFileSize is the maximum size of an individual table created
253 : // during compaction.
254 : maxOutputFileSize uint64
255 : // maxOverlapBytes is the maximum number of bytes of overlap allowed for a
256 : // single output table with the tables in the grandparent level.
257 : maxOverlapBytes uint64
258 :
259 : // flushing contains the flushables (aka memtables) that are being flushed.
260 : flushing flushableList
261 : // bytesWritten contains the number of bytes that have been written to outputs.
262 : bytesWritten atomic.Int64
263 :
264 : // The boundaries of the input data.
265 : smallest InternalKey
266 : largest InternalKey
267 :
268 : // A list of fragment iterators to close when the compaction finishes. Used by
269 : // input iteration to keep rangeDelIters open for the lifetime of the
270 : // compaction, and only close them when the compaction finishes.
271 : closers []*noCloseIter
272 :
273 : // grandparents are the tables in level+2 that overlap with the files being
274 : // compacted. Used to determine output table boundaries. Do not assume that the actual files
275 : // in the grandparent when this compaction finishes will be the same.
276 : grandparents manifest.LevelSlice
277 :
278 : // Boundaries at which flushes to L0 should be split. Determined by
279 : // L0Sublevels. If nil, flushes aren't split.
280 : l0Limits [][]byte
281 :
282 : delElision compact.TombstoneElision
283 : rangeKeyElision compact.TombstoneElision
284 :
285 : // allowedZeroSeqNum is true if seqnums can be zeroed if there are no
286 : // snapshots requiring them to be kept. This determination is made by
287 : // looking for an sstable which overlaps the bounds of the compaction at a
288 : // lower level in the LSM during runCompaction.
289 : allowedZeroSeqNum bool
290 :
291 : // deletionHints are set if this is a compactionKindDeleteOnly. Used to figure
292 : // out whether an input must be deleted in its entirety, or excised into
293 : // virtual sstables.
294 : deletionHints []deleteCompactionHint
295 :
296 : // exciseEnabled is set to true if this is a compactionKindDeleteOnly and
297 : // this compaction is allowed to excise files.
298 : exciseEnabled bool
299 :
300 : metrics levelMetricsDelta
301 :
302 : pickerMetrics pickedCompactionMetrics
303 :
304 : grantHandle CompactionGrantHandle
305 :
306 : opts objstorage.CreateOptions
307 : }
308 :
309 : // inputLargestSeqNumAbsolute returns the maximum LargestSeqNumAbsolute of any
310 : // input sstables.
311 1 : func (c *compaction) inputLargestSeqNumAbsolute() base.SeqNum {
312 1 : var seqNum base.SeqNum
313 1 : for _, cl := range c.inputs {
314 1 : for m := range cl.files.All() {
315 1 : seqNum = max(seqNum, m.LargestSeqNumAbsolute)
316 1 : }
317 : }
318 1 : return seqNum
319 : }
320 :
321 1 : func (c *compaction) makeInfo(jobID JobID) CompactionInfo {
322 1 : info := CompactionInfo{
323 1 : JobID: int(jobID),
324 1 : Reason: c.kind.String(),
325 1 : Input: make([]LevelInfo, 0, len(c.inputs)),
326 1 : Annotations: []string{},
327 1 : }
328 1 : if c.isDownload {
329 1 : info.Reason = "download," + info.Reason
330 1 : }
331 1 : for _, cl := range c.inputs {
332 1 : inputInfo := LevelInfo{Level: cl.level, Tables: nil}
333 1 : for m := range cl.files.All() {
334 1 : inputInfo.Tables = append(inputInfo.Tables, m.TableInfo())
335 1 : }
336 1 : info.Input = append(info.Input, inputInfo)
337 : }
338 1 : if c.outputLevel != nil {
339 1 : info.Output.Level = c.outputLevel.level
340 1 :
341 1 : // If there are no inputs from the output level (eg, a move
342 1 : // compaction), add an empty LevelInfo to info.Input.
343 1 : if len(c.inputs) > 0 && c.inputs[len(c.inputs)-1].level != c.outputLevel.level {
344 0 : info.Input = append(info.Input, LevelInfo{Level: c.outputLevel.level})
345 0 : }
346 1 : } else {
347 1 : // For a delete-only compaction, set the output level to L6. The
348 1 : // output level is not meaningful here, but complicating the
349 1 : // info.Output interface with a pointer doesn't seem worth the
350 1 : // semantic distinction.
351 1 : info.Output.Level = numLevels - 1
352 1 : }
353 :
354 1 : for i, score := range c.pickerMetrics.scores {
355 1 : info.Input[i].Score = score
356 1 : }
357 1 : info.SingleLevelOverlappingRatio = c.pickerMetrics.singleLevelOverlappingRatio
358 1 : info.MultiLevelOverlappingRatio = c.pickerMetrics.multiLevelOverlappingRatio
359 1 : if len(info.Input) > 2 {
360 1 : info.Annotations = append(info.Annotations, "multilevel")
361 1 : }
362 1 : return info
363 : }
364 :
365 1 : func (c *compaction) userKeyBounds() base.UserKeyBounds {
366 1 : return base.UserKeyBoundsFromInternal(c.smallest, c.largest)
367 1 : }
368 :
369 : type getValueSeparation func(JobID, *compaction, sstable.TableFormat) compact.ValueSeparation
370 :
371 : func newCompaction(
372 : pc *pickedCompaction,
373 : opts *Options,
374 : beganAt time.Time,
375 : provider objstorage.Provider,
376 : grantHandle CompactionGrantHandle,
377 : getValueSeparation getValueSeparation,
378 1 : ) *compaction {
379 1 : c := &compaction{
380 1 : kind: compactionKindDefault,
381 1 : cmp: pc.cmp,
382 1 : equal: opts.Comparer.Equal,
383 1 : comparer: opts.Comparer,
384 1 : formatKey: opts.Comparer.FormatKey,
385 1 : inputs: pc.inputs,
386 1 : smallest: pc.smallest,
387 1 : largest: pc.largest,
388 1 : logger: opts.Logger,
389 1 : version: pc.version,
390 1 : beganAt: beganAt,
391 1 : getValueSeparation: getValueSeparation,
392 1 : maxOutputFileSize: pc.maxOutputFileSize,
393 1 : maxOverlapBytes: pc.maxOverlapBytes,
394 1 : pickerMetrics: pc.pickerMetrics,
395 1 : grantHandle: grantHandle,
396 1 : }
397 1 : c.startLevel = &c.inputs[0]
398 1 : if pc.startLevel.l0SublevelInfo != nil {
399 1 : c.startLevel.l0SublevelInfo = pc.startLevel.l0SublevelInfo
400 1 : }
401 1 : c.outputLevel = &c.inputs[1]
402 1 :
403 1 : if len(pc.extraLevels) > 0 {
404 1 : c.extraLevels = pc.extraLevels
405 1 : c.outputLevel = &c.inputs[len(c.inputs)-1]
406 1 : }
407 : // Compute the set of outputLevel+1 files that overlap this compaction (these
408 : // are the grandparent sstables).
409 1 : if c.outputLevel.level+1 < numLevels {
410 1 : c.grandparents = c.version.Overlaps(c.outputLevel.level+1, c.userKeyBounds())
411 1 : }
412 1 : c.delElision, c.rangeKeyElision = compact.SetupTombstoneElision(
413 1 : c.cmp, c.version, pc.l0Organizer, c.outputLevel.level, base.UserKeyBoundsFromInternal(c.smallest, c.largest),
414 1 : )
415 1 : c.kind = pc.kind
416 1 :
417 1 : preferSharedStorage := remote.ShouldCreateShared(opts.Experimental.CreateOnShared, c.outputLevel.level)
418 1 : c.maybeSwitchToMoveOrCopy(preferSharedStorage, provider)
419 1 : c.opts = objstorage.CreateOptions{
420 1 : PreferSharedStorage: preferSharedStorage,
421 1 : WriteCategory: getDiskWriteCategoryForCompaction(opts, c.kind),
422 1 : }
423 1 : if c.opts.PreferSharedStorage {
424 1 : c.getValueSeparation = neverSeparateValues
425 1 : }
426 :
427 1 : return c
428 : }
429 :
430 : // maybeSwitchToMoveOrCopy decides if the compaction can be changed into a move
431 : // or copy compaction, in which case c.kind is updated.
432 : func (c *compaction) maybeSwitchToMoveOrCopy(
433 : preferSharedStorage bool, provider objstorage.Provider,
434 1 : ) {
435 1 : // Only non-multi-level compactions with a single input file can be
436 1 : // considered.
437 1 : if c.startLevel.files.Len() != 1 || !c.outputLevel.files.Empty() || c.hasExtraLevelData() {
438 1 : return
439 1 : }
440 :
441 : // In addition to the default compaction, we also check whether a tombstone
442 : // density compaction can be optimized into a move compaction. However, we
443 : // want to avoid performing a move compaction into the lowest level, since the
444 : // goal there is to actually remove the tombstones.
445 : //
446 : // Tombstone density compaction is meant to address cases where tombstones
447 : // don't reclaim much space but are still expensive to scan over. We can only
448 : // remove the tombstones once there's nothing at all underneath them.
449 1 : switch c.kind {
450 1 : case compactionKindDefault:
451 : // Proceed.
452 1 : case compactionKindTombstoneDensity:
453 1 : // Tombstone density compaction can be optimized into a move compaction.
454 1 : // However, we want to avoid performing a move compaction into the lowest
455 1 : // level, since the goal there is to actually remove the tombstones; even if
456 1 : // they don't prevent a lot of space from being reclaimed, tombstones can
457 1 : // still be expensive to scan over.
458 1 : if c.outputLevel.level == numLevels-1 {
459 1 : return
460 1 : }
461 1 : default:
462 1 : // Other compaction kinds not supported.
463 1 : return
464 : }
465 :
466 : // We avoid a move or copy if there is lots of overlapping grandparent data.
467 : // Otherwise, the move could create a parent file that will require a very
468 : // expensive merge later on.
469 1 : if c.grandparents.AggregateSizeSum() > c.maxOverlapBytes {
470 1 : return
471 1 : }
472 :
473 1 : iter := c.startLevel.files.Iter()
474 1 : meta := iter.First()
475 1 :
476 1 : // We should always be passed a provider, except in some unit tests.
477 1 : isRemote := provider != nil && !objstorage.IsLocalTable(provider, meta.TableBacking.DiskFileNum)
478 1 :
479 1 : // Shared and external tables can always be moved. We can also move a local
480 1 : // table unless we need the result to be on shared storage.
481 1 : if isRemote || !preferSharedStorage {
482 1 : c.kind = compactionKindMove
483 1 : return
484 1 : }
485 :
486 : // We can rewrite the table (regular compaction) or we can use a copy compaction.
487 1 : switch {
488 1 : case meta.Virtual:
489 : // We want to avoid a copy compaction if the table is virtual, as we may end
490 : // up copying a lot more data than necessary.
491 0 : case meta.BlobReferenceDepth != 0:
492 : // We also want to avoid copy compactions for tables with blob references,
493 : // as we currently lack a mechanism to propagate blob references along with
494 : // the sstable.
495 1 : default:
496 1 : c.kind = compactionKindCopy
497 : }
498 : }
499 :
500 : func newDeleteOnlyCompaction(
501 : opts *Options,
502 : cur *manifest.Version,
503 : inputs []compactionLevel,
504 : beganAt time.Time,
505 : hints []deleteCompactionHint,
506 : exciseEnabled bool,
507 1 : ) *compaction {
508 1 : c := &compaction{
509 1 : kind: compactionKindDeleteOnly,
510 1 : cmp: opts.Comparer.Compare,
511 1 : equal: opts.Comparer.Equal,
512 1 : comparer: opts.Comparer,
513 1 : formatKey: opts.Comparer.FormatKey,
514 1 : logger: opts.Logger,
515 1 : version: cur,
516 1 : beganAt: beganAt,
517 1 : inputs: inputs,
518 1 : deletionHints: hints,
519 1 : exciseEnabled: exciseEnabled,
520 1 : grantHandle: noopGrantHandle{},
521 1 : }
522 1 :
523 1 : // Set c.smallest, c.largest.
524 1 : files := make([]iter.Seq[*manifest.TableMetadata], 0, len(inputs))
525 1 : for _, in := range inputs {
526 1 : files = append(files, in.files.All())
527 1 : }
528 1 : c.smallest, c.largest = manifest.KeyRange(opts.Comparer.Compare, files...)
529 1 : return c
530 : }
531 :
532 1 : func adjustGrandparentOverlapBytesForFlush(c *compaction, flushingBytes uint64) {
533 1 : // Heuristic to place a lower bound on compaction output file size
534 1 : // caused by Lbase. Prior to this heuristic we have observed an L0 in
535 1 : // production with 310K files of which 290K files were < 10KB in size.
536 1 : // Our hypothesis is that it was caused by L1 having 2600 files and
537 1 : // ~10GB, such that each flush got split into many tiny files due to
538 1 : // overlapping with most of the files in Lbase.
539 1 : //
540 1 : // The computation below is general in that it accounts
541 1 : // for flushing different volumes of data (e.g. we may be flushing
542 1 : // many memtables). For illustration, we consider the typical
543 1 : // example of flushing a 64MB memtable. So 12.8MB output,
544 1 : // based on the compression guess below. If the compressed bytes
545 1 : // guess is an over-estimate we will end up with smaller files,
546 1 : // and if an under-estimate we will end up with larger files.
547 1 : // With a 2MB target file size, 7 files. We are willing to accept
548 1 : // 4x the number of files, if it results in better write amplification
549 1 : // when later compacting to Lbase, i.e., ~450KB files (target file
550 1 : // size / 4).
551 1 : //
552 1 : // Note that this is a pessimistic heuristic in that
553 1 : // fileCountUpperBoundDueToGrandparents could be far from the actual
554 1 : // number of files produced due to the grandparent limits. For
555 1 : // example, in the extreme, consider a flush that overlaps with 1000
556 1 : // files in Lbase f0...f999, and the initially calculated value of
557 1 : // maxOverlapBytes will cause splits at f10, f20,..., f990, which
558 1 : // means an upper bound file count of 100 files. Say the input bytes
559 1 : // in the flush are such that acceptableFileCount=10. We will fatten
560 1 : // up maxOverlapBytes by 10x to ensure that the upper bound file count
561 1 : // drops to 10. However, it is possible that in practice, even without
562 1 : // this change, we would have produced no more than 10 files, and that
563 1 : // this change makes the files unnecessarily wide. Say the input bytes
564 1 : // are distributed such that 10% are in f0...f9, 10% in f10...f19, ...
565 1 : // 10% in f80...f89 and 10% in f990...f999. The original value of
566 1 : // maxOverlapBytes would have actually produced only 10 sstables. But
567 1 : // by increasing maxOverlapBytes by 10x, we may produce 1 sstable that
568 1 : // spans f0...f89, i.e., a much wider sstable than necessary.
569 1 : //
570 1 : // We could produce a tighter estimate of
571 1 : // fileCountUpperBoundDueToGrandparents if we had knowledge of the key
572 1 : // distribution of the flush. The 4x multiplier mentioned earlier is
573 1 : // a way to try to compensate for this pessimism.
574 1 : //
575 1 : // TODO(sumeer): we don't have compression info for the data being
576 1 : // flushed, but it is likely that existing files that overlap with
577 1 : // this flush in Lbase are representative wrt compression ratio. We
578 1 : // could store the uncompressed size in TableMetadata and estimate
579 1 : // the compression ratio.
580 1 : const approxCompressionRatio = 0.2
581 1 : approxOutputBytes := approxCompressionRatio * float64(flushingBytes)
582 1 : approxNumFilesBasedOnTargetSize :=
583 1 : int(math.Ceil(approxOutputBytes / float64(c.maxOutputFileSize)))
584 1 : acceptableFileCount := float64(4 * approxNumFilesBasedOnTargetSize)
585 1 : // The byte calculation is linear in numGrandparentFiles, but we will
586 1 : // incur this linear cost in compact.Runner.TableSplitLimit() too, so we are
587 1 : // also willing to pay it now. We could approximate this cheaply by using the
588 1 : // mean file size of Lbase.
589 1 : grandparentFileBytes := c.grandparents.AggregateSizeSum()
590 1 : fileCountUpperBoundDueToGrandparents :=
591 1 : float64(grandparentFileBytes) / float64(c.maxOverlapBytes)
592 1 : if fileCountUpperBoundDueToGrandparents > acceptableFileCount {
593 1 : c.maxOverlapBytes = uint64(
594 1 : float64(c.maxOverlapBytes) *
595 1 : (fileCountUpperBoundDueToGrandparents / acceptableFileCount))
596 1 : }
597 : }
598 :
599 : func newFlush(
600 : opts *Options,
601 : cur *manifest.Version,
602 : l0Organizer *manifest.L0Organizer,
603 : baseLevel int,
604 : flushing flushableList,
605 : beganAt time.Time,
606 : getValueSeparation getValueSeparation,
607 1 : ) (*compaction, error) {
608 1 : c := &compaction{
609 1 : kind: compactionKindFlush,
610 1 : cmp: opts.Comparer.Compare,
611 1 : equal: opts.Comparer.Equal,
612 1 : comparer: opts.Comparer,
613 1 : formatKey: opts.Comparer.FormatKey,
614 1 : logger: opts.Logger,
615 1 : version: cur,
616 1 : beganAt: beganAt,
617 1 : inputs: []compactionLevel{{level: -1}, {level: 0}},
618 1 : getValueSeparation: getValueSeparation,
619 1 : maxOutputFileSize: math.MaxUint64,
620 1 : maxOverlapBytes: math.MaxUint64,
621 1 : flushing: flushing,
622 1 : grantHandle: noopGrantHandle{},
623 1 : }
624 1 : c.startLevel = &c.inputs[0]
625 1 : c.outputLevel = &c.inputs[1]
626 1 : if len(flushing) > 0 {
627 1 : if _, ok := flushing[0].flushable.(*ingestedFlushable); ok {
628 1 : if len(flushing) != 1 {
629 0 : panic("pebble: ingestedFlushable must be flushed one at a time.")
630 : }
631 1 : c.kind = compactionKindIngestedFlushable
632 1 : return c, nil
633 : }
634 : }
635 :
636 1 : c.opts = objstorage.CreateOptions{
637 1 : PreferSharedStorage: remote.ShouldCreateShared(opts.Experimental.CreateOnShared, c.outputLevel.level),
638 1 : WriteCategory: getDiskWriteCategoryForCompaction(opts, c.kind),
639 1 : }
640 1 : if c.opts.PreferSharedStorage {
641 1 : c.getValueSeparation = neverSeparateValues
642 1 : }
643 :
644 : // Make sure there's no ingestedFlushable after the first flushable in the
645 : // list.
646 1 : for _, f := range flushing {
647 1 : if _, ok := f.flushable.(*ingestedFlushable); ok {
648 0 : panic("pebble: flushing shouldn't contain ingestedFlushable flushable")
649 : }
650 : }
651 :
652 1 : c.l0Limits = l0Organizer.FlushSplitKeys()
653 1 :
654 1 : smallestSet, largestSet := false, false
655 1 : updatePointBounds := func(iter internalIterator) {
656 1 : if kv := iter.First(); kv != nil {
657 1 : if !smallestSet ||
658 1 : base.InternalCompare(c.cmp, c.smallest, kv.K) > 0 {
659 1 : smallestSet = true
660 1 : c.smallest = kv.K.Clone()
661 1 : }
662 : }
663 1 : if kv := iter.Last(); kv != nil {
664 1 : if !largestSet ||
665 1 : base.InternalCompare(c.cmp, c.largest, kv.K) < 0 {
666 1 : largestSet = true
667 1 : c.largest = kv.K.Clone()
668 1 : }
669 : }
670 : }
671 :
672 1 : updateRangeBounds := func(iter keyspan.FragmentIterator) error {
673 1 : // File bounds require s != nil && !s.Empty(). We only need to check for
674 1 : // s != nil here, as the memtable's FragmentIterator would never surface
675 1 : // empty spans.
676 1 : if s, err := iter.First(); err != nil {
677 0 : return err
678 1 : } else if s != nil {
679 1 : if key := s.SmallestKey(); !smallestSet ||
680 1 : base.InternalCompare(c.cmp, c.smallest, key) > 0 {
681 1 : smallestSet = true
682 1 : c.smallest = key.Clone()
683 1 : }
684 : }
685 1 : if s, err := iter.Last(); err != nil {
686 0 : return err
687 1 : } else if s != nil {
688 1 : if key := s.LargestKey(); !largestSet ||
689 1 : base.InternalCompare(c.cmp, c.largest, key) < 0 {
690 1 : largestSet = true
691 1 : c.largest = key.Clone()
692 1 : }
693 : }
694 1 : return nil
695 : }
696 :
697 1 : var flushingBytes uint64
698 1 : for i := range flushing {
699 1 : f := flushing[i]
700 1 : updatePointBounds(f.newIter(nil))
701 1 : if rangeDelIter := f.newRangeDelIter(nil); rangeDelIter != nil {
702 1 : if err := updateRangeBounds(rangeDelIter); err != nil {
703 0 : return nil, err
704 0 : }
705 : }
706 1 : if rangeKeyIter := f.newRangeKeyIter(nil); rangeKeyIter != nil {
707 1 : if err := updateRangeBounds(rangeKeyIter); err != nil {
708 0 : return nil, err
709 0 : }
710 : }
711 1 : flushingBytes += f.inuseBytes()
712 : }
713 :
714 1 : if opts.FlushSplitBytes > 0 {
715 1 : c.maxOutputFileSize = uint64(opts.Levels[0].TargetFileSize)
716 1 : c.maxOverlapBytes = maxGrandparentOverlapBytes(opts, 0)
717 1 : c.grandparents = c.version.Overlaps(baseLevel, c.userKeyBounds())
718 1 : adjustGrandparentOverlapBytesForFlush(c, flushingBytes)
719 1 : }
720 :
721 : // We don't elide tombstones for flushes.
722 1 : c.delElision, c.rangeKeyElision = compact.NoTombstoneElision(), compact.NoTombstoneElision()
723 1 : return c, nil
724 : }
725 :
726 1 : func (c *compaction) hasExtraLevelData() bool {
727 1 : if len(c.extraLevels) == 0 {
728 1 : // not a multi level compaction
729 1 : return false
730 1 : } else if c.extraLevels[0].files.Empty() {
731 1 : // a multi level compaction without data in the intermediate input level;
732 1 : // e.g. for a multi level compaction with levels 4,5, and 6, this could
733 1 : // occur if there is no files to compact in 5, or in 5 and 6 (i.e. a move).
734 1 : return false
735 1 : }
736 1 : return true
737 : }
738 :
739 : // errorOnUserKeyOverlap returns an error if the last two written sstables in
740 : // this compaction have revisions of the same user key present in both sstables,
741 : // when it shouldn't (eg. when splitting flushes).
742 1 : func (c *compaction) errorOnUserKeyOverlap(ve *manifest.VersionEdit) error {
743 1 : if n := len(ve.NewTables); n > 1 {
744 1 : meta := ve.NewTables[n-1].Meta
745 1 : prevMeta := ve.NewTables[n-2].Meta
746 1 : if !prevMeta.Largest().IsExclusiveSentinel() &&
747 1 : c.cmp(prevMeta.Largest().UserKey, meta.Smallest().UserKey) >= 0 {
748 1 : return errors.Errorf("pebble: compaction split user key across two sstables: %s in %s and %s",
749 1 : prevMeta.Largest().Pretty(c.formatKey),
750 1 : prevMeta.TableNum,
751 1 : meta.TableNum)
752 1 : }
753 : }
754 1 : return nil
755 : }
756 :
757 : // allowZeroSeqNum returns true if seqnum's can be zeroed if there are no
758 : // snapshots requiring them to be kept. It performs this determination by
759 : // looking at the TombstoneElision values which are set up based on sstables
760 : // which overlap the bounds of the compaction at a lower level in the LSM.
761 1 : func (c *compaction) allowZeroSeqNum() bool {
762 1 : // TODO(peter): we disable zeroing of seqnums during flushing to match
763 1 : // RocksDB behavior and to avoid generating overlapping sstables during
764 1 : // DB.replayWAL. When replaying WAL files at startup, we flush after each
765 1 : // WAL is replayed building up a single version edit that is
766 1 : // applied. Because we don't apply the version edit after each flush, this
767 1 : // code doesn't know that L0 contains files and zeroing of seqnums should
768 1 : // be disabled. That is fixable, but it seems safer to just match the
769 1 : // RocksDB behavior for now.
770 1 : return len(c.flushing) == 0 && c.delElision.ElidesEverything() && c.rangeKeyElision.ElidesEverything()
771 1 : }
772 :
773 : // newInputIters returns an iterator over all the input tables in a compaction.
774 : func (c *compaction) newInputIters(
775 : newIters tableNewIters, newRangeKeyIter keyspanimpl.TableNewSpanIter, iiopts internalIterOpts,
776 : ) (
777 : pointIter internalIterator,
778 : rangeDelIter, rangeKeyIter keyspan.FragmentIterator,
779 : retErr error,
780 1 : ) {
781 1 : // Validate the ordering of compaction input files for defense in depth.
782 1 : if len(c.flushing) == 0 {
783 1 : if c.startLevel.level >= 0 {
784 1 : err := manifest.CheckOrdering(c.cmp, c.formatKey,
785 1 : manifest.Level(c.startLevel.level), c.startLevel.files.Iter())
786 1 : if err != nil {
787 1 : return nil, nil, nil, err
788 1 : }
789 : }
790 1 : err := manifest.CheckOrdering(c.cmp, c.formatKey,
791 1 : manifest.Level(c.outputLevel.level), c.outputLevel.files.Iter())
792 1 : if err != nil {
793 1 : return nil, nil, nil, err
794 1 : }
795 1 : if c.startLevel.level == 0 {
796 1 : if c.startLevel.l0SublevelInfo == nil {
797 0 : panic("l0SublevelInfo not created for compaction out of L0")
798 : }
799 1 : for _, info := range c.startLevel.l0SublevelInfo {
800 1 : err := manifest.CheckOrdering(c.cmp, c.formatKey,
801 1 : info.sublevel, info.Iter())
802 1 : if err != nil {
803 1 : return nil, nil, nil, err
804 1 : }
805 : }
806 : }
807 1 : if len(c.extraLevels) > 0 {
808 1 : if len(c.extraLevels) > 1 {
809 0 : panic("n>2 multi level compaction not implemented yet")
810 : }
811 1 : interLevel := c.extraLevels[0]
812 1 : err := manifest.CheckOrdering(c.cmp, c.formatKey,
813 1 : manifest.Level(interLevel.level), interLevel.files.Iter())
814 1 : if err != nil {
815 0 : return nil, nil, nil, err
816 0 : }
817 : }
818 : }
819 :
820 : // There are three classes of keys that a compaction needs to process: point
821 : // keys, range deletion tombstones and range keys. Collect all iterators for
822 : // all these classes of keys from all the levels. We'll aggregate them
823 : // together farther below.
824 : //
825 : // numInputLevels is an approximation of the number of iterator levels. Due
826 : // to idiosyncrasies in iterator construction, we may (rarely) exceed this
827 : // initial capacity.
828 1 : numInputLevels := max(len(c.flushing), len(c.inputs))
829 1 : iters := make([]internalIterator, 0, numInputLevels)
830 1 : rangeDelIters := make([]keyspan.FragmentIterator, 0, numInputLevels)
831 1 : rangeKeyIters := make([]keyspan.FragmentIterator, 0, numInputLevels)
832 1 :
833 1 : // If construction of the iterator inputs fails, ensure that we close all
834 1 : // the consitutent iterators.
835 1 : defer func() {
836 1 : if retErr != nil {
837 1 : for _, iter := range iters {
838 1 : if iter != nil {
839 1 : _ = iter.Close()
840 1 : }
841 : }
842 1 : for _, rangeDelIter := range rangeDelIters {
843 0 : rangeDelIter.Close()
844 0 : }
845 : }
846 : }()
847 1 : iterOpts := IterOptions{
848 1 : Category: categoryCompaction,
849 1 : logger: c.logger,
850 1 : }
851 1 :
852 1 : // Populate iters, rangeDelIters and rangeKeyIters with the appropriate
853 1 : // constituent iterators. This depends on whether this is a flush or a
854 1 : // compaction.
855 1 : if len(c.flushing) != 0 {
856 1 : // If flushing, we need to build the input iterators over the memtables
857 1 : // stored in c.flushing.
858 1 : for i := range c.flushing {
859 1 : f := c.flushing[i]
860 1 : iters = append(iters, f.newFlushIter(nil))
861 1 : rangeDelIter := f.newRangeDelIter(nil)
862 1 : if rangeDelIter != nil {
863 1 : rangeDelIters = append(rangeDelIters, rangeDelIter)
864 1 : }
865 1 : if rangeKeyIter := f.newRangeKeyIter(nil); rangeKeyIter != nil {
866 1 : rangeKeyIters = append(rangeKeyIters, rangeKeyIter)
867 1 : }
868 : }
869 1 : } else {
870 1 : addItersForLevel := func(level *compactionLevel, l manifest.Layer) error {
871 1 : // Add a *levelIter for point iterators. Because we don't call
872 1 : // initRangeDel, the levelIter will close and forget the range
873 1 : // deletion iterator when it steps on to a new file. Surfacing range
874 1 : // deletions to compactions are handled below.
875 1 : iters = append(iters, newLevelIter(context.Background(),
876 1 : iterOpts, c.comparer, newIters, level.files.Iter(), l, iiopts))
877 1 : // TODO(jackson): Use keyspanimpl.LevelIter to avoid loading all the range
878 1 : // deletions into memory upfront. (See #2015, which reverted this.) There
879 1 : // will be no user keys that are split between sstables within a level in
880 1 : // Cockroach 23.1, which unblocks this optimization.
881 1 :
882 1 : // Add the range deletion iterator for each file as an independent level
883 1 : // in mergingIter, as opposed to making a levelIter out of those. This
884 1 : // is safer as levelIter expects all keys coming from underlying
885 1 : // iterators to be in order. Due to compaction / tombstone writing
886 1 : // logic in finishOutput(), it is possible for range tombstones to not
887 1 : // be strictly ordered across all files in one level.
888 1 : //
889 1 : // Consider this example from the metamorphic tests (also repeated in
890 1 : // finishOutput()), consisting of three L3 files with their bounds
891 1 : // specified in square brackets next to the file name:
892 1 : //
893 1 : // ./000240.sst [tmgc#391,MERGE-tmgc#391,MERGE]
894 1 : // tmgc#391,MERGE [786e627a]
895 1 : // tmgc-udkatvs#331,RANGEDEL
896 1 : //
897 1 : // ./000241.sst [tmgc#384,MERGE-tmgc#384,MERGE]
898 1 : // tmgc#384,MERGE [666c7070]
899 1 : // tmgc-tvsalezade#383,RANGEDEL
900 1 : // tmgc-tvsalezade#331,RANGEDEL
901 1 : //
902 1 : // ./000242.sst [tmgc#383,RANGEDEL-tvsalezade#72057594037927935,RANGEDEL]
903 1 : // tmgc-tvsalezade#383,RANGEDEL
904 1 : // tmgc#375,SET [72646c78766965616c72776865676e79]
905 1 : // tmgc-tvsalezade#356,RANGEDEL
906 1 : //
907 1 : // Here, the range tombstone in 000240.sst falls "after" one in
908 1 : // 000241.sst, despite 000240.sst being ordered "before" 000241.sst for
909 1 : // levelIter's purposes. While each file is still consistent before its
910 1 : // bounds, it's safer to have all rangedel iterators be visible to
911 1 : // mergingIter.
912 1 : iter := level.files.Iter()
913 1 : for f := iter.First(); f != nil; f = iter.Next() {
914 1 : rangeDelIter, err := c.newRangeDelIter(newIters, iter.Take(), iterOpts, iiopts, l)
915 1 : if err != nil {
916 1 : // The error will already be annotated with the BackingFileNum, so
917 1 : // we annotate it with the FileNum.
918 1 : return errors.Wrapf(err, "pebble: could not open table %s", errors.Safe(f.TableNum))
919 1 : }
920 1 : if rangeDelIter == nil {
921 1 : continue
922 : }
923 1 : rangeDelIters = append(rangeDelIters, rangeDelIter)
924 1 : c.closers = append(c.closers, rangeDelIter)
925 : }
926 :
927 : // Check if this level has any range keys.
928 1 : hasRangeKeys := false
929 1 : for f := iter.First(); f != nil; f = iter.Next() {
930 1 : if f.HasRangeKeys {
931 1 : hasRangeKeys = true
932 1 : break
933 : }
934 : }
935 1 : if hasRangeKeys {
936 1 : newRangeKeyIterWrapper := func(ctx context.Context, file *manifest.TableMetadata, iterOptions keyspan.SpanIterOptions) (keyspan.FragmentIterator, error) {
937 1 : rangeKeyIter, err := newRangeKeyIter(ctx, file, iterOptions)
938 1 : if err != nil {
939 0 : return nil, err
940 1 : } else if rangeKeyIter == nil {
941 0 : return emptyKeyspanIter, nil
942 0 : }
943 : // Ensure that the range key iter is not closed until the compaction is
944 : // finished. This is necessary because range key processing
945 : // requires the range keys to be held in memory for up to the
946 : // lifetime of the compaction.
947 1 : noCloseIter := &noCloseIter{rangeKeyIter}
948 1 : c.closers = append(c.closers, noCloseIter)
949 1 :
950 1 : // We do not need to truncate range keys to sstable boundaries, or
951 1 : // only read within the file's atomic compaction units, unlike with
952 1 : // range tombstones. This is because range keys were added after we
953 1 : // stopped splitting user keys across sstables, so all the range keys
954 1 : // in this sstable must wholly lie within the file's bounds.
955 1 : return noCloseIter, err
956 : }
957 1 : li := keyspanimpl.NewLevelIter(
958 1 : context.Background(), keyspan.SpanIterOptions{}, c.cmp,
959 1 : newRangeKeyIterWrapper, level.files.Iter(), l, manifest.KeyTypeRange,
960 1 : )
961 1 : rangeKeyIters = append(rangeKeyIters, li)
962 : }
963 1 : return nil
964 : }
965 :
966 1 : for i := range c.inputs {
967 1 : // If the level is annotated with l0SublevelInfo, expand it into one
968 1 : // level per sublevel.
969 1 : // TODO(jackson): Perform this expansion even earlier when we pick the
970 1 : // compaction?
971 1 : if len(c.inputs[i].l0SublevelInfo) > 0 {
972 1 : for _, info := range c.startLevel.l0SublevelInfo {
973 1 : sublevelCompactionLevel := &compactionLevel{0, info.LevelSlice, nil}
974 1 : if err := addItersForLevel(sublevelCompactionLevel, info.sublevel); err != nil {
975 1 : return nil, nil, nil, err
976 1 : }
977 : }
978 1 : continue
979 : }
980 1 : if err := addItersForLevel(&c.inputs[i], manifest.Level(c.inputs[i].level)); err != nil {
981 1 : return nil, nil, nil, err
982 1 : }
983 : }
984 : }
985 :
986 : // If there's only one constituent point iterator, we can avoid the overhead
987 : // of a *mergingIter. This is possible, for example, when performing a flush
988 : // of a single memtable. Otherwise, combine all the iterators into a merging
989 : // iter.
990 1 : pointIter = iters[0]
991 1 : if len(iters) > 1 {
992 1 : pointIter = newMergingIter(c.logger, &c.stats, c.cmp, nil, iters...)
993 1 : }
994 :
995 : // In normal operation, levelIter iterates over the point operations in a
996 : // level, and initializes a rangeDelIter pointer for the range deletions in
997 : // each table. During compaction, we want to iterate over the merged view of
998 : // point operations and range deletions. In order to do this we create one
999 : // levelIter per level to iterate over the point operations, and collect up
1000 : // all the range deletion files.
1001 : //
1002 : // The range deletion levels are combined with a keyspanimpl.MergingIter. The
1003 : // resulting merged rangedel iterator is then included using an
1004 : // InterleavingIter.
1005 : // TODO(jackson): Consider using a defragmenting iterator to stitch together
1006 : // logical range deletions that were fragmented due to previous file
1007 : // boundaries.
1008 1 : if len(rangeDelIters) > 0 {
1009 1 : mi := &keyspanimpl.MergingIter{}
1010 1 : mi.Init(c.comparer, keyspan.NoopTransform, new(keyspanimpl.MergingBuffers), rangeDelIters...)
1011 1 : rangeDelIter = mi
1012 1 : }
1013 :
1014 : // If there are range key iterators, we need to combine them using
1015 : // keyspanimpl.MergingIter, and then interleave them among the points.
1016 1 : if len(rangeKeyIters) > 0 {
1017 1 : mi := &keyspanimpl.MergingIter{}
1018 1 : mi.Init(c.comparer, keyspan.NoopTransform, new(keyspanimpl.MergingBuffers), rangeKeyIters...)
1019 1 : // TODO(radu): why do we have a defragmenter here but not above?
1020 1 : di := &keyspan.DefragmentingIter{}
1021 1 : di.Init(c.comparer, mi, keyspan.DefragmentInternal, keyspan.StaticDefragmentReducer, new(keyspan.DefragmentingBuffers))
1022 1 : rangeKeyIter = di
1023 1 : }
1024 1 : return pointIter, rangeDelIter, rangeKeyIter, nil
1025 : }
1026 :
1027 : func (c *compaction) newRangeDelIter(
1028 : newIters tableNewIters,
1029 : f manifest.LevelFile,
1030 : opts IterOptions,
1031 : iiopts internalIterOpts,
1032 : l manifest.Layer,
1033 1 : ) (*noCloseIter, error) {
1034 1 : opts.layer = l
1035 1 : iterSet, err := newIters(context.Background(), f.TableMetadata, &opts,
1036 1 : internalIterOpts{
1037 1 : compaction: true,
1038 1 : readEnv: sstable.ReadEnv{Block: block.ReadEnv{BufferPool: &c.bufferPool}},
1039 1 : }, iterRangeDeletions)
1040 1 : if err != nil {
1041 1 : return nil, err
1042 1 : } else if iterSet.rangeDeletion == nil {
1043 1 : // The file doesn't contain any range deletions.
1044 1 : return nil, nil
1045 1 : }
1046 : // Ensure that rangeDelIter is not closed until the compaction is
1047 : // finished. This is necessary because range tombstone processing
1048 : // requires the range tombstones to be held in memory for up to the
1049 : // lifetime of the compaction.
1050 1 : return &noCloseIter{iterSet.rangeDeletion}, nil
1051 : }
1052 :
1053 1 : func (c *compaction) String() string {
1054 1 : if len(c.flushing) != 0 {
1055 0 : return "flush\n"
1056 0 : }
1057 :
1058 1 : var buf bytes.Buffer
1059 1 : for level := c.startLevel.level; level <= c.outputLevel.level; level++ {
1060 1 : i := level - c.startLevel.level
1061 1 : fmt.Fprintf(&buf, "%d:", level)
1062 1 : for f := range c.inputs[i].files.All() {
1063 1 : fmt.Fprintf(&buf, " %s:%s-%s", f.TableNum, f.Smallest(), f.Largest())
1064 1 : }
1065 1 : fmt.Fprintf(&buf, "\n")
1066 : }
1067 1 : return buf.String()
1068 : }
1069 :
1070 : type manualCompaction struct {
1071 : // id is for internal bookkeeping.
1072 : id uint64
1073 : // Count of the retries due to concurrent compaction to overlapping levels.
1074 : retries int
1075 : level int
1076 : outputLevel int
1077 : done chan error
1078 : start []byte
1079 : end []byte
1080 : split bool
1081 : }
1082 :
1083 : type readCompaction struct {
1084 : level int
1085 : // [start, end] key ranges are used for de-duping.
1086 : start []byte
1087 : end []byte
1088 :
1089 : // The file associated with the compaction.
1090 : // If the file no longer belongs in the same
1091 : // level, then we skip the compaction.
1092 : tableNum base.TableNum
1093 : }
1094 :
1095 1 : func (d *DB) addInProgressCompaction(c *compaction) {
1096 1 : d.mu.compact.inProgress[c] = struct{}{}
1097 1 : var isBase, isIntraL0 bool
1098 1 : for _, cl := range c.inputs {
1099 1 : for f := range cl.files.All() {
1100 1 : if f.IsCompacting() {
1101 0 : d.opts.Logger.Fatalf("L%d->L%d: %s already being compacted", c.startLevel.level, c.outputLevel.level, f.TableNum)
1102 0 : }
1103 1 : f.SetCompactionState(manifest.CompactionStateCompacting)
1104 1 : if c.startLevel != nil && c.outputLevel != nil && c.startLevel.level == 0 {
1105 1 : if c.outputLevel.level == 0 {
1106 1 : f.IsIntraL0Compacting = true
1107 1 : isIntraL0 = true
1108 1 : } else {
1109 1 : isBase = true
1110 1 : }
1111 : }
1112 : }
1113 : }
1114 :
1115 1 : if isIntraL0 || isBase {
1116 1 : l0Inputs := []manifest.LevelSlice{c.startLevel.files}
1117 1 : if isIntraL0 {
1118 1 : l0Inputs = append(l0Inputs, c.outputLevel.files)
1119 1 : }
1120 1 : if err := d.mu.versions.l0Organizer.UpdateStateForStartedCompaction(l0Inputs, isBase); err != nil {
1121 0 : d.opts.Logger.Fatalf("could not update state for compaction: %s", err)
1122 0 : }
1123 : }
1124 : }
1125 :
1126 : // Removes compaction markers from files in a compaction. The rollback parameter
1127 : // indicates whether the compaction state should be rolled back to its original
1128 : // state in the case of an unsuccessful compaction.
1129 : //
1130 : // DB.mu must be held when calling this method, however this method can drop and
1131 : // re-acquire that mutex. All writes to the manifest for this compaction should
1132 : // have completed by this point.
1133 1 : func (d *DB) clearCompactingState(c *compaction, rollback bool) {
1134 1 : c.versionEditApplied = true
1135 1 : for _, cl := range c.inputs {
1136 1 : for f := range cl.files.All() {
1137 1 : if !f.IsCompacting() {
1138 0 : d.opts.Logger.Fatalf("L%d->L%d: %s not being compacted", c.startLevel.level, c.outputLevel.level, f.TableNum)
1139 0 : }
1140 1 : if !rollback {
1141 1 : // On success all compactions other than move and delete-only compactions
1142 1 : // transition the file into the Compacted state. Move-compacted files
1143 1 : // become eligible for compaction again and transition back to NotCompacting.
1144 1 : // Delete-only compactions could, on rare occasion, leave files untouched
1145 1 : // (eg. if files have a loose bound), so we revert them all to NotCompacting
1146 1 : // just in case they need to be compacted again.
1147 1 : if c.kind != compactionKindMove && c.kind != compactionKindDeleteOnly {
1148 1 : f.SetCompactionState(manifest.CompactionStateCompacted)
1149 1 : } else {
1150 1 : f.SetCompactionState(manifest.CompactionStateNotCompacting)
1151 1 : }
1152 1 : } else {
1153 1 : // Else, on rollback, all input files unconditionally transition back to
1154 1 : // NotCompacting.
1155 1 : f.SetCompactionState(manifest.CompactionStateNotCompacting)
1156 1 : }
1157 1 : f.IsIntraL0Compacting = false
1158 : }
1159 : }
1160 1 : l0InProgress := inProgressL0Compactions(d.getInProgressCompactionInfoLocked(c))
1161 1 : func() {
1162 1 : // InitCompactingFileInfo requires that no other manifest writes be
1163 1 : // happening in parallel with it, i.e. we're not in the midst of installing
1164 1 : // another version. Otherwise, it's possible that we've created another
1165 1 : // L0Sublevels instance, but not added it to the versions list, causing
1166 1 : // all the indices in TableMetadata to be inaccurate. To ensure this,
1167 1 : // grab the manifest lock.
1168 1 : d.mu.versions.logLock()
1169 1 : // It is a bit peculiar that we are fiddling with th current version state
1170 1 : // in a separate critical section from when this version was installed.
1171 1 : // But this fiddling is necessary if the compaction failed. When the
1172 1 : // compaction succeeded, we've already done this in UpdateVersionLocked, so
1173 1 : // this seems redundant. Anyway, we clear the pickedCompactionCache since we
1174 1 : // may be able to pick a better compaction (though when this compaction
1175 1 : // succeeded we've also cleared the cache in UpdateVersionLocked).
1176 1 : defer d.mu.versions.logUnlockAndInvalidatePickedCompactionCache()
1177 1 : d.mu.versions.l0Organizer.InitCompactingFileInfo(l0InProgress)
1178 1 : }()
1179 : }
1180 :
1181 1 : func (d *DB) calculateDiskAvailableBytes() uint64 {
1182 1 : space, err := d.opts.FS.GetDiskUsage(d.dirname)
1183 1 : if err != nil {
1184 1 : if !errors.Is(err, vfs.ErrUnsupported) {
1185 1 : d.opts.EventListener.BackgroundError(err)
1186 1 : }
1187 : // Return the last value we managed to obtain.
1188 1 : return d.diskAvailBytes.Load()
1189 : }
1190 :
1191 1 : d.lowDiskSpaceReporter.Report(space.AvailBytes, space.TotalBytes, d.opts.EventListener)
1192 1 : d.diskAvailBytes.Store(space.AvailBytes)
1193 1 : return space.AvailBytes
1194 : }
1195 :
1196 : // maybeScheduleFlush schedules a flush if necessary.
1197 : //
1198 : // d.mu must be held when calling this.
1199 1 : func (d *DB) maybeScheduleFlush() {
1200 1 : if d.mu.compact.flushing || d.closed.Load() != nil || d.opts.ReadOnly {
1201 1 : return
1202 1 : }
1203 1 : if len(d.mu.mem.queue) <= 1 {
1204 1 : return
1205 1 : }
1206 :
1207 1 : if !d.passedFlushThreshold() {
1208 1 : return
1209 1 : }
1210 :
1211 1 : d.mu.compact.flushing = true
1212 1 : go d.flush()
1213 : }
1214 :
1215 1 : func (d *DB) passedFlushThreshold() bool {
1216 1 : var n int
1217 1 : var size uint64
1218 1 : for ; n < len(d.mu.mem.queue)-1; n++ {
1219 1 : if !d.mu.mem.queue[n].readyForFlush() {
1220 1 : break
1221 : }
1222 1 : if d.mu.mem.queue[n].flushForced {
1223 1 : // A flush was forced. Pretend the memtable size is the configured
1224 1 : // size. See minFlushSize below.
1225 1 : size += d.opts.MemTableSize
1226 1 : } else {
1227 1 : size += d.mu.mem.queue[n].totalBytes()
1228 1 : }
1229 : }
1230 1 : if n == 0 {
1231 1 : // None of the immutable memtables are ready for flushing.
1232 1 : return false
1233 1 : }
1234 :
1235 : // Only flush once the sum of the queued memtable sizes exceeds half the
1236 : // configured memtable size. This prevents flushing of memtables at startup
1237 : // while we're undergoing the ramp period on the memtable size. See
1238 : // DB.newMemTable().
1239 1 : minFlushSize := d.opts.MemTableSize / 2
1240 1 : return size >= minFlushSize
1241 : }
1242 :
1243 1 : func (d *DB) maybeScheduleDelayedFlush(tbl *memTable, dur time.Duration) {
1244 1 : var mem *flushableEntry
1245 1 : for _, m := range d.mu.mem.queue {
1246 1 : if m.flushable == tbl {
1247 1 : mem = m
1248 1 : break
1249 : }
1250 : }
1251 1 : if mem == nil || mem.flushForced {
1252 1 : return
1253 1 : }
1254 1 : deadline := d.timeNow().Add(dur)
1255 1 : if !mem.delayedFlushForcedAt.IsZero() && deadline.After(mem.delayedFlushForcedAt) {
1256 1 : // Already scheduled to flush sooner than within `dur`.
1257 1 : return
1258 1 : }
1259 1 : mem.delayedFlushForcedAt = deadline
1260 1 : go func() {
1261 1 : timer := time.NewTimer(dur)
1262 1 : defer timer.Stop()
1263 1 :
1264 1 : select {
1265 1 : case <-d.closedCh:
1266 1 : return
1267 1 : case <-mem.flushed:
1268 1 : return
1269 1 : case <-timer.C:
1270 1 : d.commit.mu.Lock()
1271 1 : defer d.commit.mu.Unlock()
1272 1 : d.mu.Lock()
1273 1 : defer d.mu.Unlock()
1274 1 :
1275 1 : // NB: The timer may fire concurrently with a call to Close. If a
1276 1 : // Close call beat us to acquiring d.mu, d.closed holds ErrClosed,
1277 1 : // and it's too late to flush anything. Otherwise, the Close call
1278 1 : // will block on locking d.mu until we've finished scheduling the
1279 1 : // flush and set `d.mu.compact.flushing` to true. Close will wait
1280 1 : // for the current flush to complete.
1281 1 : if d.closed.Load() != nil {
1282 1 : return
1283 1 : }
1284 :
1285 1 : if d.mu.mem.mutable == tbl {
1286 1 : _ = d.makeRoomForWrite(nil)
1287 1 : } else {
1288 1 : mem.flushForced = true
1289 1 : }
1290 1 : d.maybeScheduleFlush()
1291 : }
1292 : }()
1293 : }
1294 :
1295 1 : func (d *DB) flush() {
1296 1 : pprof.Do(context.Background(), flushLabels, func(context.Context) {
1297 1 : flushingWorkStart := crtime.NowMono()
1298 1 : d.mu.Lock()
1299 1 : defer d.mu.Unlock()
1300 1 : idleDuration := flushingWorkStart.Sub(d.mu.compact.noOngoingFlushStartTime)
1301 1 : var bytesFlushed uint64
1302 1 : var err error
1303 1 : if bytesFlushed, err = d.flush1(); err != nil {
1304 1 : // TODO(peter): count consecutive flush errors and backoff.
1305 1 : d.opts.EventListener.BackgroundError(err)
1306 1 : }
1307 1 : d.mu.compact.flushing = false
1308 1 : d.mu.compact.noOngoingFlushStartTime = crtime.NowMono()
1309 1 : workDuration := d.mu.compact.noOngoingFlushStartTime.Sub(flushingWorkStart)
1310 1 : d.mu.compact.flushWriteThroughput.Bytes += int64(bytesFlushed)
1311 1 : d.mu.compact.flushWriteThroughput.WorkDuration += workDuration
1312 1 : d.mu.compact.flushWriteThroughput.IdleDuration += idleDuration
1313 1 : // More flush work may have arrived while we were flushing, so schedule
1314 1 : // another flush if needed.
1315 1 : d.maybeScheduleFlush()
1316 1 : // Let the CompactionScheduler know, so that it can react immediately to
1317 1 : // an increase in DB.GetAllowedWithoutPermission.
1318 1 : d.opts.Experimental.CompactionScheduler.UpdateGetAllowedWithoutPermission()
1319 1 : // The flush may have produced too many files in a level, so schedule a
1320 1 : // compaction if needed.
1321 1 : d.maybeScheduleCompaction()
1322 1 : d.mu.compact.cond.Broadcast()
1323 : })
1324 : }
1325 :
1326 : // runIngestFlush is used to generate a flush version edit for sstables which
1327 : // were ingested as flushables. Both DB.mu and the manifest lock must be held
1328 : // while runIngestFlush is called.
1329 1 : func (d *DB) runIngestFlush(c *compaction) (*manifest.VersionEdit, error) {
1330 1 : if len(c.flushing) != 1 {
1331 0 : panic("pebble: ingestedFlushable must be flushed one at a time.")
1332 : }
1333 :
1334 : // Finding the target level for ingestion must use the latest version
1335 : // after the logLock has been acquired.
1336 1 : c.version = d.mu.versions.currentVersion()
1337 1 :
1338 1 : baseLevel := d.mu.versions.picker.getBaseLevel()
1339 1 : ve := &manifest.VersionEdit{}
1340 1 : var ingestSplitFiles []ingestSplitFile
1341 1 : ingestFlushable := c.flushing[0].flushable.(*ingestedFlushable)
1342 1 :
1343 1 : updateLevelMetricsOnExcise := func(m *manifest.TableMetadata, level int, added []manifest.NewTableEntry) {
1344 1 : levelMetrics := c.metrics[level]
1345 1 : if levelMetrics == nil {
1346 1 : levelMetrics = &LevelMetrics{}
1347 1 : c.metrics[level] = levelMetrics
1348 1 : }
1349 1 : levelMetrics.TablesCount--
1350 1 : levelMetrics.TablesSize -= int64(m.Size)
1351 1 : levelMetrics.EstimatedReferencesSize -= m.EstimatedReferenceSize()
1352 1 : for i := range added {
1353 1 : levelMetrics.TablesCount++
1354 1 : levelMetrics.TablesSize += int64(added[i].Meta.Size)
1355 1 : levelMetrics.EstimatedReferencesSize += added[i].Meta.EstimatedReferenceSize()
1356 1 : }
1357 : }
1358 :
1359 1 : suggestSplit := d.opts.Experimental.IngestSplit != nil && d.opts.Experimental.IngestSplit() &&
1360 1 : d.FormatMajorVersion() >= FormatVirtualSSTables
1361 1 :
1362 1 : if suggestSplit || ingestFlushable.exciseSpan.Valid() {
1363 1 : // We could add deleted files to ve.
1364 1 : ve.DeletedTables = make(map[manifest.DeletedTableEntry]*manifest.TableMetadata)
1365 1 : }
1366 :
1367 1 : ctx := context.Background()
1368 1 : overlapChecker := &overlapChecker{
1369 1 : comparer: d.opts.Comparer,
1370 1 : newIters: d.newIters,
1371 1 : opts: IterOptions{
1372 1 : logger: d.opts.Logger,
1373 1 : Category: categoryIngest,
1374 1 : },
1375 1 : v: c.version,
1376 1 : }
1377 1 : replacedTables := make(map[base.TableNum][]manifest.NewTableEntry)
1378 1 : for _, file := range ingestFlushable.files {
1379 1 : var fileToSplit *manifest.TableMetadata
1380 1 : var level int
1381 1 :
1382 1 : // This file fits perfectly within the excise span, so we can slot it at L6.
1383 1 : if ingestFlushable.exciseSpan.Valid() &&
1384 1 : ingestFlushable.exciseSpan.Contains(d.cmp, file.Smallest()) &&
1385 1 : ingestFlushable.exciseSpan.Contains(d.cmp, file.Largest()) {
1386 1 : level = 6
1387 1 : } else {
1388 1 : // TODO(radu): this can perform I/O; we should not do this while holding DB.mu.
1389 1 : lsmOverlap, err := overlapChecker.DetermineLSMOverlap(ctx, file.UserKeyBounds())
1390 1 : if err != nil {
1391 0 : return nil, err
1392 0 : }
1393 1 : level, fileToSplit, err = ingestTargetLevel(
1394 1 : ctx, d.cmp, lsmOverlap, baseLevel, d.mu.compact.inProgress, file, suggestSplit,
1395 1 : )
1396 1 : if err != nil {
1397 0 : return nil, err
1398 0 : }
1399 : }
1400 :
1401 : // Add the current flushableIngest file to the version.
1402 1 : ve.NewTables = append(ve.NewTables, manifest.NewTableEntry{Level: level, Meta: file})
1403 1 : if fileToSplit != nil {
1404 0 : ingestSplitFiles = append(ingestSplitFiles, ingestSplitFile{
1405 0 : ingestFile: file,
1406 0 : splitFile: fileToSplit,
1407 0 : level: level,
1408 0 : })
1409 0 : }
1410 1 : levelMetrics := c.metrics[level]
1411 1 : if levelMetrics == nil {
1412 1 : levelMetrics = &LevelMetrics{}
1413 1 : c.metrics[level] = levelMetrics
1414 1 : }
1415 1 : levelMetrics.TableBytesIngested += file.Size
1416 1 : levelMetrics.TablesIngested++
1417 : }
1418 1 : if ingestFlushable.exciseSpan.Valid() {
1419 1 : exciseBounds := ingestFlushable.exciseSpan.UserKeyBounds()
1420 1 : // Iterate through all levels and find files that intersect with exciseSpan.
1421 1 : for layer, ls := range c.version.AllLevelsAndSublevels() {
1422 1 : for m := range ls.Overlaps(d.cmp, ingestFlushable.exciseSpan.UserKeyBounds()).All() {
1423 1 : leftTable, rightTable, err := d.exciseTable(context.TODO(), exciseBounds, m, layer.Level(), tightExciseBounds)
1424 1 : if err != nil {
1425 0 : return nil, err
1426 0 : }
1427 1 : newFiles := applyExciseToVersionEdit(ve, m, leftTable, rightTable, layer.Level())
1428 1 : replacedTables[m.TableNum] = newFiles
1429 1 : updateLevelMetricsOnExcise(m, layer.Level(), newFiles)
1430 : }
1431 : }
1432 : }
1433 :
1434 1 : if len(ingestSplitFiles) > 0 {
1435 0 : if err := d.ingestSplit(context.TODO(), ve, updateLevelMetricsOnExcise, ingestSplitFiles, replacedTables); err != nil {
1436 0 : return nil, err
1437 0 : }
1438 : }
1439 :
1440 1 : return ve, nil
1441 : }
1442 :
1443 : // flush runs a compaction that copies the immutable memtables from memory to
1444 : // disk.
1445 : //
1446 : // d.mu must be held when calling this, but the mutex may be dropped and
1447 : // re-acquired during the course of this method.
1448 1 : func (d *DB) flush1() (bytesFlushed uint64, err error) {
1449 1 : // NB: The flushable queue can contain flushables of type ingestedFlushable.
1450 1 : // The sstables in ingestedFlushable.files must be placed into the appropriate
1451 1 : // level in the lsm. Let's say the flushable queue contains a prefix of
1452 1 : // regular immutable memtables, then an ingestedFlushable, and then the
1453 1 : // mutable memtable. When the flush of the ingestedFlushable is performed,
1454 1 : // it needs an updated view of the lsm. That is, the prefix of immutable
1455 1 : // memtables must have already been flushed. Similarly, if there are two
1456 1 : // contiguous ingestedFlushables in the queue, then the first flushable must
1457 1 : // be flushed, so that the second flushable can see an updated view of the
1458 1 : // lsm.
1459 1 : //
1460 1 : // Given the above, we restrict flushes to either some prefix of regular
1461 1 : // memtables, or a single flushable of type ingestedFlushable. The DB.flush
1462 1 : // function will call DB.maybeScheduleFlush again, so a new flush to finish
1463 1 : // the remaining flush work should be scheduled right away.
1464 1 : //
1465 1 : // NB: Large batches placed in the flushable queue share the WAL with the
1466 1 : // previous memtable in the queue. We must ensure the property that both the
1467 1 : // large batch and the memtable with which it shares a WAL are flushed
1468 1 : // together. The property ensures that the minimum unflushed log number
1469 1 : // isn't incremented incorrectly. Since a flushableBatch.readyToFlush always
1470 1 : // returns true, and since the large batch will always be placed right after
1471 1 : // the memtable with which it shares a WAL, the property is naturally
1472 1 : // ensured. The large batch will always be placed after the memtable with
1473 1 : // which it shares a WAL because we ensure it in DB.commitWrite by holding
1474 1 : // the commitPipeline.mu and then holding DB.mu. As an extra defensive
1475 1 : // measure, if we try to flush the memtable without also flushing the
1476 1 : // flushable batch in the same flush, since the memtable and flushableBatch
1477 1 : // have the same logNum, the logNum invariant check below will trigger.
1478 1 : var n, inputs int
1479 1 : var inputBytes uint64
1480 1 : var ingest bool
1481 1 : for ; n < len(d.mu.mem.queue)-1; n++ {
1482 1 : if f, ok := d.mu.mem.queue[n].flushable.(*ingestedFlushable); ok {
1483 1 : if n == 0 {
1484 1 : // The first flushable is of type ingestedFlushable. Since these
1485 1 : // must be flushed individually, we perform a flush for just
1486 1 : // this.
1487 1 : if !f.readyForFlush() {
1488 0 : // This check is almost unnecessary, but we guard against it
1489 0 : // just in case this invariant changes in the future.
1490 0 : panic("pebble: ingestedFlushable should always be ready to flush.")
1491 : }
1492 : // By setting n = 1, we ensure that the first flushable(n == 0)
1493 : // is scheduled for a flush. The number of tables added is equal to the
1494 : // number of files in the ingest operation.
1495 1 : n = 1
1496 1 : inputs = len(f.files)
1497 1 : ingest = true
1498 1 : break
1499 1 : } else {
1500 1 : // There was some prefix of flushables which weren't of type
1501 1 : // ingestedFlushable. So, perform a flush for those.
1502 1 : break
1503 : }
1504 : }
1505 1 : if !d.mu.mem.queue[n].readyForFlush() {
1506 1 : break
1507 : }
1508 1 : inputBytes += d.mu.mem.queue[n].inuseBytes()
1509 : }
1510 1 : if n == 0 {
1511 0 : // None of the immutable memtables are ready for flushing.
1512 0 : return 0, nil
1513 0 : }
1514 1 : if !ingest {
1515 1 : // Flushes of memtables add the prefix of n memtables from the flushable
1516 1 : // queue.
1517 1 : inputs = n
1518 1 : }
1519 :
1520 : // Require that every memtable being flushed has a log number less than the
1521 : // new minimum unflushed log number.
1522 1 : minUnflushedLogNum := d.mu.mem.queue[n].logNum
1523 1 : if !d.opts.DisableWAL {
1524 1 : for i := 0; i < n; i++ {
1525 1 : if logNum := d.mu.mem.queue[i].logNum; logNum >= minUnflushedLogNum {
1526 0 : panic(errors.AssertionFailedf("logNum invariant violated: flushing %d items; %d:type=%T,logNum=%d; %d:type=%T,logNum=%d",
1527 0 : n,
1528 0 : i, d.mu.mem.queue[i].flushable, logNum,
1529 0 : n, d.mu.mem.queue[n].flushable, minUnflushedLogNum))
1530 : }
1531 : }
1532 : }
1533 :
1534 1 : c, err := newFlush(d.opts, d.mu.versions.currentVersion(), d.mu.versions.l0Organizer,
1535 1 : d.mu.versions.picker.getBaseLevel(), d.mu.mem.queue[:n], d.timeNow(), d.determineCompactionValueSeparation)
1536 1 : if err != nil {
1537 0 : return 0, err
1538 0 : }
1539 1 : d.addInProgressCompaction(c)
1540 1 :
1541 1 : jobID := d.newJobIDLocked()
1542 1 : info := FlushInfo{
1543 1 : JobID: int(jobID),
1544 1 : Input: inputs,
1545 1 : InputBytes: inputBytes,
1546 1 : Ingest: ingest,
1547 1 : }
1548 1 : d.opts.EventListener.FlushBegin(info)
1549 1 :
1550 1 : startTime := d.timeNow()
1551 1 :
1552 1 : var ve *manifest.VersionEdit
1553 1 : var stats compact.Stats
1554 1 : // To determine the target level of the files in the ingestedFlushable, we
1555 1 : // need to acquire the logLock, and not release it for that duration. Since
1556 1 : // UpdateVersionLocked acquires it anyway, we create the VersionEdit for
1557 1 : // ingestedFlushable outside runCompaction. For all other flush cases, we
1558 1 : // construct the VersionEdit inside runCompaction.
1559 1 : var compactionErr error
1560 1 : if c.kind != compactionKindIngestedFlushable {
1561 1 : ve, stats, compactionErr = d.runCompaction(jobID, c)
1562 1 : }
1563 :
1564 1 : err = d.mu.versions.UpdateVersionLocked(func() (versionUpdate, error) {
1565 1 : err := compactionErr
1566 1 : if c.kind == compactionKindIngestedFlushable {
1567 1 : ve, err = d.runIngestFlush(c)
1568 1 : }
1569 1 : info.Duration = d.timeNow().Sub(startTime)
1570 1 : if err != nil {
1571 1 : return versionUpdate{}, err
1572 1 : }
1573 :
1574 1 : validateVersionEdit(ve, d.opts.Comparer.ValidateKey, d.opts.Comparer.FormatKey, d.opts.Logger)
1575 1 : for i := range ve.NewTables {
1576 1 : e := &ve.NewTables[i]
1577 1 : info.Output = append(info.Output, e.Meta.TableInfo())
1578 1 : // Ingested tables are not necessarily flushed to L0. Record the level of
1579 1 : // each ingested file explicitly.
1580 1 : if ingest {
1581 1 : info.IngestLevels = append(info.IngestLevels, e.Level)
1582 1 : }
1583 : }
1584 :
1585 : // The flush succeeded or it produced an empty sstable. In either case we
1586 : // want to bump the minimum unflushed log number to the log number of the
1587 : // oldest unflushed memtable.
1588 1 : ve.MinUnflushedLogNum = minUnflushedLogNum
1589 1 : if c.kind != compactionKindIngestedFlushable {
1590 1 : l0Metrics := c.metrics[0]
1591 1 : if d.opts.DisableWAL {
1592 1 : // If the WAL is disabled, every flushable has a zero [logSize],
1593 1 : // resulting in zero bytes in. Instead, use the number of bytes we
1594 1 : // flushed as the BytesIn. This ensures we get a reasonable w-amp
1595 1 : // calculation even when the WAL is disabled.
1596 1 : l0Metrics.TableBytesIn = l0Metrics.TableBytesFlushed + l0Metrics.BlobBytesFlushed
1597 1 : } else {
1598 1 : for i := 0; i < n; i++ {
1599 1 : l0Metrics.TableBytesIn += d.mu.mem.queue[i].logSize
1600 1 : }
1601 : }
1602 1 : } else {
1603 1 : // c.kind == compactionKindIngestedFlushable && we could have deleted files due
1604 1 : // to ingest-time splits or excises.
1605 1 : ingestFlushable := c.flushing[0].flushable.(*ingestedFlushable)
1606 1 : for c2 := range d.mu.compact.inProgress {
1607 1 : // Check if this compaction overlaps with the excise span. Note that just
1608 1 : // checking if the inputs individually overlap with the excise span
1609 1 : // isn't sufficient; for instance, a compaction could have [a,b] and [e,f]
1610 1 : // as inputs and write it all out as [a,b,e,f] in one sstable. If we're
1611 1 : // doing a [c,d) excise at the same time as this compaction, we will have
1612 1 : // to error out the whole compaction as we can't guarantee it hasn't/won't
1613 1 : // write a file overlapping with the excise span.
1614 1 : if ingestFlushable.exciseSpan.OverlapsInternalKeyRange(d.cmp, c2.smallest, c2.largest) {
1615 1 : c2.cancel.Store(true)
1616 1 : }
1617 : }
1618 :
1619 1 : if len(ve.DeletedTables) > 0 {
1620 1 : // Iterate through all other compactions, and check if their inputs have
1621 1 : // been replaced due to an ingest-time split or excise. In that case,
1622 1 : // cancel the compaction.
1623 1 : for c2 := range d.mu.compact.inProgress {
1624 1 : for i := range c2.inputs {
1625 1 : for f := range c2.inputs[i].files.All() {
1626 1 : if _, ok := ve.DeletedTables[manifest.DeletedTableEntry{FileNum: f.TableNum, Level: c2.inputs[i].level}]; ok {
1627 1 : c2.cancel.Store(true)
1628 1 : break
1629 : }
1630 : }
1631 : }
1632 : }
1633 : }
1634 : }
1635 1 : return versionUpdate{
1636 1 : VE: ve,
1637 1 : JobID: jobID,
1638 1 : Metrics: c.metrics,
1639 1 : InProgressCompactionsFn: func() []compactionInfo { return d.getInProgressCompactionInfoLocked(c) },
1640 : }, nil
1641 : })
1642 :
1643 : // If err != nil, then the flush will be retried, and we will recalculate
1644 : // these metrics.
1645 1 : if err == nil {
1646 1 : d.mu.snapshots.cumulativePinnedCount += stats.CumulativePinnedKeys
1647 1 : d.mu.snapshots.cumulativePinnedSize += stats.CumulativePinnedSize
1648 1 : d.mu.versions.metrics.Keys.MissizedTombstonesCount += stats.CountMissizedDels
1649 1 : }
1650 :
1651 1 : d.clearCompactingState(c, err != nil)
1652 1 : delete(d.mu.compact.inProgress, c)
1653 1 : d.mu.versions.incrementCompactions(c.kind, c.extraLevels, c.pickerMetrics, c.bytesWritten.Load(), err)
1654 1 :
1655 1 : var flushed flushableList
1656 1 : if err == nil {
1657 1 : flushed = d.mu.mem.queue[:n]
1658 1 : d.mu.mem.queue = d.mu.mem.queue[n:]
1659 1 : d.updateReadStateLocked(d.opts.DebugCheck)
1660 1 : d.updateTableStatsLocked(ve.NewTables)
1661 1 : if ingest {
1662 1 : d.mu.versions.metrics.Flush.AsIngestCount++
1663 1 : for _, l := range c.metrics {
1664 1 : if l != nil {
1665 1 : d.mu.versions.metrics.Flush.AsIngestBytes += l.TableBytesIngested
1666 1 : d.mu.versions.metrics.Flush.AsIngestTableCount += l.TablesIngested
1667 1 : }
1668 : }
1669 : }
1670 1 : d.maybeTransitionSnapshotsToFileOnlyLocked()
1671 : }
1672 : // Signal FlushEnd after installing the new readState. This helps for unit
1673 : // tests that use the callback to trigger a read using an iterator with
1674 : // IterOptions.OnlyReadGuaranteedDurable.
1675 1 : info.Err = err
1676 1 : if info.Err == nil && len(ve.NewTables) == 0 {
1677 1 : info.Err = errEmptyTable
1678 1 : }
1679 1 : info.Done = true
1680 1 : info.TotalDuration = d.timeNow().Sub(startTime)
1681 1 : d.opts.EventListener.FlushEnd(info)
1682 1 :
1683 1 : // The order of these operations matters here for ease of testing.
1684 1 : // Removing the reader reference first allows tests to be guaranteed that
1685 1 : // the memtable reservation has been released by the time a synchronous
1686 1 : // flush returns. readerUnrefLocked may also produce obsolete files so the
1687 1 : // call to deleteObsoleteFiles must happen after it.
1688 1 : for i := range flushed {
1689 1 : flushed[i].readerUnrefLocked(true)
1690 1 : }
1691 :
1692 1 : d.deleteObsoleteFiles(jobID)
1693 1 :
1694 1 : // Mark all the memtables we flushed as flushed.
1695 1 : for i := range flushed {
1696 1 : close(flushed[i].flushed)
1697 1 : }
1698 :
1699 1 : return inputBytes, err
1700 : }
1701 :
1702 : // maybeTransitionSnapshotsToFileOnlyLocked transitions any "eventually
1703 : // file-only" snapshots to be file-only if all their visible state has been
1704 : // flushed to sstables.
1705 : //
1706 : // REQUIRES: d.mu.
1707 1 : func (d *DB) maybeTransitionSnapshotsToFileOnlyLocked() {
1708 1 : earliestUnflushedSeqNum := d.getEarliestUnflushedSeqNumLocked()
1709 1 : currentVersion := d.mu.versions.currentVersion()
1710 1 : for s := d.mu.snapshots.root.next; s != &d.mu.snapshots.root; {
1711 1 : if s.efos == nil {
1712 1 : s = s.next
1713 1 : continue
1714 : }
1715 1 : overlapsFlushable := false
1716 1 : if base.Visible(earliestUnflushedSeqNum, s.efos.seqNum, base.SeqNumMax) {
1717 1 : // There are some unflushed keys that are still visible to the EFOS.
1718 1 : // Check if any memtables older than the EFOS contain keys within a
1719 1 : // protected range of the EFOS. If no, we can transition.
1720 1 : protectedRanges := make([]bounded, len(s.efos.protectedRanges))
1721 1 : for i := range s.efos.protectedRanges {
1722 1 : protectedRanges[i] = s.efos.protectedRanges[i]
1723 1 : }
1724 1 : for i := range d.mu.mem.queue {
1725 1 : if !base.Visible(d.mu.mem.queue[i].logSeqNum, s.efos.seqNum, base.SeqNumMax) {
1726 0 : // All keys in this memtable are newer than the EFOS. Skip this
1727 0 : // memtable.
1728 0 : continue
1729 : }
1730 : // NB: computePossibleOverlaps could have false positives, such as if
1731 : // the flushable is a flushable ingest and not a memtable. In that
1732 : // case we don't open the sstables to check; we just pessimistically
1733 : // assume an overlap.
1734 1 : d.mu.mem.queue[i].computePossibleOverlaps(func(b bounded) shouldContinue {
1735 1 : overlapsFlushable = true
1736 1 : return stopIteration
1737 1 : }, protectedRanges...)
1738 1 : if overlapsFlushable {
1739 1 : break
1740 : }
1741 : }
1742 : }
1743 1 : if overlapsFlushable {
1744 1 : s = s.next
1745 1 : continue
1746 : }
1747 1 : currentVersion.Ref()
1748 1 :
1749 1 : // NB: s.efos.transitionToFileOnlySnapshot could close s, in which
1750 1 : // case s.next would be nil. Save it before calling it.
1751 1 : next := s.next
1752 1 : _ = s.efos.transitionToFileOnlySnapshot(currentVersion)
1753 1 : s = next
1754 : }
1755 : }
1756 :
1757 : // maybeScheduleCompactionAsync should be used when
1758 : // we want to possibly schedule a compaction, but don't
1759 : // want to eat the cost of running maybeScheduleCompaction.
1760 : // This method should be launched in a separate goroutine.
1761 : // d.mu must not be held when this is called.
1762 0 : func (d *DB) maybeScheduleCompactionAsync() {
1763 0 : defer d.compactionSchedulers.Done()
1764 0 :
1765 0 : d.mu.Lock()
1766 0 : d.maybeScheduleCompaction()
1767 0 : d.mu.Unlock()
1768 0 : }
1769 :
1770 : // maybeScheduleCompaction schedules a compaction if necessary.
1771 : //
1772 : // WARNING: maybeScheduleCompaction and Schedule must be the only ways that
1773 : // any compactions are run. These ensure that the pickedCompactionCache is
1774 : // used and not stale (by ensuring invalidation is done).
1775 : //
1776 : // Even compactions that are not scheduled by the CompactionScheduler must be
1777 : // run using maybeScheduleCompaction, since starting those compactions needs
1778 : // to invalidate the pickedCompactionCache.
1779 : //
1780 : // Requires d.mu to be held.
1781 1 : func (d *DB) maybeScheduleCompaction() {
1782 1 : d.mu.versions.logLock()
1783 1 : defer d.mu.versions.logUnlock()
1784 1 : env := d.makeCompactionEnvLocked()
1785 1 : if env == nil {
1786 1 : return
1787 1 : }
1788 : // env.inProgressCompactions will become stale once we pick a compaction, so
1789 : // it needs to be kept fresh. Also, the pickedCompaction in the
1790 : // pickedCompactionCache is not valid if we pick a compaction before using
1791 : // it, since those earlier compactions can mark the same file as compacting.
1792 :
1793 : // Delete-only compactions are expected to be cheap and reduce future
1794 : // compaction work, so schedule them directly instead of using the
1795 : // CompactionScheduler.
1796 1 : if d.tryScheduleDeleteOnlyCompaction() {
1797 1 : env.inProgressCompactions = d.getInProgressCompactionInfoLocked(nil)
1798 1 : d.mu.versions.pickedCompactionCache.invalidate()
1799 1 : }
1800 : // Download compactions have their own concurrency and do not currently
1801 : // interact with CompactionScheduler.
1802 : //
1803 : // TODO(sumeer): integrate with CompactionScheduler, since these consume
1804 : // disk write bandwidth.
1805 1 : if d.tryScheduleDownloadCompactions(*env, d.opts.MaxConcurrentDownloads()) {
1806 1 : env.inProgressCompactions = d.getInProgressCompactionInfoLocked(nil)
1807 1 : d.mu.versions.pickedCompactionCache.invalidate()
1808 1 : }
1809 : // The remaining compactions are scheduled by the CompactionScheduler.
1810 1 : if d.mu.versions.pickedCompactionCache.isWaiting() {
1811 1 : // CompactionScheduler already knows that the DB is waiting to run a
1812 1 : // compaction.
1813 1 : return
1814 1 : }
1815 : // INVARIANT: !pickedCompactionCache.isWaiting. The following loop will
1816 : // either exit after successfully starting all the compactions it can pick,
1817 : // or will exit with one pickedCompaction in the cache, and isWaiting=true.
1818 1 : for {
1819 1 : // Do not have a pickedCompaction in the cache.
1820 1 : pc := d.pickAnyCompaction(*env)
1821 1 : if pc == nil {
1822 1 : return
1823 1 : }
1824 1 : success, grantHandle := d.opts.Experimental.CompactionScheduler.TrySchedule()
1825 1 : if !success {
1826 1 : // Can't run now, but remember this pickedCompaction in the cache.
1827 1 : d.mu.versions.pickedCompactionCache.add(pc)
1828 1 : return
1829 1 : }
1830 1 : d.runPickedCompaction(pc, grantHandle)
1831 1 : env.inProgressCompactions = d.getInProgressCompactionInfoLocked(nil)
1832 : }
1833 : }
1834 :
1835 : // makeCompactionEnv attempts to create a compactionEnv necessary during
1836 : // compaction picking. If the DB is closed or marked as read-only,
1837 : // makeCompactionEnv returns nil to indicate that compactions may not be
1838 : // performed. Else, a new compactionEnv is constructed using the current DB
1839 : // state.
1840 : //
1841 : // Compaction picking needs a coherent view of a Version. For example, we need
1842 : // to exclude concurrent ingestions from making a decision on which level to
1843 : // ingest into that conflicts with our compaction decision.
1844 : //
1845 : // A pickedCompaction constructed using a compactionEnv must only be used if
1846 : // the latest Version has not changed.
1847 : //
1848 : // REQUIRES: d.mu and d.mu.versions.logLock are held.
1849 1 : func (d *DB) makeCompactionEnvLocked() *compactionEnv {
1850 1 : if d.closed.Load() != nil || d.opts.ReadOnly {
1851 1 : return nil
1852 1 : }
1853 1 : env := &compactionEnv{
1854 1 : diskAvailBytes: d.diskAvailBytes.Load(),
1855 1 : earliestSnapshotSeqNum: d.mu.snapshots.earliest(),
1856 1 : earliestUnflushedSeqNum: d.getEarliestUnflushedSeqNumLocked(),
1857 1 : inProgressCompactions: d.getInProgressCompactionInfoLocked(nil),
1858 1 : readCompactionEnv: readCompactionEnv{
1859 1 : readCompactions: &d.mu.compact.readCompactions,
1860 1 : flushing: d.mu.compact.flushing || d.passedFlushThreshold(),
1861 1 : rescheduleReadCompaction: &d.mu.compact.rescheduleReadCompaction,
1862 1 : },
1863 1 : }
1864 1 : if !d.problemSpans.IsEmpty() {
1865 1 : env.problemSpans = &d.problemSpans
1866 1 : }
1867 1 : return env
1868 : }
1869 :
1870 : // pickAnyCompaction tries to pick a manual or automatic compaction.
1871 1 : func (d *DB) pickAnyCompaction(env compactionEnv) (pc *pickedCompaction) {
1872 1 : // Pick a score-based compaction first, since a misshapen LSM is bad.
1873 1 : if !d.opts.DisableAutomaticCompactions {
1874 1 : if pc = d.mu.versions.picker.pickAutoScore(env); pc != nil {
1875 1 : return pc
1876 1 : }
1877 : }
1878 : // Pick a manual compaction, if any.
1879 1 : if pc = d.pickManualCompaction(env); pc != nil {
1880 1 : return pc
1881 1 : }
1882 1 : if !d.opts.DisableAutomaticCompactions {
1883 1 : return d.mu.versions.picker.pickAutoNonScore(env)
1884 1 : }
1885 1 : return nil
1886 : }
1887 :
1888 : // runPickedCompaction kicks off the provided pickedCompaction. In case the
1889 : // pickedCompaction is a manual compaction, the corresponding manualCompaction
1890 : // is removed from d.mu.compact.manual.
1891 : //
1892 : // REQUIRES: d.mu and d.mu.versions.logLock is held.
1893 1 : func (d *DB) runPickedCompaction(pc *pickedCompaction, grantHandle CompactionGrantHandle) {
1894 1 : var doneChannel chan error
1895 1 : if pc.manualID > 0 {
1896 1 : for i := range d.mu.compact.manual {
1897 1 : if d.mu.compact.manual[i].id == pc.manualID {
1898 1 : doneChannel = d.mu.compact.manual[i].done
1899 1 : d.mu.compact.manual = slices.Delete(d.mu.compact.manual, i, i+1)
1900 1 : d.mu.compact.manualLen.Store(int32(len(d.mu.compact.manual)))
1901 1 : break
1902 : }
1903 : }
1904 1 : if doneChannel == nil {
1905 0 : panic(errors.AssertionFailedf("did not find manual compaction with id %d", pc.manualID))
1906 : }
1907 : }
1908 :
1909 1 : d.mu.compact.compactingCount++
1910 1 : compaction := newCompaction(pc, d.opts, d.timeNow(), d.ObjProvider(), grantHandle, d.determineCompactionValueSeparation)
1911 1 : d.addInProgressCompaction(compaction)
1912 1 : go func() {
1913 1 : d.compact(compaction, doneChannel)
1914 1 : }()
1915 : }
1916 :
1917 : // Schedule implements DBForCompaction (it is called by the
1918 : // CompactionScheduler).
1919 1 : func (d *DB) Schedule(grantHandle CompactionGrantHandle) bool {
1920 1 : d.mu.Lock()
1921 1 : defer d.mu.Unlock()
1922 1 : d.mu.versions.logLock()
1923 1 : defer d.mu.versions.logUnlock()
1924 1 : isWaiting := d.mu.versions.pickedCompactionCache.isWaiting()
1925 1 : if !isWaiting {
1926 0 : return false
1927 0 : }
1928 1 : pc := d.mu.versions.pickedCompactionCache.getForRunning()
1929 1 : if pc == nil {
1930 1 : env := d.makeCompactionEnvLocked()
1931 1 : if env != nil {
1932 1 : pc = d.pickAnyCompaction(*env)
1933 1 : }
1934 1 : if pc == nil {
1935 0 : d.mu.versions.pickedCompactionCache.setNotWaiting()
1936 0 : return false
1937 0 : }
1938 : }
1939 : // INVARIANT: pc != nil and is not in the cache. isWaiting is true, since
1940 : // there may be more compactions to run.
1941 1 : d.runPickedCompaction(pc, grantHandle)
1942 1 : return true
1943 : }
1944 :
1945 : // GetWaitingCompaction implements DBForCompaction (it is called by the
1946 : // CompactionScheduler).
1947 1 : func (d *DB) GetWaitingCompaction() (bool, WaitingCompaction) {
1948 1 : d.mu.Lock()
1949 1 : defer d.mu.Unlock()
1950 1 : d.mu.versions.logLock()
1951 1 : defer d.mu.versions.logUnlock()
1952 1 : isWaiting := d.mu.versions.pickedCompactionCache.isWaiting()
1953 1 : if !isWaiting {
1954 1 : return false, WaitingCompaction{}
1955 1 : }
1956 1 : pc := d.mu.versions.pickedCompactionCache.peek()
1957 1 : if pc == nil {
1958 1 : // Need to pick a compaction.
1959 1 : env := d.makeCompactionEnvLocked()
1960 1 : if env != nil {
1961 1 : pc = d.pickAnyCompaction(*env)
1962 1 : }
1963 1 : if pc == nil {
1964 1 : // Call setNotWaiting so that next call to GetWaitingCompaction can
1965 1 : // return early.
1966 1 : d.mu.versions.pickedCompactionCache.setNotWaiting()
1967 1 : return false, WaitingCompaction{}
1968 1 : } else {
1969 1 : d.mu.versions.pickedCompactionCache.add(pc)
1970 1 : }
1971 : }
1972 : // INVARIANT: pc != nil and is in the cache.
1973 1 : return true, makeWaitingCompaction(pc.manualID > 0, pc.kind, pc.score)
1974 : }
1975 :
1976 : // GetAllowedWithoutPermission implements DBForCompaction (it is called by the
1977 : // CompactionScheduler).
1978 1 : func (d *DB) GetAllowedWithoutPermission() int {
1979 1 : allowedBasedOnBacklog := int(d.mu.versions.curCompactionConcurrency.Load())
1980 1 : allowedBasedOnManual := 0
1981 1 : manualBacklog := int(d.mu.compact.manualLen.Load())
1982 1 : if manualBacklog > 0 {
1983 1 : _, maxAllowed := d.opts.CompactionConcurrencyRange()
1984 1 : allowedBasedOnManual = min(maxAllowed, manualBacklog+allowedBasedOnBacklog)
1985 1 : }
1986 1 : return max(allowedBasedOnBacklog, allowedBasedOnManual)
1987 : }
1988 :
1989 : // tryScheduleDownloadCompactions tries to start download compactions.
1990 : //
1991 : // Requires d.mu to be held. Updates d.mu.compact.downloads.
1992 : //
1993 : // Returns true iff at least one compaction was started.
1994 1 : func (d *DB) tryScheduleDownloadCompactions(env compactionEnv, maxConcurrentDownloads int) bool {
1995 1 : started := false
1996 1 : vers := d.mu.versions.currentVersion()
1997 1 : for i := 0; i < len(d.mu.compact.downloads); {
1998 1 : if d.mu.compact.downloadingCount >= maxConcurrentDownloads {
1999 1 : break
2000 : }
2001 1 : download := d.mu.compact.downloads[i]
2002 1 : switch d.tryLaunchDownloadCompaction(download, vers, d.mu.versions.l0Organizer, env, maxConcurrentDownloads) {
2003 1 : case launchedCompaction:
2004 1 : started = true
2005 1 : continue
2006 0 : case didNotLaunchCompaction:
2007 0 : // See if we can launch a compaction for another download task.
2008 0 : i++
2009 1 : case downloadTaskCompleted:
2010 1 : // Task is completed and must be removed.
2011 1 : d.mu.compact.downloads = slices.Delete(d.mu.compact.downloads, i, i+1)
2012 : }
2013 : }
2014 1 : return started
2015 : }
2016 :
2017 1 : func (d *DB) pickManualCompaction(env compactionEnv) (pc *pickedCompaction) {
2018 1 : v := d.mu.versions.currentVersion()
2019 1 : for len(d.mu.compact.manual) > 0 {
2020 1 : manual := d.mu.compact.manual[0]
2021 1 : pc, retryLater := newPickedManualCompaction(v, d.mu.versions.l0Organizer, d.opts, env, d.mu.versions.picker.getBaseLevel(), manual)
2022 1 : if pc != nil {
2023 1 : return pc
2024 1 : }
2025 1 : if retryLater {
2026 1 : // We are not able to run this manual compaction at this time.
2027 1 : // Inability to run the head blocks later manual compactions.
2028 1 : manual.retries++
2029 1 : return nil
2030 1 : }
2031 : // Manual compaction is a no-op. Signal that it's complete.
2032 1 : manual.done <- nil
2033 1 : d.mu.compact.manual = d.mu.compact.manual[1:]
2034 1 : d.mu.compact.manualLen.Store(int32(len(d.mu.compact.manual)))
2035 : }
2036 1 : return nil
2037 : }
2038 :
2039 : // tryScheduleDeleteOnlyCompaction tries to kick off a delete-only compaction
2040 : // for all files that can be deleted as suggested by deletionHints.
2041 : //
2042 : // Requires d.mu to be held. Updates d.mu.compact.deletionHints.
2043 : //
2044 : // Returns true iff a compaction was started.
2045 1 : func (d *DB) tryScheduleDeleteOnlyCompaction() bool {
2046 1 : if d.opts.private.disableDeleteOnlyCompactions || d.opts.DisableAutomaticCompactions ||
2047 1 : len(d.mu.compact.deletionHints) == 0 {
2048 1 : return false
2049 1 : }
2050 1 : if _, maxConcurrency := d.opts.CompactionConcurrencyRange(); d.mu.compact.compactingCount >= maxConcurrency {
2051 1 : return false
2052 1 : }
2053 1 : v := d.mu.versions.currentVersion()
2054 1 : snapshots := d.mu.snapshots.toSlice()
2055 1 : // We need to save the value of exciseEnabled in the compaction itself, as
2056 1 : // it can change dynamically between now and when the compaction runs.
2057 1 : exciseEnabled := d.FormatMajorVersion() >= FormatVirtualSSTables &&
2058 1 : d.opts.Experimental.EnableDeleteOnlyCompactionExcises != nil && d.opts.Experimental.EnableDeleteOnlyCompactionExcises()
2059 1 : inputs, resolvedHints, unresolvedHints := checkDeleteCompactionHints(d.cmp, v, d.mu.compact.deletionHints, snapshots, exciseEnabled)
2060 1 : d.mu.compact.deletionHints = unresolvedHints
2061 1 :
2062 1 : if len(inputs) > 0 {
2063 1 : c := newDeleteOnlyCompaction(d.opts, v, inputs, d.timeNow(), resolvedHints, exciseEnabled)
2064 1 : d.mu.compact.compactingCount++
2065 1 : d.addInProgressCompaction(c)
2066 1 : go d.compact(c, nil)
2067 1 : return true
2068 1 : }
2069 1 : return false
2070 : }
2071 :
2072 : // deleteCompactionHintType indicates whether the deleteCompactionHint was
2073 : // generated from a span containing a range del (point key only), a range key
2074 : // delete (range key only), or both a point and range key.
2075 : type deleteCompactionHintType uint8
2076 :
2077 : const (
2078 : // NOTE: While these are primarily used as enumeration types, they are also
2079 : // used for some bitwise operations. Care should be taken when updating.
2080 : deleteCompactionHintTypeUnknown deleteCompactionHintType = iota
2081 : deleteCompactionHintTypePointKeyOnly
2082 : deleteCompactionHintTypeRangeKeyOnly
2083 : deleteCompactionHintTypePointAndRangeKey
2084 : )
2085 :
2086 : // String implements fmt.Stringer.
2087 1 : func (h deleteCompactionHintType) String() string {
2088 1 : switch h {
2089 0 : case deleteCompactionHintTypeUnknown:
2090 0 : return "unknown"
2091 1 : case deleteCompactionHintTypePointKeyOnly:
2092 1 : return "point-key-only"
2093 1 : case deleteCompactionHintTypeRangeKeyOnly:
2094 1 : return "range-key-only"
2095 1 : case deleteCompactionHintTypePointAndRangeKey:
2096 1 : return "point-and-range-key"
2097 0 : default:
2098 0 : panic(fmt.Sprintf("unknown hint type: %d", h))
2099 : }
2100 : }
2101 :
2102 : // compactionHintFromKeys returns a deleteCompactionHintType given a slice of
2103 : // keyspan.Keys.
2104 1 : func compactionHintFromKeys(keys []keyspan.Key) deleteCompactionHintType {
2105 1 : var hintType deleteCompactionHintType
2106 1 : for _, k := range keys {
2107 1 : switch k.Kind() {
2108 1 : case base.InternalKeyKindRangeDelete:
2109 1 : hintType |= deleteCompactionHintTypePointKeyOnly
2110 1 : case base.InternalKeyKindRangeKeyDelete:
2111 1 : hintType |= deleteCompactionHintTypeRangeKeyOnly
2112 0 : default:
2113 0 : panic(fmt.Sprintf("unsupported key kind: %s", k.Kind()))
2114 : }
2115 : }
2116 1 : return hintType
2117 : }
2118 :
2119 : // A deleteCompactionHint records a user key and sequence number span that has been
2120 : // deleted by a range tombstone. A hint is recorded if at least one sstable
2121 : // falls completely within both the user key and sequence number spans.
2122 : // Once the tombstones and the observed completely-contained sstables fall
2123 : // into the same snapshot stripe, a delete-only compaction may delete any
2124 : // sstables within the range.
2125 : type deleteCompactionHint struct {
2126 : // The type of key span that generated this hint (point key, range key, or
2127 : // both).
2128 : hintType deleteCompactionHintType
2129 : // start and end are user keys specifying a key range [start, end) of
2130 : // deleted keys.
2131 : start []byte
2132 : end []byte
2133 : // The level of the file containing the range tombstone(s) when the hint
2134 : // was created. Only lower levels need to be searched for files that may
2135 : // be deleted.
2136 : tombstoneLevel int
2137 : // The file containing the range tombstone(s) that created the hint.
2138 : tombstoneFile *manifest.TableMetadata
2139 : // The smallest and largest sequence numbers of the abutting tombstones
2140 : // merged to form this hint. All of a tables' keys must be less than the
2141 : // tombstone smallest sequence number to be deleted. All of a tables'
2142 : // sequence numbers must fall into the same snapshot stripe as the
2143 : // tombstone largest sequence number to be deleted.
2144 : tombstoneLargestSeqNum base.SeqNum
2145 : tombstoneSmallestSeqNum base.SeqNum
2146 : // The smallest sequence number of a sstable that was found to be covered
2147 : // by this hint. The hint cannot be resolved until this sequence number is
2148 : // in the same snapshot stripe as the largest tombstone sequence number.
2149 : // This is set when a hint is created, so the LSM may look different and
2150 : // notably no longer contain the sstable that contained the key at this
2151 : // sequence number.
2152 : fileSmallestSeqNum base.SeqNum
2153 : }
2154 :
2155 : type deletionHintOverlap int8
2156 :
2157 : const (
2158 : // hintDoesNotApply indicates that the hint does not apply to the file.
2159 : hintDoesNotApply deletionHintOverlap = iota
2160 : // hintExcisesFile indicates that the hint excises a portion of the file,
2161 : // and the format major version of the DB supports excises.
2162 : hintExcisesFile
2163 : // hintDeletesFile indicates that the hint deletes the entirety of the file.
2164 : hintDeletesFile
2165 : )
2166 :
2167 1 : func (h deleteCompactionHint) String() string {
2168 1 : return fmt.Sprintf(
2169 1 : "L%d.%s %s-%s seqnums(tombstone=%d-%d, file-smallest=%d, type=%s)",
2170 1 : h.tombstoneLevel, h.tombstoneFile.TableNum, h.start, h.end,
2171 1 : h.tombstoneSmallestSeqNum, h.tombstoneLargestSeqNum, h.fileSmallestSeqNum,
2172 1 : h.hintType,
2173 1 : )
2174 1 : }
2175 :
2176 : func (h *deleteCompactionHint) canDeleteOrExcise(
2177 : cmp Compare, m *manifest.TableMetadata, snapshots compact.Snapshots, exciseEnabled bool,
2178 1 : ) deletionHintOverlap {
2179 1 : // The file can only be deleted if all of its keys are older than the
2180 1 : // earliest tombstone aggregated into the hint. Note that we use
2181 1 : // m.LargestSeqNumAbsolute, not m.LargestSeqNum. Consider a compaction that
2182 1 : // zeroes sequence numbers. A compaction may zero the sequence number of a
2183 1 : // key with a sequence number > h.tombstoneSmallestSeqNum and set it to
2184 1 : // zero. If we looked at m.LargestSeqNum, the resulting output file would
2185 1 : // appear to not contain any keys more recent than the oldest tombstone. To
2186 1 : // avoid this error, the largest pre-zeroing sequence number is maintained
2187 1 : // in LargestSeqNumAbsolute and used here to make the determination whether
2188 1 : // the file's keys are older than all of the hint's tombstones.
2189 1 : if m.LargestSeqNumAbsolute >= h.tombstoneSmallestSeqNum || m.SmallestSeqNum < h.fileSmallestSeqNum {
2190 1 : return hintDoesNotApply
2191 1 : }
2192 :
2193 : // The file's oldest key must be in the same snapshot stripe as the
2194 : // newest tombstone. NB: We already checked the hint's sequence numbers,
2195 : // but this file's oldest sequence number might be lower than the hint's
2196 : // smallest sequence number despite the file falling within the key range
2197 : // if this file was constructed after the hint by a compaction.
2198 1 : if snapshots.Index(h.tombstoneLargestSeqNum) != snapshots.Index(m.SmallestSeqNum) {
2199 0 : return hintDoesNotApply
2200 0 : }
2201 :
2202 1 : switch h.hintType {
2203 1 : case deleteCompactionHintTypePointKeyOnly:
2204 1 : // A hint generated by a range del span cannot delete tables that contain
2205 1 : // range keys.
2206 1 : if m.HasRangeKeys {
2207 0 : return hintDoesNotApply
2208 0 : }
2209 1 : case deleteCompactionHintTypeRangeKeyOnly:
2210 1 : // A hint generated by a range key del span cannot delete tables that
2211 1 : // contain point keys.
2212 1 : if m.HasPointKeys {
2213 1 : return hintDoesNotApply
2214 1 : }
2215 1 : case deleteCompactionHintTypePointAndRangeKey:
2216 : // A hint from a span that contains both range dels *and* range keys can
2217 : // only be deleted if both bounds fall within the hint. The next check takes
2218 : // care of this.
2219 0 : default:
2220 0 : panic(fmt.Sprintf("pebble: unknown delete compaction hint type: %d", h.hintType))
2221 : }
2222 1 : if cmp(h.start, m.Smallest().UserKey) <= 0 &&
2223 1 : base.UserKeyExclusive(h.end).CompareUpperBounds(cmp, m.UserKeyBounds().End) >= 0 {
2224 1 : return hintDeletesFile
2225 1 : }
2226 1 : if !exciseEnabled {
2227 1 : // The file's keys must be completely contained within the hint range; excises
2228 1 : // aren't allowed.
2229 1 : return hintDoesNotApply
2230 1 : }
2231 : // Check for any overlap. In cases of partial overlap, we can excise the part of the file
2232 : // that overlaps with the deletion hint.
2233 1 : if cmp(h.end, m.Smallest().UserKey) > 0 &&
2234 1 : (m.UserKeyBounds().End.CompareUpperBounds(cmp, base.UserKeyInclusive(h.start)) >= 0) {
2235 1 : return hintExcisesFile
2236 1 : }
2237 1 : return hintDoesNotApply
2238 : }
2239 :
2240 : // checkDeleteCompactionHints checks the passed-in deleteCompactionHints for those that
2241 : // can be resolved and those that cannot. A hint is considered resolved when its largest
2242 : // tombstone sequence number and the smallest sequence number of covered files fall in
2243 : // the same snapshot stripe. No more than maxHintsPerDeleteOnlyCompaction will be resolved
2244 : // per method call. Resolved and unresolved hints are returned in separate return values.
2245 : // The files that the resolved hints apply to, are returned as compactionLevels.
2246 : func checkDeleteCompactionHints(
2247 : cmp Compare,
2248 : v *manifest.Version,
2249 : hints []deleteCompactionHint,
2250 : snapshots compact.Snapshots,
2251 : exciseEnabled bool,
2252 1 : ) (levels []compactionLevel, resolved, unresolved []deleteCompactionHint) {
2253 1 : var files map[*manifest.TableMetadata]bool
2254 1 : var byLevel [numLevels][]*manifest.TableMetadata
2255 1 :
2256 1 : // Delete-only compactions can be quadratic (O(mn)) in terms of runtime
2257 1 : // where m = number of files in the delete-only compaction and n = number
2258 1 : // of resolved hints. To prevent these from growing unbounded, we cap
2259 1 : // the number of hints we resolve for one delete-only compaction. This
2260 1 : // cap only applies if exciseEnabled == true.
2261 1 : const maxHintsPerDeleteOnlyCompaction = 10
2262 1 :
2263 1 : unresolvedHints := hints[:0]
2264 1 : // Lazily populate resolvedHints, similar to files above.
2265 1 : resolvedHints := make([]deleteCompactionHint, 0)
2266 1 : for _, h := range hints {
2267 1 : // Check each compaction hint to see if it's resolvable. Resolvable
2268 1 : // hints are removed and trigger a delete-only compaction if any files
2269 1 : // in the current LSM still meet their criteria. Unresolvable hints
2270 1 : // are saved and don't trigger a delete-only compaction.
2271 1 : //
2272 1 : // When a compaction hint is created, the sequence numbers of the
2273 1 : // range tombstones and the covered file with the oldest key are
2274 1 : // recorded. The largest tombstone sequence number and the smallest
2275 1 : // file sequence number must be in the same snapshot stripe for the
2276 1 : // hint to be resolved. The below graphic models a compaction hint
2277 1 : // covering the keyspace [b, r). The hint completely contains two
2278 1 : // files, 000002 and 000003. The file 000003 contains the lowest
2279 1 : // covered sequence number at #90. The tombstone b.RANGEDEL.230:h has
2280 1 : // the highest tombstone sequence number incorporated into the hint.
2281 1 : // The hint may be resolved only once the snapshots at #100, #180 and
2282 1 : // #210 are all closed. File 000001 is not included within the hint
2283 1 : // because it extends beyond the range tombstones in user key space.
2284 1 : //
2285 1 : // 250
2286 1 : //
2287 1 : // |-b...230:h-|
2288 1 : // _____________________________________________________ snapshot #210
2289 1 : // 200 |--h.RANGEDEL.200:r--|
2290 1 : //
2291 1 : // _____________________________________________________ snapshot #180
2292 1 : //
2293 1 : // 150 +--------+
2294 1 : // +---------+ | 000003 |
2295 1 : // | 000002 | | |
2296 1 : // +_________+ | |
2297 1 : // 100_____________________|________|___________________ snapshot #100
2298 1 : // +--------+
2299 1 : // _____________________________________________________ snapshot #70
2300 1 : // +---------------+
2301 1 : // 50 | 000001 |
2302 1 : // | |
2303 1 : // +---------------+
2304 1 : // ______________________________________________________________
2305 1 : // a b c d e f g h i j k l m n o p q r s t u v w x y z
2306 1 :
2307 1 : if snapshots.Index(h.tombstoneLargestSeqNum) != snapshots.Index(h.fileSmallestSeqNum) ||
2308 1 : (len(resolvedHints) >= maxHintsPerDeleteOnlyCompaction && exciseEnabled) {
2309 1 : // Cannot resolve yet.
2310 1 : unresolvedHints = append(unresolvedHints, h)
2311 1 : continue
2312 : }
2313 :
2314 : // The hint h will be resolved and dropped, if it either affects no files at all
2315 : // or if the number of files it creates (eg. through excision) is less than or
2316 : // equal to the number of files it deletes. First, determine how many files are
2317 : // affected by this hint.
2318 1 : filesDeletedByCurrentHint := 0
2319 1 : var filesDeletedByLevel [7][]*manifest.TableMetadata
2320 1 : for l := h.tombstoneLevel + 1; l < numLevels; l++ {
2321 1 : for m := range v.Overlaps(l, base.UserKeyBoundsEndExclusive(h.start, h.end)).All() {
2322 1 : doesHintApply := h.canDeleteOrExcise(cmp, m, snapshots, exciseEnabled)
2323 1 : if m.IsCompacting() || doesHintApply == hintDoesNotApply || files[m] {
2324 1 : continue
2325 : }
2326 1 : switch doesHintApply {
2327 1 : case hintDeletesFile:
2328 1 : filesDeletedByCurrentHint++
2329 1 : case hintExcisesFile:
2330 1 : // Account for the original file being deleted.
2331 1 : filesDeletedByCurrentHint++
2332 1 : // An excise could produce up to 2 new files. If the hint
2333 1 : // leaves a fragment of the file on the left, decrement
2334 1 : // the counter once. If the hint leaves a fragment of the
2335 1 : // file on the right, decrement the counter once.
2336 1 : if cmp(h.start, m.Smallest().UserKey) > 0 {
2337 1 : filesDeletedByCurrentHint--
2338 1 : }
2339 1 : if m.UserKeyBounds().End.IsUpperBoundFor(cmp, h.end) {
2340 1 : filesDeletedByCurrentHint--
2341 1 : }
2342 : }
2343 1 : filesDeletedByLevel[l] = append(filesDeletedByLevel[l], m)
2344 : }
2345 : }
2346 1 : if filesDeletedByCurrentHint < 0 {
2347 1 : // This hint does not delete a sufficient number of files to warrant
2348 1 : // a delete-only compaction at this stage. Drop it (ie. don't add it
2349 1 : // to either resolved or unresolved hints) so it doesn't stick around
2350 1 : // forever.
2351 1 : continue
2352 : }
2353 : // This hint will be resolved and dropped.
2354 1 : for l := h.tombstoneLevel + 1; l < numLevels; l++ {
2355 1 : byLevel[l] = append(byLevel[l], filesDeletedByLevel[l]...)
2356 1 : for _, m := range filesDeletedByLevel[l] {
2357 1 : if files == nil {
2358 1 : // Construct files lazily, assuming most calls will not
2359 1 : // produce delete-only compactions.
2360 1 : files = make(map[*manifest.TableMetadata]bool)
2361 1 : }
2362 1 : files[m] = true
2363 : }
2364 : }
2365 1 : resolvedHints = append(resolvedHints, h)
2366 : }
2367 :
2368 1 : var compactLevels []compactionLevel
2369 1 : for l, files := range byLevel {
2370 1 : if len(files) == 0 {
2371 1 : continue
2372 : }
2373 1 : compactLevels = append(compactLevels, compactionLevel{
2374 1 : level: l,
2375 1 : files: manifest.NewLevelSliceKeySorted(cmp, files),
2376 1 : })
2377 : }
2378 1 : return compactLevels, resolvedHints, unresolvedHints
2379 : }
2380 :
2381 1 : func (d *DB) compactionPprofLabels(c *compaction) pprof.LabelSet {
2382 1 : activity := "compact"
2383 1 : if len(c.flushing) != 0 {
2384 0 : activity = "flush"
2385 0 : }
2386 1 : level := "L?"
2387 1 : // Delete-only compactions don't have an output level.
2388 1 : if c.outputLevel != nil {
2389 1 : level = fmt.Sprintf("L%d", c.outputLevel.level)
2390 1 : }
2391 1 : if kc := d.opts.Experimental.UserKeyCategories; kc.Len() > 0 {
2392 0 : cat := kc.CategorizeKeyRange(c.smallest.UserKey, c.largest.UserKey)
2393 0 : return pprof.Labels("pebble", activity, "output-level", level, "key-type", cat)
2394 0 : }
2395 1 : return pprof.Labels("pebble", activity, "output-level", level)
2396 : }
2397 :
2398 : // compact runs one compaction and maybe schedules another call to compact.
2399 1 : func (d *DB) compact(c *compaction, errChannel chan error) {
2400 1 : pprof.Do(context.Background(), d.compactionPprofLabels(c), func(context.Context) {
2401 1 : d.mu.Lock()
2402 1 : c.grantHandle.Started()
2403 1 : if err := d.compact1(c, errChannel); err != nil {
2404 1 : d.handleCompactFailure(c, err)
2405 1 : }
2406 1 : if c.isDownload {
2407 1 : d.mu.compact.downloadingCount--
2408 1 : } else {
2409 1 : d.mu.compact.compactingCount--
2410 1 : }
2411 1 : delete(d.mu.compact.inProgress, c)
2412 1 : // Add this compaction's duration to the cumulative duration. NB: This
2413 1 : // must be atomic with the above removal of c from
2414 1 : // d.mu.compact.InProgress to ensure Metrics.Compact.Duration does not
2415 1 : // miss or double count a completing compaction's duration.
2416 1 : d.mu.compact.duration += d.timeNow().Sub(c.beganAt)
2417 1 : d.mu.Unlock()
2418 1 : // Done must not be called while holding any lock that needs to be
2419 1 : // acquired by Schedule. Also, it must be called after new Version has
2420 1 : // been installed, and metadata related to compactingCount and inProgress
2421 1 : // compactions has been updated. This is because when we are running at
2422 1 : // the limit of permitted compactions, Done can cause the
2423 1 : // CompactionScheduler to schedule another compaction. Note that the only
2424 1 : // compactions that may be scheduled by Done are those integrated with the
2425 1 : // CompactionScheduler.
2426 1 : c.grantHandle.Done()
2427 1 : c.grantHandle = nil
2428 1 : // The previous compaction may have produced too many files in a level, so
2429 1 : // reschedule another compaction if needed.
2430 1 : //
2431 1 : // The preceding Done call will not necessarily cause a compaction to be
2432 1 : // scheduled, so we also need to call maybeScheduleCompaction. And
2433 1 : // maybeScheduleCompaction encompasses all compactions, and not only those
2434 1 : // scheduled via the CompactionScheduler.
2435 1 : d.mu.Lock()
2436 1 : d.maybeScheduleCompaction()
2437 1 : d.mu.compact.cond.Broadcast()
2438 1 : d.mu.Unlock()
2439 : })
2440 : }
2441 :
2442 1 : func (d *DB) handleCompactFailure(c *compaction, err error) {
2443 1 : if errors.Is(err, ErrCancelledCompaction) {
2444 1 : // ErrCancelledCompaction is expected during normal operation, so we don't
2445 1 : // want to report it as a background error.
2446 1 : d.opts.Logger.Infof("%v", err)
2447 1 : return
2448 1 : }
2449 :
2450 : // Record problem spans for a short duration, unless the error is a corruption.
2451 1 : expiration := 30 * time.Second
2452 1 : if IsCorruptionError(err) {
2453 1 : // TODO(radu): ideally, we should be using the corruption reporting
2454 1 : // mechanism which has a tighter span for the corruption. We would need to
2455 1 : // somehow plumb the level of the file.
2456 1 : expiration = 5 * time.Minute
2457 1 : }
2458 1 : for i := range c.inputs {
2459 1 : level := c.inputs[i].level
2460 1 : if level == 0 {
2461 1 : // We do not set problem spans on L0, as they could block flushes.
2462 1 : continue
2463 : }
2464 1 : it := c.inputs[i].files.Iter()
2465 1 : for f := it.First(); f != nil; f = it.Next() {
2466 1 : d.problemSpans.Add(level, f.UserKeyBounds(), expiration)
2467 1 : }
2468 : }
2469 :
2470 : // TODO(peter): count consecutive compaction errors and backoff.
2471 1 : d.opts.EventListener.BackgroundError(err)
2472 : }
2473 :
2474 : // cleanupVersionEdit cleans up any on-disk artifacts that were created
2475 : // for the application of a versionEdit that is no longer going to be applied.
2476 : //
2477 : // d.mu must be held when calling this method.
2478 1 : func (d *DB) cleanupVersionEdit(ve *manifest.VersionEdit) {
2479 1 : obsoleteFiles := manifest.ObsoleteFiles{
2480 1 : TableBackings: make([]*manifest.TableBacking, 0, len(ve.NewTables)),
2481 1 : BlobFiles: make([]*manifest.BlobFileMetadata, 0, len(ve.NewBlobFiles)),
2482 1 : }
2483 1 : deletedTables := make(map[base.TableNum]struct{})
2484 1 : for key := range ve.DeletedTables {
2485 1 : deletedTables[key.FileNum] = struct{}{}
2486 1 : }
2487 1 : for i := range ve.NewBlobFiles {
2488 0 : obsoleteFiles.AddBlob(ve.NewBlobFiles[i])
2489 0 : d.mu.versions.zombieBlobs.Add(objectInfo{
2490 0 : fileInfo: fileInfo{
2491 0 : FileNum: base.DiskFileNum(ve.NewBlobFiles[i].FileID),
2492 0 : FileSize: ve.NewBlobFiles[i].Size,
2493 0 : },
2494 0 : isLocal: objstorage.IsLocalBlobFile(d.objProvider, base.DiskFileNum(ve.NewBlobFiles[i].FileID)),
2495 0 : })
2496 0 : }
2497 1 : for i := range ve.NewTables {
2498 1 : if ve.NewTables[i].Meta.Virtual {
2499 0 : // We handle backing files separately.
2500 0 : continue
2501 : }
2502 1 : if _, ok := deletedTables[ve.NewTables[i].Meta.TableNum]; ok {
2503 0 : // This file is being moved in this ve to a different level.
2504 0 : // Don't mark it as obsolete.
2505 0 : continue
2506 : }
2507 1 : obsoleteFiles.AddBacking(ve.NewTables[i].Meta.PhysicalMeta().TableBacking)
2508 : }
2509 1 : for i := range ve.CreatedBackingTables {
2510 0 : if ve.CreatedBackingTables[i].IsUnused() {
2511 0 : obsoleteFiles.AddBacking(ve.CreatedBackingTables[i])
2512 0 : }
2513 : }
2514 1 : for _, of := range obsoleteFiles.TableBackings {
2515 1 : // Add this file to zombie tables as well, as the versionSet
2516 1 : // asserts on whether every obsolete file was at one point
2517 1 : // marked zombie.
2518 1 : d.mu.versions.zombieTables.Add(objectInfo{
2519 1 : fileInfo: fileInfo{
2520 1 : FileNum: of.DiskFileNum,
2521 1 : FileSize: of.Size,
2522 1 : },
2523 1 : isLocal: objstorage.IsLocalTable(d.objProvider, of.DiskFileNum),
2524 1 : })
2525 1 : }
2526 1 : d.mu.versions.addObsoleteLocked(obsoleteFiles)
2527 : }
2528 :
2529 : // compact1 runs one compaction.
2530 : //
2531 : // d.mu must be held when calling this, but the mutex may be dropped and
2532 : // re-acquired during the course of this method.
2533 1 : func (d *DB) compact1(c *compaction, errChannel chan error) (err error) {
2534 1 : if errChannel != nil {
2535 1 : defer func() {
2536 1 : errChannel <- err
2537 1 : }()
2538 : }
2539 :
2540 1 : jobID := d.newJobIDLocked()
2541 1 : info := c.makeInfo(jobID)
2542 1 : d.opts.EventListener.CompactionBegin(info)
2543 1 : startTime := d.timeNow()
2544 1 :
2545 1 : ve, stats, err := d.runCompaction(jobID, c)
2546 1 :
2547 1 : info.Duration = d.timeNow().Sub(startTime)
2548 1 : if err == nil {
2549 1 : validateVersionEdit(ve, d.opts.Comparer.ValidateKey, d.opts.Comparer.FormatKey, d.opts.Logger)
2550 1 : err = d.mu.versions.UpdateVersionLocked(func() (versionUpdate, error) {
2551 1 : // Check if this compaction had a conflicting operation (eg. a d.excise())
2552 1 : // that necessitates it restarting from scratch. Note that since we hold
2553 1 : // the manifest lock, we don't expect this bool to change its value
2554 1 : // as only the holder of the manifest lock will ever write to it.
2555 1 : if c.cancel.Load() {
2556 1 : err = firstError(err, ErrCancelledCompaction)
2557 1 : // This is the first time we've seen a cancellation during the
2558 1 : // life of this compaction (or the original condition on err == nil
2559 1 : // would not have been true). We should delete any tables already
2560 1 : // created, as d.runCompaction did not do that.
2561 1 : d.cleanupVersionEdit(ve)
2562 1 : // Note that UpdateVersionLocked invalidates the pickedCompactionCache
2563 1 : // when we return, which is relevant because this failed compaction
2564 1 : // may be the highest priority to run next.
2565 1 : return versionUpdate{}, err
2566 1 : }
2567 1 : return versionUpdate{
2568 1 : VE: ve,
2569 1 : JobID: jobID,
2570 1 : Metrics: c.metrics,
2571 1 : InProgressCompactionsFn: func() []compactionInfo { return d.getInProgressCompactionInfoLocked(c) },
2572 : }, nil
2573 : })
2574 : }
2575 :
2576 1 : info.Done = true
2577 1 : info.Err = err
2578 1 : if err == nil {
2579 1 : for i := range ve.NewTables {
2580 1 : e := &ve.NewTables[i]
2581 1 : info.Output.Tables = append(info.Output.Tables, e.Meta.TableInfo())
2582 1 : }
2583 1 : d.mu.snapshots.cumulativePinnedCount += stats.CumulativePinnedKeys
2584 1 : d.mu.snapshots.cumulativePinnedSize += stats.CumulativePinnedSize
2585 1 : d.mu.versions.metrics.Keys.MissizedTombstonesCount += stats.CountMissizedDels
2586 : }
2587 :
2588 : // NB: clearing compacting state must occur before updating the read state;
2589 : // L0Sublevels initialization depends on it.
2590 1 : d.clearCompactingState(c, err != nil)
2591 1 : d.mu.versions.incrementCompactions(c.kind, c.extraLevels, c.pickerMetrics, c.bytesWritten.Load(), err)
2592 1 : d.mu.versions.incrementCompactionBytes(-c.bytesWritten.Load())
2593 1 :
2594 1 : info.TotalDuration = d.timeNow().Sub(c.beganAt)
2595 1 : d.opts.EventListener.CompactionEnd(info)
2596 1 :
2597 1 : // Update the read state before deleting obsolete files because the
2598 1 : // read-state update will cause the previous version to be unref'd and if
2599 1 : // there are no references obsolete tables will be added to the obsolete
2600 1 : // table list.
2601 1 : if err == nil {
2602 1 : d.updateReadStateLocked(d.opts.DebugCheck)
2603 1 : d.updateTableStatsLocked(ve.NewTables)
2604 1 : }
2605 1 : d.deleteObsoleteFiles(jobID)
2606 1 :
2607 1 : return err
2608 : }
2609 :
2610 : // runCopyCompaction runs a copy compaction where a new TableNum is created that
2611 : // is a byte-for-byte copy of the input file or span thereof in some cases. This
2612 : // is used in lieu of a move compaction when a file is being moved across the
2613 : // local/remote storage boundary. It could also be used in lieu of a rewrite
2614 : // compaction as part of a Download() call, which allows copying only a span of
2615 : // the external file, provided the file does not contain range keys or value
2616 : // blocks (see sstable.CopySpan).
2617 : //
2618 : // d.mu must be held when calling this method. The mutex will be released when
2619 : // doing IO.
2620 : func (d *DB) runCopyCompaction(
2621 : jobID JobID, c *compaction,
2622 1 : ) (ve *manifest.VersionEdit, stats compact.Stats, _ error) {
2623 1 : if c.cancel.Load() {
2624 0 : return nil, compact.Stats{}, ErrCancelledCompaction
2625 0 : }
2626 1 : iter := c.startLevel.files.Iter()
2627 1 : inputMeta := iter.First()
2628 1 : if iter.Next() != nil {
2629 0 : return nil, compact.Stats{}, base.AssertionFailedf("got more than one file for a move compaction")
2630 0 : }
2631 1 : if inputMeta.BlobReferenceDepth > 0 || len(inputMeta.BlobReferences) > 0 {
2632 0 : return nil, compact.Stats{}, base.AssertionFailedf(
2633 0 : "copy compaction for %s with blob references (depth=%d, refs=%d)",
2634 0 : inputMeta.TableNum, inputMeta.BlobReferenceDepth, len(inputMeta.BlobReferences),
2635 0 : )
2636 0 : }
2637 1 : ve = &manifest.VersionEdit{
2638 1 : DeletedTables: map[manifest.DeletedTableEntry]*manifest.TableMetadata{
2639 1 : {Level: c.startLevel.level, FileNum: inputMeta.TableNum}: inputMeta,
2640 1 : },
2641 1 : }
2642 1 :
2643 1 : objMeta, err := d.objProvider.Lookup(base.FileTypeTable, inputMeta.TableBacking.DiskFileNum)
2644 1 : if err != nil {
2645 0 : return nil, compact.Stats{}, err
2646 0 : }
2647 : // This code does not support copying a shared table (which should never be necessary).
2648 1 : if objMeta.IsShared() {
2649 0 : return nil, compact.Stats{}, base.AssertionFailedf("copy compaction of shared table")
2650 0 : }
2651 :
2652 : // We are in the relatively more complex case where we need to copy this
2653 : // file to remote storage. Drop the db mutex while we do the copy
2654 : //
2655 : // To ease up cleanup of the local file and tracking of refs, we create
2656 : // a new FileNum. This has the potential of making the block cache less
2657 : // effective, however.
2658 1 : newMeta := &manifest.TableMetadata{
2659 1 : Size: inputMeta.Size,
2660 1 : CreationTime: inputMeta.CreationTime,
2661 1 : SmallestSeqNum: inputMeta.SmallestSeqNum,
2662 1 : LargestSeqNum: inputMeta.LargestSeqNum,
2663 1 : LargestSeqNumAbsolute: inputMeta.LargestSeqNumAbsolute,
2664 1 : Stats: inputMeta.Stats,
2665 1 : Virtual: inputMeta.Virtual,
2666 1 : SyntheticPrefixAndSuffix: inputMeta.SyntheticPrefixAndSuffix,
2667 1 : }
2668 1 : if inputMeta.HasPointKeys {
2669 1 : newMeta.ExtendPointKeyBounds(c.cmp, inputMeta.PointKeyBounds.Smallest(), inputMeta.PointKeyBounds.Largest())
2670 1 : }
2671 1 : if inputMeta.HasRangeKeys {
2672 1 : newMeta.ExtendRangeKeyBounds(c.cmp, inputMeta.RangeKeyBounds.Smallest(), inputMeta.RangeKeyBounds.Largest())
2673 1 : }
2674 1 : newMeta.TableNum = d.mu.versions.getNextTableNum()
2675 1 : if objMeta.IsExternal() {
2676 1 : // external -> local/shared copy. File must be virtual.
2677 1 : // We will update this size later after we produce the new backing file.
2678 1 : newMeta.InitVirtualBacking(base.DiskFileNum(newMeta.TableNum), inputMeta.TableBacking.Size)
2679 1 : } else {
2680 1 : // local -> shared copy. New file is guaranteed to not be virtual.
2681 1 : newMeta.InitPhysicalBacking()
2682 1 : }
2683 :
2684 : // Before dropping the db mutex, grab a ref to the current version. This
2685 : // prevents any concurrent excises from deleting files that this compaction
2686 : // needs to read/maintain a reference to.
2687 1 : vers := d.mu.versions.currentVersion()
2688 1 : vers.Ref()
2689 1 : defer vers.UnrefLocked()
2690 1 :
2691 1 : // NB: The order here is reversed, lock after unlock. This is similar to
2692 1 : // runCompaction.
2693 1 : d.mu.Unlock()
2694 1 : defer d.mu.Lock()
2695 1 :
2696 1 : deleteOnExit := false
2697 1 : defer func() {
2698 1 : if deleteOnExit {
2699 1 : _ = d.objProvider.Remove(base.FileTypeTable, newMeta.TableBacking.DiskFileNum)
2700 1 : }
2701 : }()
2702 :
2703 : // If the src obj is external, we're doing an external to local/shared copy.
2704 1 : if objMeta.IsExternal() {
2705 1 : ctx := context.TODO()
2706 1 : src, err := d.objProvider.OpenForReading(
2707 1 : ctx, base.FileTypeTable, inputMeta.TableBacking.DiskFileNum, objstorage.OpenOptions{},
2708 1 : )
2709 1 : if err != nil {
2710 0 : return nil, compact.Stats{}, err
2711 0 : }
2712 1 : defer func() {
2713 1 : if src != nil {
2714 0 : _ = src.Close()
2715 0 : }
2716 : }()
2717 :
2718 1 : w, _, err := d.objProvider.Create(
2719 1 : ctx, base.FileTypeTable, newMeta.TableBacking.DiskFileNum,
2720 1 : objstorage.CreateOptions{
2721 1 : PreferSharedStorage: remote.ShouldCreateShared(d.opts.Experimental.CreateOnShared, c.outputLevel.level),
2722 1 : },
2723 1 : )
2724 1 : if err != nil {
2725 0 : return nil, compact.Stats{}, err
2726 0 : }
2727 1 : deleteOnExit = true
2728 1 :
2729 1 : start, end := newMeta.Smallest(), newMeta.Largest()
2730 1 : if newMeta.SyntheticPrefixAndSuffix.HasPrefix() {
2731 1 : syntheticPrefix := newMeta.SyntheticPrefixAndSuffix.Prefix()
2732 1 : start.UserKey = syntheticPrefix.Invert(start.UserKey)
2733 1 : end.UserKey = syntheticPrefix.Invert(end.UserKey)
2734 1 : }
2735 1 : if newMeta.SyntheticPrefixAndSuffix.HasSuffix() {
2736 0 : // Extend the bounds as necessary so that the keys don't include suffixes.
2737 0 : start.UserKey = start.UserKey[:c.comparer.Split(start.UserKey)]
2738 0 : if n := c.comparer.Split(end.UserKey); n < len(end.UserKey) {
2739 0 : end = base.MakeRangeDeleteSentinelKey(c.comparer.ImmediateSuccessor(nil, end.UserKey[:n]))
2740 0 : }
2741 : }
2742 :
2743 : // NB: external files are always virtual.
2744 1 : var wrote uint64
2745 1 : err = d.fileCache.withReader(ctx, block.NoReadEnv, inputMeta.VirtualMeta(), func(r *sstable.Reader, env sstable.ReadEnv) error {
2746 1 : var err error
2747 1 : // TODO(radu): plumb a ReadEnv to CopySpan (it could use the buffer pool
2748 1 : // or update category stats).
2749 1 : wrote, err = sstable.CopySpan(ctx,
2750 1 : src, r, d.opts.MakeReaderOptions(),
2751 1 : w, d.opts.MakeWriterOptions(c.outputLevel.level, d.TableFormat()),
2752 1 : start, end,
2753 1 : )
2754 1 : return err
2755 1 : })
2756 :
2757 1 : src = nil // We passed src to CopySpan; it's responsible for closing it.
2758 1 : if err != nil {
2759 1 : if errors.Is(err, sstable.ErrEmptySpan) {
2760 1 : // The virtual table was empty. Just remove the backing file.
2761 1 : // Note that deleteOnExit is true so we will delete the created object.
2762 1 : c.metrics[c.outputLevel.level] = &LevelMetrics{
2763 1 : TableBytesIn: inputMeta.Size,
2764 1 : }
2765 1 :
2766 1 : return ve, compact.Stats{}, nil
2767 1 : }
2768 0 : return nil, compact.Stats{}, err
2769 : }
2770 1 : newMeta.TableBacking.Size = wrote
2771 1 : newMeta.Size = wrote
2772 1 : } else {
2773 1 : _, err := d.objProvider.LinkOrCopyFromLocal(context.TODO(), d.opts.FS,
2774 1 : d.objProvider.Path(objMeta), base.FileTypeTable, newMeta.TableBacking.DiskFileNum,
2775 1 : objstorage.CreateOptions{PreferSharedStorage: true})
2776 1 : if err != nil {
2777 0 : return nil, compact.Stats{}, err
2778 0 : }
2779 1 : deleteOnExit = true
2780 : }
2781 1 : ve.NewTables = []manifest.NewTableEntry{{
2782 1 : Level: c.outputLevel.level,
2783 1 : Meta: newMeta,
2784 1 : }}
2785 1 : if newMeta.Virtual {
2786 1 : ve.CreatedBackingTables = []*manifest.TableBacking{newMeta.TableBacking}
2787 1 : }
2788 1 : c.metrics[c.outputLevel.level] = &LevelMetrics{
2789 1 : TableBytesIn: inputMeta.Size,
2790 1 : TableBytesCompacted: newMeta.Size,
2791 1 : TablesCompacted: 1,
2792 1 : }
2793 1 :
2794 1 : if err := d.objProvider.Sync(); err != nil {
2795 0 : return nil, compact.Stats{}, err
2796 0 : }
2797 1 : deleteOnExit = false
2798 1 : return ve, compact.Stats{}, nil
2799 : }
2800 :
2801 : // applyHintOnFile applies a deleteCompactionHint to a file, and updates the
2802 : // versionEdit accordingly. It returns a list of new files that were created
2803 : // if the hint was applied partially to a file (eg. through an exciseTable as opposed
2804 : // to an outright deletion). levelMetrics is kept up-to-date with the number
2805 : // of tables deleted or excised.
2806 : func (d *DB) applyHintOnFile(
2807 : h deleteCompactionHint,
2808 : f *manifest.TableMetadata,
2809 : level int,
2810 : levelMetrics *LevelMetrics,
2811 : ve *manifest.VersionEdit,
2812 : hintOverlap deletionHintOverlap,
2813 1 : ) (newFiles []manifest.NewTableEntry, err error) {
2814 1 : if hintOverlap == hintDoesNotApply {
2815 0 : return nil, nil
2816 0 : }
2817 :
2818 : // The hint overlaps with at least part of the file.
2819 1 : if hintOverlap == hintDeletesFile {
2820 1 : // The hint deletes the entirety of this file.
2821 1 : ve.DeletedTables[manifest.DeletedTableEntry{
2822 1 : Level: level,
2823 1 : FileNum: f.TableNum,
2824 1 : }] = f
2825 1 : levelMetrics.TablesDeleted++
2826 1 : return nil, nil
2827 1 : }
2828 : // The hint overlaps with only a part of the file, not the entirety of it. We need
2829 : // to use d.exciseTable. (hintOverlap == hintExcisesFile)
2830 1 : if d.FormatMajorVersion() < FormatVirtualSSTables {
2831 0 : panic("pebble: delete-only compaction hint excising a file is not supported in this version")
2832 : }
2833 :
2834 1 : levelMetrics.TablesExcised++
2835 1 : exciseBounds := base.UserKeyBoundsEndExclusive(h.start, h.end)
2836 1 : leftTable, rightTable, err := d.exciseTable(context.TODO(), exciseBounds, f, level, tightExciseBounds)
2837 1 : if err != nil {
2838 0 : return nil, errors.Wrap(err, "error when running excise for delete-only compaction")
2839 0 : }
2840 1 : newFiles = applyExciseToVersionEdit(ve, f, leftTable, rightTable, level)
2841 1 : return newFiles, nil
2842 : }
2843 :
2844 : func (d *DB) runDeleteOnlyCompactionForLevel(
2845 : cl compactionLevel,
2846 : levelMetrics *LevelMetrics,
2847 : ve *manifest.VersionEdit,
2848 : snapshots compact.Snapshots,
2849 : fragments []deleteCompactionHintFragment,
2850 : exciseEnabled bool,
2851 1 : ) error {
2852 1 : if cl.level == 0 {
2853 0 : panic("cannot run delete-only compaction for L0")
2854 : }
2855 1 : curFragment := 0
2856 1 :
2857 1 : // Outer loop loops on files. Middle loop loops on fragments. Inner loop
2858 1 : // loops on raw fragments of hints. Number of fragments are bounded by
2859 1 : // the number of hints this compaction was created with, which is capped
2860 1 : // in the compaction picker to avoid very CPU-hot loops here.
2861 1 : for f := range cl.files.All() {
2862 1 : // curFile usually matches f, except if f got excised in which case
2863 1 : // it maps to a virtual file that replaces f, or nil if f got removed
2864 1 : // in its entirety.
2865 1 : curFile := f
2866 1 : for curFragment < len(fragments) && d.cmp(fragments[curFragment].start, f.Smallest().UserKey) <= 0 {
2867 1 : curFragment++
2868 1 : }
2869 1 : if curFragment > 0 {
2870 1 : curFragment--
2871 1 : }
2872 :
2873 1 : for ; curFragment < len(fragments); curFragment++ {
2874 1 : if f.UserKeyBounds().End.CompareUpperBounds(d.cmp, base.UserKeyInclusive(fragments[curFragment].start)) < 0 {
2875 1 : break
2876 : }
2877 : // Process all overlapping hints with this file. Note that applying
2878 : // a hint twice is idempotent; curFile should have already been excised
2879 : // the first time, resulting in no change the second time.
2880 1 : for _, h := range fragments[curFragment].hints {
2881 1 : if h.tombstoneLevel >= cl.level {
2882 1 : // We cannot excise out the deletion tombstone itself, or anything
2883 1 : // above it.
2884 1 : continue
2885 : }
2886 1 : hintOverlap := h.canDeleteOrExcise(d.cmp, curFile, snapshots, exciseEnabled)
2887 1 : if hintOverlap == hintDoesNotApply {
2888 1 : continue
2889 : }
2890 1 : newFiles, err := d.applyHintOnFile(h, curFile, cl.level, levelMetrics, ve, hintOverlap)
2891 1 : if err != nil {
2892 0 : return err
2893 0 : }
2894 1 : if _, ok := ve.DeletedTables[manifest.DeletedTableEntry{Level: cl.level, FileNum: curFile.TableNum}]; ok {
2895 1 : curFile = nil
2896 1 : }
2897 1 : if len(newFiles) > 0 {
2898 1 : curFile = newFiles[len(newFiles)-1].Meta
2899 1 : } else if curFile == nil {
2900 1 : // Nothing remains of the file.
2901 1 : break
2902 : }
2903 : }
2904 1 : if curFile == nil {
2905 1 : // Nothing remains of the file.
2906 1 : break
2907 : }
2908 : }
2909 1 : if _, ok := ve.DeletedTables[manifest.DeletedTableEntry{
2910 1 : Level: cl.level,
2911 1 : FileNum: f.TableNum,
2912 1 : }]; !ok {
2913 0 : panic("pebble: delete-only compaction scheduled with hints that did not delete or excise a file")
2914 : }
2915 : }
2916 1 : return nil
2917 : }
2918 :
2919 : // deleteCompactionHintFragment represents a fragment of the key space and
2920 : // contains a set of deleteCompactionHints that apply to that fragment; a
2921 : // fragment starts at the start field and ends where the next fragment starts.
2922 : type deleteCompactionHintFragment struct {
2923 : start []byte
2924 : hints []deleteCompactionHint
2925 : }
2926 :
2927 : // Delete compaction hints can overlap with each other, and multiple fragments
2928 : // can apply to a single file. This function takes a list of hints and fragments
2929 : // them, to make it easier to apply them to non-overlapping files occupying a level;
2930 : // that way, files and hint fragments can be iterated on in lockstep, while efficiently
2931 : // being able to apply all hints overlapping with a given file.
2932 : func fragmentDeleteCompactionHints(
2933 : cmp Compare, hints []deleteCompactionHint,
2934 1 : ) []deleteCompactionHintFragment {
2935 1 : fragments := make([]deleteCompactionHintFragment, 0, len(hints)*2)
2936 1 : for i := range hints {
2937 1 : fragments = append(fragments, deleteCompactionHintFragment{start: hints[i].start},
2938 1 : deleteCompactionHintFragment{start: hints[i].end})
2939 1 : }
2940 1 : slices.SortFunc(fragments, func(i, j deleteCompactionHintFragment) int {
2941 1 : return cmp(i.start, j.start)
2942 1 : })
2943 1 : fragments = slices.CompactFunc(fragments, func(i, j deleteCompactionHintFragment) bool {
2944 1 : return bytes.Equal(i.start, j.start)
2945 1 : })
2946 1 : for _, h := range hints {
2947 1 : startIdx := sort.Search(len(fragments), func(i int) bool {
2948 1 : return cmp(fragments[i].start, h.start) >= 0
2949 1 : })
2950 1 : endIdx := sort.Search(len(fragments), func(i int) bool {
2951 1 : return cmp(fragments[i].start, h.end) >= 0
2952 1 : })
2953 1 : for i := startIdx; i < endIdx; i++ {
2954 1 : fragments[i].hints = append(fragments[i].hints, h)
2955 1 : }
2956 : }
2957 1 : return fragments
2958 : }
2959 :
2960 : // Runs a delete-only compaction.
2961 : //
2962 : // d.mu must *not* be held when calling this.
2963 : func (d *DB) runDeleteOnlyCompaction(
2964 : jobID JobID, c *compaction, snapshots compact.Snapshots,
2965 1 : ) (ve *manifest.VersionEdit, stats compact.Stats, retErr error) {
2966 1 : fragments := fragmentDeleteCompactionHints(d.cmp, c.deletionHints)
2967 1 : ve = &manifest.VersionEdit{
2968 1 : DeletedTables: map[manifest.DeletedTableEntry]*manifest.TableMetadata{},
2969 1 : }
2970 1 : for _, cl := range c.inputs {
2971 1 : levelMetrics := &LevelMetrics{}
2972 1 : if err := d.runDeleteOnlyCompactionForLevel(cl, levelMetrics, ve, snapshots, fragments, c.exciseEnabled); err != nil {
2973 0 : return nil, stats, err
2974 0 : }
2975 1 : c.metrics[cl.level] = levelMetrics
2976 : }
2977 : // Remove any files that were added and deleted in the same versionEdit.
2978 1 : ve.NewTables = slices.DeleteFunc(ve.NewTables, func(e manifest.NewTableEntry) bool {
2979 1 : entry := manifest.DeletedTableEntry{Level: e.Level, FileNum: e.Meta.TableNum}
2980 1 : if _, deleted := ve.DeletedTables[entry]; deleted {
2981 1 : delete(ve.DeletedTables, entry)
2982 1 : return true
2983 1 : }
2984 1 : return false
2985 : })
2986 : // Remove any entries from CreatedBackingTables that are not used in any
2987 : // NewFiles.
2988 1 : usedBackingFiles := make(map[base.DiskFileNum]struct{})
2989 1 : for _, e := range ve.NewTables {
2990 1 : if e.Meta.Virtual {
2991 1 : usedBackingFiles[e.Meta.TableBacking.DiskFileNum] = struct{}{}
2992 1 : }
2993 : }
2994 1 : ve.CreatedBackingTables = slices.DeleteFunc(ve.CreatedBackingTables, func(b *manifest.TableBacking) bool {
2995 1 : _, used := usedBackingFiles[b.DiskFileNum]
2996 1 : return !used
2997 1 : })
2998 : // Refresh the disk available statistic whenever a compaction/flush
2999 : // completes, before re-acquiring the mutex.
3000 1 : d.calculateDiskAvailableBytes()
3001 1 : return ve, stats, nil
3002 : }
3003 :
3004 : func (d *DB) runMoveCompaction(
3005 : jobID JobID, c *compaction,
3006 1 : ) (ve *manifest.VersionEdit, stats compact.Stats, _ error) {
3007 1 : iter := c.startLevel.files.Iter()
3008 1 : meta := iter.First()
3009 1 : if iter.Next() != nil {
3010 0 : return nil, stats, base.AssertionFailedf("got more than one file for a move compaction")
3011 0 : }
3012 1 : if c.cancel.Load() {
3013 0 : return ve, stats, ErrCancelledCompaction
3014 0 : }
3015 1 : c.metrics[c.outputLevel.level] = &LevelMetrics{
3016 1 : TableBytesMoved: meta.Size,
3017 1 : TablesMoved: 1,
3018 1 : }
3019 1 : ve = &manifest.VersionEdit{
3020 1 : DeletedTables: map[manifest.DeletedTableEntry]*manifest.TableMetadata{
3021 1 : {Level: c.startLevel.level, FileNum: meta.TableNum}: meta,
3022 1 : },
3023 1 : NewTables: []manifest.NewTableEntry{
3024 1 : {Level: c.outputLevel.level, Meta: meta},
3025 1 : },
3026 1 : }
3027 1 :
3028 1 : return ve, stats, nil
3029 : }
3030 :
3031 : // runCompaction runs a compaction that produces new on-disk tables from
3032 : // memtables or old on-disk tables.
3033 : //
3034 : // runCompaction cannot be used for compactionKindIngestedFlushable.
3035 : //
3036 : // d.mu must be held when calling this, but the mutex may be dropped and
3037 : // re-acquired during the course of this method.
3038 : func (d *DB) runCompaction(
3039 : jobID JobID, c *compaction,
3040 1 : ) (ve *manifest.VersionEdit, stats compact.Stats, retErr error) {
3041 1 : if c.cancel.Load() {
3042 1 : return ve, stats, ErrCancelledCompaction
3043 1 : }
3044 1 : switch c.kind {
3045 1 : case compactionKindDeleteOnly:
3046 1 : // Before dropping the db mutex, grab a ref to the current version. This
3047 1 : // prevents any concurrent excises from deleting files that this compaction
3048 1 : // needs to read/maintain a reference to.
3049 1 : //
3050 1 : // Note that delete-only compactions can call excise(), which needs to be able
3051 1 : // to read these files.
3052 1 : vers := d.mu.versions.currentVersion()
3053 1 : vers.Ref()
3054 1 : defer vers.UnrefLocked()
3055 1 : // Release the d.mu lock while doing I/O.
3056 1 : // Note the unusual order: Unlock and then Lock.
3057 1 : snapshots := d.mu.snapshots.toSlice()
3058 1 : d.mu.Unlock()
3059 1 : defer d.mu.Lock()
3060 1 : return d.runDeleteOnlyCompaction(jobID, c, snapshots)
3061 1 : case compactionKindMove:
3062 1 : return d.runMoveCompaction(jobID, c)
3063 1 : case compactionKindCopy:
3064 1 : return d.runCopyCompaction(jobID, c)
3065 0 : case compactionKindIngestedFlushable:
3066 0 : panic("pebble: runCompaction cannot handle compactionKindIngestedFlushable.")
3067 : }
3068 :
3069 1 : snapshots := d.mu.snapshots.toSlice()
3070 1 :
3071 1 : if c.flushing == nil {
3072 1 : // Before dropping the db mutex, grab a ref to the current version. This
3073 1 : // prevents any concurrent excises from deleting files that this compaction
3074 1 : // needs to read/maintain a reference to.
3075 1 : //
3076 1 : // Note that unlike user iterators, compactionIter does not maintain a ref
3077 1 : // of the version or read state.
3078 1 : vers := d.mu.versions.currentVersion()
3079 1 : vers.Ref()
3080 1 : defer vers.UnrefLocked()
3081 1 : }
3082 :
3083 : // The table is typically written at the maximum allowable format implied by
3084 : // the current format major version of the DB, but Options may define
3085 : // additional constraints.
3086 1 : tableFormat := d.TableFormat()
3087 1 :
3088 1 : // Release the d.mu lock while doing I/O.
3089 1 : // Note the unusual order: Unlock and then Lock.
3090 1 : d.mu.Unlock()
3091 1 : defer d.mu.Lock()
3092 1 :
3093 1 : // Determine whether we should separate values into blob files.
3094 1 : //
3095 1 : // TODO(jackson): Currently we never separate values in non-tests. Choose
3096 1 : // and initialize the appropriate ValueSeparation implementation based on
3097 1 : // Options and the compaction inputs.
3098 1 : valueSeparation := c.getValueSeparation(jobID, c, tableFormat)
3099 1 :
3100 1 : result := d.compactAndWrite(jobID, c, snapshots, tableFormat, valueSeparation)
3101 1 : if result.Err == nil {
3102 1 : ve, result.Err = c.makeVersionEdit(result)
3103 1 : }
3104 1 : if result.Err != nil {
3105 1 : // Delete any created tables or blob files.
3106 1 : obsoleteFiles := manifest.ObsoleteFiles{
3107 1 : TableBackings: make([]*manifest.TableBacking, 0, len(result.Tables)),
3108 1 : BlobFiles: make([]*manifest.BlobFileMetadata, 0, len(result.Blobs)),
3109 1 : }
3110 1 : d.mu.Lock()
3111 1 : for i := range result.Tables {
3112 1 : backing := &manifest.TableBacking{
3113 1 : DiskFileNum: result.Tables[i].ObjMeta.DiskFileNum,
3114 1 : Size: result.Tables[i].WriterMeta.Size,
3115 1 : }
3116 1 : obsoleteFiles.AddBacking(backing)
3117 1 : // Add this file to zombie tables as well, as the versionSet
3118 1 : // asserts on whether every obsolete file was at one point
3119 1 : // marked zombie.
3120 1 : d.mu.versions.zombieTables.AddMetadata(&result.Tables[i].ObjMeta, backing.Size)
3121 1 : }
3122 1 : for i := range result.Blobs {
3123 0 : obsoleteFiles.AddBlob(result.Blobs[i].Metadata)
3124 0 : // Add this file to zombie blobs as well, as the versionSet
3125 0 : // asserts on whether every obsolete file was at one point
3126 0 : // marked zombie.
3127 0 : d.mu.versions.zombieBlobs.AddMetadata(&result.Blobs[i].ObjMeta, result.Blobs[i].Metadata.Size)
3128 0 : }
3129 1 : d.mu.versions.addObsoleteLocked(obsoleteFiles)
3130 1 : d.mu.Unlock()
3131 : }
3132 : // Refresh the disk available statistic whenever a compaction/flush
3133 : // completes, before re-acquiring the mutex.
3134 1 : d.calculateDiskAvailableBytes()
3135 1 : return ve, result.Stats, result.Err
3136 : }
3137 :
3138 : // compactAndWrite runs the data part of a compaction, where we set up a
3139 : // compaction iterator and use it to write output tables.
3140 : func (d *DB) compactAndWrite(
3141 : jobID JobID,
3142 : c *compaction,
3143 : snapshots compact.Snapshots,
3144 : tableFormat sstable.TableFormat,
3145 : valueSeparation compact.ValueSeparation,
3146 1 : ) (result compact.Result) {
3147 1 : // Compactions use a pool of buffers to read blocks, avoiding polluting the
3148 1 : // block cache with blocks that will not be read again. We initialize the
3149 1 : // buffer pool with a size 12. This initial size does not need to be
3150 1 : // accurate, because the pool will grow to accommodate the maximum number of
3151 1 : // blocks allocated at a given time over the course of the compaction. But
3152 1 : // choosing a size larger than that working set avoids any additional
3153 1 : // allocations to grow the size of the pool over the course of iteration.
3154 1 : //
3155 1 : // Justification for initial size 12: In a two-level compaction, at any
3156 1 : // given moment we'll have 2 index blocks in-use and 2 data blocks in-use.
3157 1 : // Additionally, when decoding a compressed block, we'll temporarily
3158 1 : // allocate 1 additional block to hold the compressed buffer. In the worst
3159 1 : // case that all input sstables have two-level index blocks (+2), value
3160 1 : // blocks (+2), range deletion blocks (+n) and range key blocks (+n), we'll
3161 1 : // additionally require 2n+4 blocks where n is the number of input sstables.
3162 1 : // Range deletion and range key blocks are relatively rare, and the cost of
3163 1 : // an additional allocation or two over the course of the compaction is
3164 1 : // considered to be okay. A larger initial size would cause the pool to hold
3165 1 : // on to more memory, even when it's not in-use because the pool will
3166 1 : // recycle buffers up to the current capacity of the pool. The memory use of
3167 1 : // a 12-buffer pool is expected to be within reason, even if all the buffers
3168 1 : // grow to the typical size of an index block (256 KiB) which would
3169 1 : // translate to 3 MiB per compaction.
3170 1 : c.bufferPool.Init(12)
3171 1 : defer c.bufferPool.Release()
3172 1 : blockReadEnv := block.ReadEnv{
3173 1 : BufferPool: &c.bufferPool,
3174 1 : Stats: &c.stats,
3175 1 : IterStats: d.fileCache.SSTStatsCollector().Accumulator(
3176 1 : uint64(uintptr(unsafe.Pointer(c))),
3177 1 : categoryCompaction,
3178 1 : ),
3179 1 : }
3180 1 : c.valueFetcher.Init(d.fileCache, blockReadEnv)
3181 1 : iiopts := internalIterOpts{
3182 1 : compaction: true,
3183 1 : readEnv: sstable.ReadEnv{Block: blockReadEnv},
3184 1 : blobValueFetcher: &c.valueFetcher,
3185 1 : }
3186 1 : defer func() { _ = c.valueFetcher.Close() }()
3187 :
3188 1 : pointIter, rangeDelIter, rangeKeyIter, err := c.newInputIters(d.newIters, d.tableNewRangeKeyIter, iiopts)
3189 1 : defer func() {
3190 1 : for _, closer := range c.closers {
3191 1 : closer.FragmentIterator.Close()
3192 1 : }
3193 : }()
3194 1 : if err != nil {
3195 1 : return compact.Result{Err: err}
3196 1 : }
3197 1 : c.allowedZeroSeqNum = c.allowZeroSeqNum()
3198 1 : cfg := compact.IterConfig{
3199 1 : Comparer: c.comparer,
3200 1 : Merge: d.merge,
3201 1 : TombstoneElision: c.delElision,
3202 1 : RangeKeyElision: c.rangeKeyElision,
3203 1 : Snapshots: snapshots,
3204 1 : AllowZeroSeqNum: c.allowedZeroSeqNum,
3205 1 : IneffectualSingleDeleteCallback: func(userKey []byte) {
3206 1 : d.opts.EventListener.PossibleAPIMisuse(PossibleAPIMisuseInfo{
3207 1 : Kind: IneffectualSingleDelete,
3208 1 : UserKey: slices.Clone(userKey),
3209 1 : })
3210 1 : },
3211 0 : NondeterministicSingleDeleteCallback: func(userKey []byte) {
3212 0 : d.opts.EventListener.PossibleAPIMisuse(PossibleAPIMisuseInfo{
3213 0 : Kind: NondeterministicSingleDelete,
3214 0 : UserKey: slices.Clone(userKey),
3215 0 : })
3216 0 : },
3217 1 : MissizedDeleteCallback: func(userKey []byte, elidedSize, expectedSize uint64) {
3218 1 : d.opts.EventListener.PossibleAPIMisuse(PossibleAPIMisuseInfo{
3219 1 : Kind: MissizedDelete,
3220 1 : UserKey: slices.Clone(userKey),
3221 1 : ExtraInfo: fmt.Sprintf("elidedSize=%d,expectedSize=%d", elidedSize, expectedSize),
3222 1 : })
3223 1 : },
3224 : }
3225 1 : iter := compact.NewIter(cfg, pointIter, rangeDelIter, rangeKeyIter)
3226 1 :
3227 1 : runnerCfg := compact.RunnerConfig{
3228 1 : CompactionBounds: base.UserKeyBoundsFromInternal(c.smallest, c.largest),
3229 1 : L0SplitKeys: c.l0Limits,
3230 1 : Grandparents: c.grandparents,
3231 1 : MaxGrandparentOverlapBytes: c.maxOverlapBytes,
3232 1 : TargetOutputFileSize: c.maxOutputFileSize,
3233 1 : GrantHandle: c.grantHandle,
3234 1 : }
3235 1 : runner := compact.NewRunner(runnerCfg, iter)
3236 1 :
3237 1 : var spanPolicyValid bool
3238 1 : var spanPolicy SpanPolicy
3239 1 : // If spanPolicyValid is true and spanPolicyEndKey is empty, then spanPolicy
3240 1 : // applies for the rest of the keyspace.
3241 1 : var spanPolicyEndKey []byte
3242 1 :
3243 1 : for runner.MoreDataToWrite() {
3244 1 : if c.cancel.Load() {
3245 1 : return runner.Finish().WithError(ErrCancelledCompaction)
3246 1 : }
3247 : // Create a new table.
3248 1 : firstKey := runner.FirstKey()
3249 1 : if !spanPolicyValid || (len(spanPolicyEndKey) > 0 && d.cmp(firstKey, spanPolicyEndKey) >= 0) {
3250 1 : var err error
3251 1 : spanPolicy, spanPolicyEndKey, err = d.opts.Experimental.SpanPolicyFunc(firstKey)
3252 1 : if err != nil {
3253 0 : return runner.Finish().WithError(err)
3254 0 : }
3255 1 : spanPolicyValid = true
3256 : }
3257 :
3258 1 : writerOpts := d.opts.MakeWriterOptions(c.outputLevel.level, tableFormat)
3259 1 : if spanPolicy.DisableValueSeparationBySuffix {
3260 1 : writerOpts.DisableValueBlocks = true
3261 1 : }
3262 1 : vSep := valueSeparation
3263 1 : if spanPolicy.ValueStoragePolicy == ValueStorageLowReadLatency {
3264 1 : vSep = compact.NeverSeparateValues{}
3265 1 : }
3266 1 : objMeta, tw, err := d.newCompactionOutputTable(jobID, c, writerOpts)
3267 1 : if err != nil {
3268 1 : return runner.Finish().WithError(err)
3269 1 : }
3270 1 : runner.WriteTable(objMeta, tw, spanPolicyEndKey, vSep)
3271 : }
3272 1 : result = runner.Finish()
3273 1 : if result.Err == nil {
3274 1 : result.Err = d.objProvider.Sync()
3275 1 : }
3276 1 : return result
3277 : }
3278 :
3279 : // makeVersionEdit creates the version edit for a compaction, based on the
3280 : // tables in compact.Result.
3281 1 : func (c *compaction) makeVersionEdit(result compact.Result) (*manifest.VersionEdit, error) {
3282 1 : ve := &manifest.VersionEdit{
3283 1 : DeletedTables: map[manifest.DeletedTableEntry]*manifest.TableMetadata{},
3284 1 : }
3285 1 : for _, cl := range c.inputs {
3286 1 : for f := range cl.files.All() {
3287 1 : ve.DeletedTables[manifest.DeletedTableEntry{
3288 1 : Level: cl.level,
3289 1 : FileNum: f.TableNum,
3290 1 : }] = f
3291 1 : }
3292 : }
3293 : // Add any newly constructed blob files to the version edit.
3294 1 : ve.NewBlobFiles = make([]*manifest.BlobFileMetadata, len(result.Blobs))
3295 1 : for i := range result.Blobs {
3296 1 : ve.NewBlobFiles[i] = result.Blobs[i].Metadata
3297 1 : }
3298 :
3299 1 : startLevelBytes := c.startLevel.files.TableSizeSum()
3300 1 : outputMetrics := &LevelMetrics{
3301 1 : TableBytesIn: startLevelBytes,
3302 1 : // TODO(jackson): This BytesRead value does not include any blob files
3303 1 : // written. It either should, or we should add a separate metric.
3304 1 : TableBytesRead: c.outputLevel.files.TableSizeSum(),
3305 1 : BlobBytesCompacted: result.Stats.CumulativeBlobFileSize,
3306 1 : }
3307 1 : if c.flushing != nil {
3308 1 : outputMetrics.BlobBytesFlushed = result.Stats.CumulativeBlobFileSize
3309 1 : }
3310 1 : if len(c.extraLevels) > 0 {
3311 1 : outputMetrics.TableBytesIn += c.extraLevels[0].files.TableSizeSum()
3312 1 : }
3313 1 : outputMetrics.TableBytesRead += outputMetrics.TableBytesIn
3314 1 :
3315 1 : c.metrics[c.outputLevel.level] = outputMetrics
3316 1 : if len(c.flushing) == 0 && c.metrics[c.startLevel.level] == nil {
3317 1 : c.metrics[c.startLevel.level] = &LevelMetrics{}
3318 1 : }
3319 1 : if len(c.extraLevels) > 0 {
3320 1 : c.metrics[c.extraLevels[0].level] = &LevelMetrics{}
3321 1 : outputMetrics.MultiLevel.TableBytesInTop = startLevelBytes
3322 1 : outputMetrics.MultiLevel.TableBytesIn = outputMetrics.TableBytesIn
3323 1 : outputMetrics.MultiLevel.TableBytesRead = outputMetrics.TableBytesRead
3324 1 : }
3325 :
3326 1 : inputLargestSeqNumAbsolute := c.inputLargestSeqNumAbsolute()
3327 1 : ve.NewTables = make([]manifest.NewTableEntry, len(result.Tables))
3328 1 : for i := range result.Tables {
3329 1 : t := &result.Tables[i]
3330 1 :
3331 1 : if t.WriterMeta.Properties.NumValuesInBlobFiles > 0 {
3332 1 : if len(t.BlobReferences) == 0 {
3333 0 : return nil, base.AssertionFailedf("num values in blob files %d but no blob references",
3334 0 : t.WriterMeta.Properties.NumValuesInBlobFiles)
3335 0 : }
3336 : }
3337 :
3338 1 : fileMeta := &manifest.TableMetadata{
3339 1 : TableNum: base.PhysicalTableFileNum(t.ObjMeta.DiskFileNum),
3340 1 : CreationTime: t.CreationTime.Unix(),
3341 1 : Size: t.WriterMeta.Size,
3342 1 : SmallestSeqNum: t.WriterMeta.SmallestSeqNum,
3343 1 : LargestSeqNum: t.WriterMeta.LargestSeqNum,
3344 1 : BlobReferences: t.BlobReferences,
3345 1 : BlobReferenceDepth: t.BlobReferenceDepth,
3346 1 : }
3347 1 : if c.flushing == nil {
3348 1 : // Set the file's LargestSeqNumAbsolute to be the maximum value of any
3349 1 : // of the compaction's input sstables.
3350 1 : // TODO(jackson): This could be narrowed to be the maximum of input
3351 1 : // sstables that overlap the output sstable's key range.
3352 1 : fileMeta.LargestSeqNumAbsolute = inputLargestSeqNumAbsolute
3353 1 : } else {
3354 1 : fileMeta.LargestSeqNumAbsolute = t.WriterMeta.LargestSeqNum
3355 1 : }
3356 1 : fileMeta.InitPhysicalBacking()
3357 1 :
3358 1 : // If the file didn't contain any range deletions, we can fill its
3359 1 : // table stats now, avoiding unnecessarily loading the table later.
3360 1 : maybeSetStatsFromProperties(
3361 1 : fileMeta.PhysicalMeta(), &t.WriterMeta.Properties.CommonProperties, c.logger,
3362 1 : )
3363 1 :
3364 1 : if t.WriterMeta.HasPointKeys {
3365 1 : fileMeta.ExtendPointKeyBounds(c.cmp, t.WriterMeta.SmallestPoint, t.WriterMeta.LargestPoint)
3366 1 : }
3367 1 : if t.WriterMeta.HasRangeDelKeys {
3368 1 : fileMeta.ExtendPointKeyBounds(c.cmp, t.WriterMeta.SmallestRangeDel, t.WriterMeta.LargestRangeDel)
3369 1 : }
3370 1 : if t.WriterMeta.HasRangeKeys {
3371 1 : fileMeta.ExtendRangeKeyBounds(c.cmp, t.WriterMeta.SmallestRangeKey, t.WriterMeta.LargestRangeKey)
3372 1 : }
3373 :
3374 1 : ve.NewTables[i] = manifest.NewTableEntry{
3375 1 : Level: c.outputLevel.level,
3376 1 : Meta: fileMeta,
3377 1 : }
3378 1 :
3379 1 : // Update metrics.
3380 1 : if c.flushing == nil {
3381 1 : outputMetrics.TablesCompacted++
3382 1 : outputMetrics.TableBytesCompacted += fileMeta.Size
3383 1 : } else {
3384 1 : outputMetrics.TablesFlushed++
3385 1 : outputMetrics.TableBytesFlushed += fileMeta.Size
3386 1 : }
3387 1 : outputMetrics.EstimatedReferencesSize += fileMeta.EstimatedReferenceSize()
3388 1 : outputMetrics.BlobBytesReadEstimate += fileMeta.EstimatedReferenceSize()
3389 1 : outputMetrics.TablesSize += int64(fileMeta.Size)
3390 1 : outputMetrics.TablesCount++
3391 1 : outputMetrics.Additional.BytesWrittenDataBlocks += t.WriterMeta.Properties.DataSize
3392 1 : outputMetrics.Additional.BytesWrittenValueBlocks += t.WriterMeta.Properties.ValueBlocksSize
3393 : }
3394 :
3395 : // Sanity check that the tables are ordered and don't overlap.
3396 1 : for i := 1; i < len(ve.NewTables); i++ {
3397 1 : if ve.NewTables[i-1].Meta.UserKeyBounds().End.IsUpperBoundFor(c.cmp, ve.NewTables[i].Meta.Smallest().UserKey) {
3398 0 : return nil, base.AssertionFailedf("pebble: compaction output tables overlap: %s and %s",
3399 0 : ve.NewTables[i-1].Meta.DebugString(c.formatKey, true),
3400 0 : ve.NewTables[i].Meta.DebugString(c.formatKey, true),
3401 0 : )
3402 0 : }
3403 : }
3404 :
3405 1 : return ve, nil
3406 : }
3407 :
3408 : // newCompactionOutputTable creates an object for a new table produced by a
3409 : // compaction or flush.
3410 : func (d *DB) newCompactionOutputTable(
3411 : jobID JobID, c *compaction, writerOpts sstable.WriterOptions,
3412 1 : ) (objstorage.ObjectMetadata, sstable.RawWriter, error) {
3413 1 : writable, objMeta, err := d.newCompactionOutputObj(c, base.FileTypeTable)
3414 1 : if err != nil {
3415 1 : return objstorage.ObjectMetadata{}, nil, err
3416 1 : }
3417 1 : d.opts.EventListener.TableCreated(TableCreateInfo{
3418 1 : JobID: int(jobID),
3419 1 : Reason: c.kind.compactingOrFlushing(),
3420 1 : Path: d.objProvider.Path(objMeta),
3421 1 : FileNum: objMeta.DiskFileNum,
3422 1 : })
3423 1 : writerOpts.SetInternal(sstableinternal.WriterOptions{
3424 1 : CacheOpts: sstableinternal.CacheOptions{
3425 1 : CacheHandle: d.cacheHandle,
3426 1 : FileNum: objMeta.DiskFileNum,
3427 1 : },
3428 1 : })
3429 1 : tw := sstable.NewRawWriterWithCPUMeasurer(writable, writerOpts, c.grantHandle)
3430 1 : return objMeta, tw, nil
3431 : }
3432 :
3433 : // newCompactionOutputBlob creates an object for a new blob produced by a
3434 : // compaction or flush.
3435 : func (d *DB) newCompactionOutputBlob(
3436 : jobID JobID, c *compaction,
3437 1 : ) (objstorage.Writable, objstorage.ObjectMetadata, error) {
3438 1 : writable, objMeta, err := d.newCompactionOutputObj(c, base.FileTypeBlob)
3439 1 : if err != nil {
3440 0 : return nil, objstorage.ObjectMetadata{}, err
3441 0 : }
3442 1 : d.opts.EventListener.BlobFileCreated(BlobFileCreateInfo{
3443 1 : JobID: int(jobID),
3444 1 : Reason: c.kind.compactingOrFlushing(),
3445 1 : Path: d.objProvider.Path(objMeta),
3446 1 : FileNum: objMeta.DiskFileNum,
3447 1 : })
3448 1 : return writable, objMeta, nil
3449 : }
3450 :
3451 : // newCompactionOutputObj creates an object produced by a compaction or flush.
3452 : func (d *DB) newCompactionOutputObj(
3453 : c *compaction, typ base.FileType,
3454 1 : ) (objstorage.Writable, objstorage.ObjectMetadata, error) {
3455 1 : diskFileNum := d.mu.versions.getNextDiskFileNum()
3456 1 : ctx := context.TODO()
3457 1 :
3458 1 : if objiotracing.Enabled {
3459 0 : ctx = objiotracing.WithLevel(ctx, c.outputLevel.level)
3460 0 : if c.kind == compactionKindFlush {
3461 0 : ctx = objiotracing.WithReason(ctx, objiotracing.ForFlush)
3462 0 : } else {
3463 0 : ctx = objiotracing.WithReason(ctx, objiotracing.ForCompaction)
3464 0 : }
3465 : }
3466 :
3467 1 : writable, objMeta, err := d.objProvider.Create(ctx, typ, diskFileNum, c.opts)
3468 1 : if err != nil {
3469 1 : return nil, objstorage.ObjectMetadata{}, err
3470 1 : }
3471 :
3472 1 : if c.kind != compactionKindFlush {
3473 1 : writable = &compactionWritable{
3474 1 : Writable: writable,
3475 1 : versions: d.mu.versions,
3476 1 : written: &c.bytesWritten,
3477 1 : }
3478 1 : }
3479 1 : return writable, objMeta, nil
3480 : }
3481 :
3482 : // validateVersionEdit validates that start and end keys across new and deleted
3483 : // files in a versionEdit pass the given validation function.
3484 : func validateVersionEdit(
3485 : ve *manifest.VersionEdit, vk base.ValidateKey, format base.FormatKey, logger Logger,
3486 1 : ) {
3487 1 : validateKey := func(f *manifest.TableMetadata, key []byte) {
3488 1 : if err := vk.Validate(key); err != nil {
3489 1 : logger.Fatalf("pebble: version edit validation failed (key=%s file=%s): %v", format(key), f, err)
3490 1 : }
3491 : }
3492 :
3493 : // Validate both new and deleted files.
3494 1 : for _, f := range ve.NewTables {
3495 1 : validateKey(f.Meta, f.Meta.Smallest().UserKey)
3496 1 : validateKey(f.Meta, f.Meta.Largest().UserKey)
3497 1 : }
3498 1 : for _, m := range ve.DeletedTables {
3499 1 : validateKey(m, m.Smallest().UserKey)
3500 1 : validateKey(m, m.Largest().UserKey)
3501 1 : }
3502 : }
3503 :
3504 1 : func getDiskWriteCategoryForCompaction(opts *Options, kind compactionKind) vfs.DiskWriteCategory {
3505 1 : if opts.EnableSQLRowSpillMetrics {
3506 0 : // In the scenario that the Pebble engine is used for SQL row spills the
3507 0 : // data written to the memtable will correspond to spills to disk and
3508 0 : // should be categorized as such.
3509 0 : return "sql-row-spill"
3510 1 : } else if kind == compactionKindFlush {
3511 1 : return "pebble-memtable-flush"
3512 1 : } else {
3513 1 : return "pebble-compaction"
3514 1 : }
3515 : }
|