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