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