Line data Source code
1 : // Copyright 2020 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 manifest
6 :
7 : import (
8 : "bytes"
9 : stdcmp "cmp"
10 : "fmt"
11 : "math"
12 : "slices"
13 : "sort"
14 : "strings"
15 :
16 : "github.com/cockroachdb/errors"
17 : "github.com/cockroachdb/pebble/internal/base"
18 : "github.com/cockroachdb/pebble/internal/invariants"
19 : )
20 :
21 : // errInvalidL0SublevelsOpt is for use in AddL0Files when the incremental
22 : // sublevel generation optimization failed, and NewL0Sublevels must be called.
23 : var errInvalidL0SublevelsOpt = errors.New("pebble: L0 sublevel generation optimization cannot be used")
24 :
25 : // Intervals are of the form [start, end) with no gap between intervals. Each
26 : // file overlaps perfectly with a sequence of intervals. This perfect overlap
27 : // occurs because the union of file boundary keys is used to pick intervals.
28 : // However when the largest key in a file is inclusive and it is used as an end
29 : // of an interval, the actual key is ImmediateSuccessor(key). We don't have the
30 : // ImmediateSuccessor function to do this computation, so we instead keep an
31 : // isInclusiveEndBound bool to remind the code about this fact. This is used for
32 : // comparisons in the following manner:
33 : // - intervalKey{k, false} < intervalKey{k, true}
34 : // - k1 < k2 -> intervalKey{k1, _} < intervalKey{k2, _}.
35 : //
36 : // Note that the file's largest key is exclusive if the internal key
37 : // has a trailer matching the rangedel sentinel key. In this case, we set
38 : // isInclusiveEndBound to false for end interval computation.
39 : //
40 : // For example, consider three files with bounds [a,e], [b,g], and [e,j]. The
41 : // interval keys produced would be intervalKey{a, false}, intervalKey{b, false},
42 : // intervalKey{e, false}, intervalKey{e, true}, intervalKey{g, true} and
43 : // intervalKey{j, true}, resulting in intervals
44 : // [a, b), [b, (e, false)), [(e,false), (e, true)), [(e, true), (g, true)) and
45 : // [(g, true), (j, true)). The first file overlaps with the first three
46 : // perfectly, the second file overlaps with the second through to fourth
47 : // intervals, and the third file overlaps with the last three.
48 : //
49 : // The intervals are indexed starting from 0, with the index of the interval
50 : // being the index of the start key of the interval.
51 : //
52 : // In addition to helping with compaction picking, we use interval indices
53 : // to assign each file an interval range once. Subsequent operations, say
54 : // picking overlapping files for a compaction, only need to use the index
55 : // numbers and so avoid expensive byte slice comparisons.
56 : type intervalKey struct {
57 : key []byte
58 : isInclusiveEndBound bool
59 : }
60 :
61 1 : func (k *intervalKey) toEndBoundary() base.UserKeyBoundary {
62 1 : return base.UserKeyExclusiveIf(k.key, !k.isInclusiveEndBound)
63 1 : }
64 :
65 : // intervalKeyTemp is used in the sortAndSweep step. It contains additional metadata
66 : // which is used to generate the {min,max}IntervalIndex for files.
67 : type intervalKeyTemp struct {
68 : intervalKey intervalKey
69 : fileMeta *FileMetadata
70 : isEndKey bool
71 : }
72 :
73 1 : func (i *intervalKeyTemp) setFileIntervalIndex(idx int) {
74 1 : if i.isEndKey {
75 1 : // This is the right endpoint of some file interval, so the
76 1 : // file.maxIntervalIndex must be j - 1 as maxIntervalIndex is
77 1 : // inclusive.
78 1 : i.fileMeta.maxIntervalIndex = idx - 1
79 1 : return
80 1 : }
81 : // This is the left endpoint for some file interval, so the
82 : // file.minIntervalIndex must be j.
83 1 : i.fileMeta.minIntervalIndex = idx
84 : }
85 :
86 1 : func intervalKeyCompare(cmp Compare, a, b intervalKey) int {
87 1 : rv := cmp(a.key, b.key)
88 1 : if rv == 0 {
89 1 : if a.isInclusiveEndBound && !b.isInclusiveEndBound {
90 1 : return +1
91 1 : }
92 1 : if !a.isInclusiveEndBound && b.isInclusiveEndBound {
93 1 : return -1
94 1 : }
95 : }
96 1 : return rv
97 : }
98 :
99 : type intervalKeySorter struct {
100 : keys []intervalKeyTemp
101 : cmp Compare
102 : }
103 :
104 1 : func (s intervalKeySorter) Len() int { return len(s.keys) }
105 1 : func (s intervalKeySorter) Less(i, j int) bool {
106 1 : return intervalKeyCompare(s.cmp, s.keys[i].intervalKey, s.keys[j].intervalKey) < 0
107 1 : }
108 1 : func (s intervalKeySorter) Swap(i, j int) {
109 1 : s.keys[i], s.keys[j] = s.keys[j], s.keys[i]
110 1 : }
111 :
112 : // sortAndSweep will sort the intervalKeys using intervalKeySorter, remove the
113 : // duplicate fileIntervals, and set the {min, max}IntervalIndex for the files.
114 1 : func sortAndSweep(keys []intervalKeyTemp, cmp Compare) []intervalKeyTemp {
115 1 : if len(keys) == 0 {
116 1 : return nil
117 1 : }
118 1 : sorter := intervalKeySorter{keys: keys, cmp: cmp}
119 1 : sort.Sort(sorter)
120 1 :
121 1 : // intervalKeys are generated using the file bounds. Specifically, there are
122 1 : // 2 intervalKeys for each file, and len(keys) = 2 * number of files. Each
123 1 : // `intervalKeyTemp` stores information about which file it was generated
124 1 : // from, and whether the key represents the end key of the file. So, as
125 1 : // we're deduplicating the `keys` slice, we're guaranteed to iterate over
126 1 : // the interval keys belonging to each of the files. Since the
127 1 : // file.{min,max}IntervalIndex points to the position of the files bounds in
128 1 : // the deduplicated `keys` slice, we can determine
129 1 : // file.{min,max}IntervalIndex during the iteration.
130 1 : i := 0
131 1 : j := 0
132 1 : for i < len(keys) {
133 1 : // loop invariant: j <= i
134 1 : currKey := keys[i]
135 1 : keys[j] = keys[i]
136 1 :
137 1 : for {
138 1 : keys[i].setFileIntervalIndex(j)
139 1 : i++
140 1 : if i >= len(keys) || intervalKeyCompare(cmp, currKey.intervalKey, keys[i].intervalKey) != 0 {
141 1 : break
142 : }
143 : }
144 1 : j++
145 : }
146 1 : return keys[:j]
147 : }
148 :
149 : // A key interval of the form [start, end). The end is not represented here
150 : // since it is implicit in the start of the next interval. The last interval is
151 : // an exception but we don't need to ever lookup the end of that interval; the
152 : // last fileInterval will only act as an end key marker. The set of intervals
153 : // is const after initialization.
154 : type fileInterval struct {
155 : index int
156 : startKey intervalKey
157 :
158 : // True iff some file in this interval is compacting to base. Such intervals
159 : // cannot have any files participate in L0 -> Lbase compactions.
160 : isBaseCompacting bool
161 :
162 : // The min and max intervals index across all the files that overlap with
163 : // this interval. Inclusive on both sides.
164 : filesMinIntervalIndex int
165 : filesMaxIntervalIndex int
166 :
167 : // True if another interval that has a file extending into this interval is
168 : // undergoing a compaction into Lbase. In other words, this bool is true if
169 : // any interval in [filesMinIntervalIndex, filesMaxIntervalIndex] has
170 : // isBaseCompacting set to true. This lets the compaction picker
171 : // de-prioritize this interval for picking compactions, since there's a high
172 : // chance that a base compaction with a sufficient height of sublevels
173 : // rooted at this interval could not be chosen due to the ongoing base
174 : // compaction in the other interval. If the file straddling the two
175 : // intervals is at a sufficiently high sublevel (with enough compactible
176 : // files below it to satisfy minCompactionDepth), this is not an issue, but
177 : // to optimize for quickly picking base compactions far away from other base
178 : // compactions, this bool is used as a heuristic (but not as a complete
179 : // disqualifier).
180 : intervalRangeIsBaseCompacting bool
181 :
182 : // All files in this interval, in increasing sublevel order.
183 : files []*FileMetadata
184 :
185 : // len(files) - compactingFileCount is the stack depth that requires
186 : // starting new compactions. This metric is not precise since the
187 : // compactingFileCount can include files that are part of N (where N > 1)
188 : // intra-L0 compactions, so the stack depth after those complete will be
189 : // len(files) - compactingFileCount + N. We ignore this imprecision since we
190 : // don't want to track which files are part of which intra-L0 compaction.
191 : compactingFileCount int
192 :
193 : // Interpolated from files in this interval. For files spanning multiple
194 : // intervals, we assume an equal distribution of bytes across all those
195 : // intervals.
196 : estimatedBytes uint64
197 : }
198 :
199 : // Helper type for any cases requiring a bool slice.
200 : type bitSet []bool
201 :
202 1 : func newBitSet(n int) bitSet {
203 1 : return make([]bool, n)
204 1 : }
205 :
206 1 : func (b *bitSet) markBit(i int) {
207 1 : (*b)[i] = true
208 1 : }
209 :
210 1 : func (b *bitSet) markBits(start, end int) {
211 1 : for i := start; i < end; i++ {
212 1 : (*b)[i] = true
213 1 : }
214 : }
215 :
216 1 : func (b *bitSet) clearAllBits() {
217 1 : for i := range *b {
218 1 : (*b)[i] = false
219 1 : }
220 : }
221 :
222 : // L0Compaction describes an active compaction with inputs from L0.
223 : type L0Compaction struct {
224 : Smallest InternalKey
225 : Largest InternalKey
226 : IsIntraL0 bool
227 : }
228 :
229 : // L0Sublevels represents a sublevel view of SSTables in L0. Tables in one
230 : // sublevel are non-overlapping in key ranges, and keys in higher-indexed
231 : // sublevels shadow older versions in lower-indexed sublevels. These invariants
232 : // are similar to the regular level invariants, except with higher indexed
233 : // sublevels having newer keys as opposed to lower indexed levels.
234 : //
235 : // There is no limit to the number of sublevels that can exist in L0 at any
236 : // time, however read and compaction performance is best when there are as few
237 : // sublevels as possible.
238 : type L0Sublevels struct {
239 : // Levels are ordered from oldest sublevel to youngest sublevel in the
240 : // outer slice, and the inner slice contains non-overlapping files for
241 : // that sublevel in increasing key order. Levels is constructed from
242 : // levelFiles and is used by callers that require a LevelSlice. The below two
243 : // fields are treated as immutable once created in NewL0Sublevels.
244 : Levels []LevelSlice
245 : levelFiles [][]*FileMetadata
246 :
247 : cmp Compare
248 : formatKey base.FormatKey
249 :
250 : fileBytes uint64
251 : // All the L0 files, ordered from oldest to youngest.
252 : levelMetadata *LevelMetadata
253 :
254 : // The file intervals in increasing key order.
255 : orderedIntervals []fileInterval
256 :
257 : // Keys to break flushes at.
258 : flushSplitUserKeys [][]byte
259 :
260 : // Only used to check invariants.
261 : addL0FilesCalled bool
262 : }
263 :
264 : type sublevelSorter []*FileMetadata
265 :
266 : // Len implements sort.Interface.
267 1 : func (sl sublevelSorter) Len() int {
268 1 : return len(sl)
269 1 : }
270 :
271 : // Less implements sort.Interface.
272 1 : func (sl sublevelSorter) Less(i, j int) bool {
273 1 : return sl[i].minIntervalIndex < sl[j].minIntervalIndex
274 1 : }
275 :
276 : // Swap implements sort.Interface.
277 1 : func (sl sublevelSorter) Swap(i, j int) {
278 1 : sl[i], sl[j] = sl[j], sl[i]
279 1 : }
280 :
281 : // NewL0Sublevels creates an L0Sublevels instance for a given set of L0 files.
282 : // These files must all be in L0 and must be sorted by seqnum (see
283 : // SortBySeqNum). During interval iteration, when flushSplitMaxBytes bytes are
284 : // exceeded in the range of intervals since the last flush split key, a flush
285 : // split key is added.
286 : //
287 : // This method can be called without DB.mu being held, so any DB.mu protected
288 : // fields in FileMetadata cannot be accessed here, such as Compacting and
289 : // IsIntraL0Compacting. Those fields are accessed in InitCompactingFileInfo
290 : // instead.
291 : func NewL0Sublevels(
292 : levelMetadata *LevelMetadata, cmp Compare, formatKey base.FormatKey, flushSplitMaxBytes int64,
293 1 : ) (*L0Sublevels, error) {
294 1 : s := &L0Sublevels{cmp: cmp, formatKey: formatKey}
295 1 : s.levelMetadata = levelMetadata
296 1 : keys := make([]intervalKeyTemp, 0, 2*s.levelMetadata.Len())
297 1 : iter := levelMetadata.Iter()
298 1 : for i, f := 0, iter.First(); f != nil; i, f = i+1, iter.Next() {
299 1 : f.L0Index = i
300 1 : keys = append(keys, intervalKeyTemp{
301 1 : intervalKey: intervalKey{key: f.Smallest.UserKey},
302 1 : fileMeta: f,
303 1 : isEndKey: false,
304 1 : })
305 1 : keys = append(keys, intervalKeyTemp{
306 1 : intervalKey: intervalKey{
307 1 : key: f.Largest.UserKey,
308 1 : isInclusiveEndBound: !f.Largest.IsExclusiveSentinel(),
309 1 : },
310 1 : fileMeta: f,
311 1 : isEndKey: true,
312 1 : })
313 1 : }
314 1 : keys = sortAndSweep(keys, cmp)
315 1 : // All interval indices reference s.orderedIntervals.
316 1 : s.orderedIntervals = make([]fileInterval, len(keys))
317 1 : for i := range keys {
318 1 : s.orderedIntervals[i] = fileInterval{
319 1 : index: i,
320 1 : startKey: keys[i].intervalKey,
321 1 : filesMinIntervalIndex: i,
322 1 : filesMaxIntervalIndex: i,
323 1 : }
324 1 : }
325 : // Initialize minIntervalIndex and maxIntervalIndex for each file, and use that
326 : // to update intervals.
327 1 : for f := iter.First(); f != nil; f = iter.Next() {
328 1 : if err := s.addFileToSublevels(f, false /* checkInvariant */); err != nil {
329 0 : return nil, err
330 0 : }
331 : }
332 : // Sort each sublevel in increasing key order.
333 1 : for i := range s.levelFiles {
334 1 : sort.Sort(sublevelSorter(s.levelFiles[i]))
335 1 : }
336 :
337 : // Construct a parallel slice of sublevel B-Trees.
338 : // TODO(jackson): Consolidate and only use the B-Trees.
339 1 : for _, sublevelFiles := range s.levelFiles {
340 1 : tr, ls := makeBTree(btreeCmpSmallestKey(cmp), sublevelFiles)
341 1 : s.Levels = append(s.Levels, ls)
342 1 : tr.Release()
343 1 : }
344 :
345 1 : s.calculateFlushSplitKeys(flushSplitMaxBytes)
346 1 : return s, nil
347 : }
348 :
349 : // Helper function to merge new intervalKeys into an existing slice of old
350 : // fileIntervals, into result. Returns the new result and a slice of ints
351 : // mapping old interval indices to new ones. The added intervalKeys do not need
352 : // to be sorted; they get sorted and deduped in this function.
353 : func mergeIntervals(
354 : old, result []fileInterval, added []intervalKeyTemp, compare Compare,
355 1 : ) ([]fileInterval, []int) {
356 1 : sorter := intervalKeySorter{keys: added, cmp: compare}
357 1 : sort.Sort(sorter)
358 1 :
359 1 : oldToNewMap := make([]int, len(old))
360 1 : i := 0
361 1 : j := 0
362 1 :
363 1 : for i < len(old) || j < len(added) {
364 1 : for j > 0 && j < len(added) && intervalKeyCompare(compare, added[j-1].intervalKey, added[j].intervalKey) == 0 {
365 1 : added[j].setFileIntervalIndex(len(result) - 1)
366 1 : j++
367 1 : }
368 1 : if i >= len(old) && j >= len(added) {
369 1 : break
370 : }
371 1 : var cmp int
372 1 : if i >= len(old) {
373 1 : cmp = +1
374 1 : }
375 1 : if j >= len(added) {
376 1 : cmp = -1
377 1 : }
378 1 : if cmp == 0 {
379 1 : cmp = intervalKeyCompare(compare, old[i].startKey, added[j].intervalKey)
380 1 : }
381 1 : switch {
382 1 : case cmp <= 0:
383 1 : // Shallow-copy the existing interval.
384 1 : newInterval := old[i]
385 1 : result = append(result, newInterval)
386 1 : oldToNewMap[i] = len(result) - 1
387 1 : i++
388 1 : if cmp == 0 {
389 1 : added[j].setFileIntervalIndex(len(result) - 1)
390 1 : j++
391 1 : }
392 1 : case cmp > 0:
393 1 : var prevInterval fileInterval
394 1 : // Insert a new interval for a newly-added file. prevInterval, if
395 1 : // non-zero, will be "inherited"; we copy its files as those extend
396 1 : // into this interval.
397 1 : if len(result) > 0 {
398 1 : prevInterval = result[len(result)-1]
399 1 : }
400 1 : newInterval := fileInterval{
401 1 : index: len(result),
402 1 : startKey: added[j].intervalKey,
403 1 : filesMinIntervalIndex: len(result),
404 1 : filesMaxIntervalIndex: len(result),
405 1 :
406 1 : // estimatedBytes gets recalculated later on, as the number of intervals
407 1 : // the file bytes are interpolated over has changed.
408 1 : estimatedBytes: 0,
409 1 : // Copy the below attributes from prevInterval.
410 1 : files: append([]*FileMetadata(nil), prevInterval.files...),
411 1 : isBaseCompacting: prevInterval.isBaseCompacting,
412 1 : intervalRangeIsBaseCompacting: prevInterval.intervalRangeIsBaseCompacting,
413 1 : compactingFileCount: prevInterval.compactingFileCount,
414 1 : }
415 1 : result = append(result, newInterval)
416 1 : added[j].setFileIntervalIndex(len(result) - 1)
417 1 : j++
418 : }
419 : }
420 1 : return result, oldToNewMap
421 : }
422 :
423 : // AddL0Files incrementally builds a new L0Sublevels for when the only change
424 : // since the receiver L0Sublevels was an addition of the specified files, with
425 : // no L0 deletions. The common case of this is an ingestion or a flush. These
426 : // files can "sit on top" of existing sublevels, creating at most one new
427 : // sublevel for a flush (and possibly multiple for an ingestion), and at most
428 : // 2*len(files) additions to s.orderedIntervals. No files must have been deleted
429 : // from L0, and the added files must all be newer in sequence numbers than
430 : // existing files in L0Sublevels. The files parameter must be sorted in seqnum
431 : // order. The levelMetadata parameter corresponds to the new L0 post addition of
432 : // files. This method is meant to be significantly more performant than
433 : // NewL0Sublevels.
434 : //
435 : // Note that this function can only be called once on a given receiver; it
436 : // appends to some slices in s which is only safe when done once. This is okay,
437 : // as the common case (generating a new L0Sublevels after a flush/ingestion) is
438 : // only going to necessitate one call of this method on a given receiver. The
439 : // returned value, if non-nil, can then have [*L0Sublevels.AddL0Files] called on
440 : // it again, and so on. If [errInvalidL0SublevelsOpt] is returned as an error,
441 : // it likely means the optimization could not be applied (i.e. files added were
442 : // older than files already in the sublevels, which is possible around
443 : // ingestions and in tests). Eg. it can happen when an ingested file was
444 : // ingested without queueing a flush since it did not actually overlap with any
445 : // keys in the memtable. Later on the memtable was flushed, and the memtable had
446 : // keys spanning around the ingested file, producing a flushed file that
447 : // overlapped with the ingested file in file bounds but not in keys. It's
448 : // possible for that flushed file to have a lower LargestSeqNum than the
449 : // ingested file if all the additions after the ingestion were to another
450 : // flushed file that was split into a separate sstable during flush. Any other
451 : // non-nil error means [L0Sublevels] generation failed in the same way as
452 : // [NewL0Sublevels] would likely fail.
453 : func (s *L0Sublevels) AddL0Files(
454 : files []*FileMetadata, flushSplitMaxBytes int64, levelMetadata *LevelMetadata,
455 1 : ) (*L0Sublevels, error) {
456 1 : if invariants.Enabled && s.addL0FilesCalled {
457 0 : panic("AddL0Files called twice on the same receiver")
458 : }
459 1 : s.addL0FilesCalled = true
460 1 :
461 1 : // Start with a shallow copy of s.
462 1 : newVal := &L0Sublevels{}
463 1 : *newVal = *s
464 1 :
465 1 : newVal.addL0FilesCalled = false
466 1 : newVal.levelMetadata = levelMetadata
467 1 : // Deep copy levelFiles and Levels, as they are mutated and sorted below.
468 1 : // Shallow copies of slices that we just append to, are okay.
469 1 : newVal.levelFiles = make([][]*FileMetadata, len(s.levelFiles))
470 1 : for i := range s.levelFiles {
471 1 : newVal.levelFiles[i] = make([]*FileMetadata, len(s.levelFiles[i]))
472 1 : copy(newVal.levelFiles[i], s.levelFiles[i])
473 1 : }
474 1 : newVal.Levels = make([]LevelSlice, len(s.Levels))
475 1 : copy(newVal.Levels, s.Levels)
476 1 :
477 1 : fileKeys := make([]intervalKeyTemp, 0, 2*len(files))
478 1 : for _, f := range files {
479 1 : left := intervalKeyTemp{
480 1 : intervalKey: intervalKey{key: f.Smallest.UserKey},
481 1 : fileMeta: f,
482 1 : }
483 1 : right := intervalKeyTemp{
484 1 : intervalKey: intervalKey{
485 1 : key: f.Largest.UserKey,
486 1 : isInclusiveEndBound: !f.Largest.IsExclusiveSentinel(),
487 1 : },
488 1 : fileMeta: f,
489 1 : isEndKey: true,
490 1 : }
491 1 : fileKeys = append(fileKeys, left, right)
492 1 : }
493 1 : keys := make([]fileInterval, 0, 2*levelMetadata.Len())
494 1 : var oldToNewMap []int
495 1 : // We can avoid the sortAndSweep step on the combined length of
496 1 : // s.orderedIntervals and fileKeys by treating this as a merge of two sorted
497 1 : // runs, fileKeys and s.orderedIntervals, into `keys` which will form
498 1 : // newVal.orderedIntervals.
499 1 : keys, oldToNewMap = mergeIntervals(s.orderedIntervals, keys, fileKeys, s.cmp)
500 1 : if invariants.Enabled {
501 1 : for i := 1; i < len(keys); i++ {
502 1 : if intervalKeyCompare(newVal.cmp, keys[i-1].startKey, keys[i].startKey) >= 0 {
503 0 : panic("keys not sorted correctly")
504 : }
505 : }
506 : }
507 1 : newVal.orderedIntervals = keys
508 1 : // Update indices in s.orderedIntervals for fileIntervals we retained.
509 1 : for _, newIdx := range oldToNewMap {
510 1 : newInterval := &keys[newIdx]
511 1 : newInterval.index = newIdx
512 1 : // This code, and related code in the for loop below, adjusts
513 1 : // files{Min,Max}IntervalIndex just for interval indices shifting due to
514 1 : // new intervals, and not for any of the new files being added to the
515 1 : // same intervals. The goal is to produce a state of the system that's
516 1 : // accurate for all existing files, and has all the new intervals to
517 1 : // support new files. Once that's done, we can just call
518 1 : // addFileToSublevel to adjust all relevant intervals for new files.
519 1 : newInterval.filesMinIntervalIndex = oldToNewMap[newInterval.filesMinIntervalIndex]
520 1 : // maxIntervalIndexes are special. Since it's an inclusive end bound, we
521 1 : // actually have to map it to the _next_ old interval's new previous
522 1 : // interval. This logic is easier to understand if you see
523 1 : // [f.minIntervalIndex, f.maxIntervalIndex] as [f.minIntervalIndex,
524 1 : // f.maxIntervalIndex+1). The other case to remember is when the
525 1 : // interval is completely empty (i.e. len(newInterval.files) == 0); in
526 1 : // that case we want to refer back to ourselves regardless of additions
527 1 : // to the right of us.
528 1 : if newInterval.filesMaxIntervalIndex < len(oldToNewMap)-1 && len(newInterval.files) > 0 {
529 1 : newInterval.filesMaxIntervalIndex = oldToNewMap[newInterval.filesMaxIntervalIndex+1] - 1
530 1 : } else {
531 1 : // newInterval.filesMaxIntervalIndex == len(oldToNewMap)-1.
532 1 : newInterval.filesMaxIntervalIndex = oldToNewMap[newInterval.filesMaxIntervalIndex]
533 1 : }
534 : }
535 : // Loop through all instances of new intervals added between two old
536 : // intervals and expand [filesMinIntervalIndex, filesMaxIntervalIndex] of
537 : // new intervals to reflect that of adjacent old intervals.
538 1 : {
539 1 : // We can skip cases where new intervals were added to the left of all
540 1 : // existing intervals (eg. if the first entry in oldToNewMap is
541 1 : // oldToNewMap[0] >= 1). Those intervals will only contain newly added
542 1 : // files and will have their parameters adjusted down in
543 1 : // addFileToSublevels. The same can also be said about new intervals
544 1 : // that are to the right of all existing intervals.
545 1 : lastIdx := 0
546 1 : for _, newIdx := range oldToNewMap {
547 1 : for i := lastIdx + 1; i < newIdx; i++ {
548 1 : minIntervalIndex := i
549 1 : maxIntervalIndex := i
550 1 : if keys[lastIdx].filesMaxIntervalIndex != lastIdx {
551 1 : // Last old interval has files extending into keys[i].
552 1 : minIntervalIndex = keys[lastIdx].filesMinIntervalIndex
553 1 : maxIntervalIndex = keys[lastIdx].filesMaxIntervalIndex
554 1 : }
555 :
556 1 : keys[i].filesMinIntervalIndex = minIntervalIndex
557 1 : keys[i].filesMaxIntervalIndex = maxIntervalIndex
558 : }
559 1 : lastIdx = newIdx
560 : }
561 : }
562 : // Go through old files and update interval indices.
563 : //
564 : // TODO(bilal): This is the only place in this method where we loop through
565 : // all existing files, which could be much more in number than newly added
566 : // files. See if we can avoid the need for this, either by getting rid of
567 : // f.minIntervalIndex and f.maxIntervalIndex and calculating them on the fly
568 : // with a binary search, or by only looping through files to the right of
569 : // the first interval touched by this method.
570 1 : for sublevel := range s.Levels {
571 1 : s.Levels[sublevel].Each(func(f *FileMetadata) {
572 1 : oldIntervalDelta := f.maxIntervalIndex - f.minIntervalIndex + 1
573 1 : oldMinIntervalIndex := f.minIntervalIndex
574 1 : f.minIntervalIndex = oldToNewMap[f.minIntervalIndex]
575 1 : // maxIntervalIndex is special. Since it's an inclusive end bound,
576 1 : // we actually have to map it to the _next_ old interval's new
577 1 : // previous interval. This logic is easier to understand if you see
578 1 : // [f.minIntervalIndex, f.maxIntervalIndex] as [f.minIntervalIndex,
579 1 : // f.maxIntervalIndex+1).
580 1 : f.maxIntervalIndex = oldToNewMap[f.maxIntervalIndex+1] - 1
581 1 : newIntervalDelta := f.maxIntervalIndex - f.minIntervalIndex + 1
582 1 : // Recalculate estimatedBytes for all old files across new
583 1 : // intervals, but only if new intervals were added in between.
584 1 : if oldIntervalDelta != newIntervalDelta {
585 1 : // j is incremented so that oldToNewMap[j] points to the next
586 1 : // old interval. This is used to distinguish between old
587 1 : // intervals (i.e. ones where we need to subtract
588 1 : // f.Size/oldIntervalDelta) from new ones (where we don't need
589 1 : // to subtract). In both cases we need to add
590 1 : // f.Size/newIntervalDelta.
591 1 : j := oldMinIntervalIndex
592 1 : for i := f.minIntervalIndex; i <= f.maxIntervalIndex; i++ {
593 1 : if oldToNewMap[j] == i {
594 1 : newVal.orderedIntervals[i].estimatedBytes -= f.Size / uint64(oldIntervalDelta)
595 1 : j++
596 1 : }
597 1 : newVal.orderedIntervals[i].estimatedBytes += f.Size / uint64(newIntervalDelta)
598 : }
599 : }
600 : })
601 : }
602 1 : updatedSublevels := make([]int, 0)
603 1 : // Update interval indices for new files.
604 1 : for i, f := range files {
605 1 : f.L0Index = s.levelMetadata.Len() + i
606 1 : if err := newVal.addFileToSublevels(f, true /* checkInvariant */); err != nil {
607 1 : return nil, err
608 1 : }
609 1 : updatedSublevels = append(updatedSublevels, f.SubLevel)
610 : }
611 :
612 : // Sort and deduplicate updatedSublevels.
613 1 : sort.Ints(updatedSublevels)
614 1 : {
615 1 : j := 0
616 1 : for i := 1; i < len(updatedSublevels); i++ {
617 1 : if updatedSublevels[i] != updatedSublevels[j] {
618 1 : j++
619 1 : updatedSublevels[j] = updatedSublevels[i]
620 1 : }
621 : }
622 1 : updatedSublevels = updatedSublevels[:j+1]
623 : }
624 :
625 : // Sort each updated sublevel in increasing key order.
626 1 : for _, sublevel := range updatedSublevels {
627 1 : sort.Sort(sublevelSorter(newVal.levelFiles[sublevel]))
628 1 : }
629 :
630 : // Construct a parallel slice of sublevel B-Trees.
631 : // TODO(jackson): Consolidate and only use the B-Trees.
632 1 : for _, sublevel := range updatedSublevels {
633 1 : tr, ls := makeBTree(btreeCmpSmallestKey(newVal.cmp), newVal.levelFiles[sublevel])
634 1 : if sublevel == len(newVal.Levels) {
635 1 : newVal.Levels = append(newVal.Levels, ls)
636 1 : } else {
637 1 : // sublevel < len(s.Levels). If this panics, updatedSublevels was not
638 1 : // populated correctly.
639 1 : newVal.Levels[sublevel] = ls
640 1 : }
641 1 : tr.Release()
642 : }
643 :
644 1 : newVal.flushSplitUserKeys = nil
645 1 : newVal.calculateFlushSplitKeys(flushSplitMaxBytes)
646 1 : return newVal, nil
647 : }
648 :
649 : // addFileToSublevels is called during L0Sublevels generation, and adds f to the
650 : // correct sublevel's levelFiles, the relevant intervals' files slices, and sets
651 : // interval indices on f. This method, if called successively on multiple files,
652 : // _must_ be called on successively newer files (by seqnum). If checkInvariant
653 : // is true, it could check for this in some cases and return
654 : // [errInvalidL0SublevelsOpt] if that invariant isn't held.
655 1 : func (s *L0Sublevels) addFileToSublevels(f *FileMetadata, checkInvariant bool) error {
656 1 : // This is a simple and not very accurate estimate of the number of
657 1 : // bytes this SSTable contributes to the intervals it is a part of.
658 1 : //
659 1 : // TODO(bilal): Call EstimateDiskUsage in sstable.Reader with interval
660 1 : // bounds to get a better estimate for each interval.
661 1 : interpolatedBytes := f.Size / uint64(f.maxIntervalIndex-f.minIntervalIndex+1)
662 1 : s.fileBytes += f.Size
663 1 : subLevel := 0
664 1 : // Update state in every fileInterval for this file.
665 1 : for i := f.minIntervalIndex; i <= f.maxIntervalIndex; i++ {
666 1 : interval := &s.orderedIntervals[i]
667 1 : if len(interval.files) > 0 {
668 1 : if checkInvariant && interval.files[len(interval.files)-1].LargestSeqNum > f.LargestSeqNum {
669 1 : // We are sliding this file "underneath" an existing file. Throw away
670 1 : // and start over in NewL0Sublevels.
671 1 : return errInvalidL0SublevelsOpt
672 1 : }
673 : // interval.files is sorted by sublevels, from lowest to highest.
674 : // AddL0Files can only add files at sublevels higher than existing files
675 : // in the same key intervals.
676 1 : if maxSublevel := interval.files[len(interval.files)-1].SubLevel; subLevel <= maxSublevel {
677 1 : subLevel = maxSublevel + 1
678 1 : }
679 : }
680 1 : interval.estimatedBytes += interpolatedBytes
681 1 : if f.minIntervalIndex < interval.filesMinIntervalIndex {
682 1 : interval.filesMinIntervalIndex = f.minIntervalIndex
683 1 : }
684 1 : if f.maxIntervalIndex > interval.filesMaxIntervalIndex {
685 1 : interval.filesMaxIntervalIndex = f.maxIntervalIndex
686 1 : }
687 1 : interval.files = append(interval.files, f)
688 : }
689 1 : f.SubLevel = subLevel
690 1 : if subLevel > len(s.levelFiles) {
691 0 : return errors.Errorf("chose a sublevel beyond allowed range of sublevels: %d vs 0-%d", subLevel, len(s.levelFiles))
692 0 : }
693 1 : if subLevel == len(s.levelFiles) {
694 1 : s.levelFiles = append(s.levelFiles, []*FileMetadata{f})
695 1 : } else {
696 1 : s.levelFiles[subLevel] = append(s.levelFiles[subLevel], f)
697 1 : }
698 1 : return nil
699 : }
700 :
701 1 : func (s *L0Sublevels) calculateFlushSplitKeys(flushSplitMaxBytes int64) {
702 1 : var cumulativeBytes uint64
703 1 : // Multiply flushSplitMaxBytes by the number of sublevels. This prevents
704 1 : // excessive flush splitting when the number of sublevels increases.
705 1 : flushSplitMaxBytes *= int64(len(s.levelFiles))
706 1 : for i := 0; i < len(s.orderedIntervals); i++ {
707 1 : interval := &s.orderedIntervals[i]
708 1 : if flushSplitMaxBytes > 0 && cumulativeBytes > uint64(flushSplitMaxBytes) &&
709 1 : (len(s.flushSplitUserKeys) == 0 ||
710 1 : !bytes.Equal(interval.startKey.key, s.flushSplitUserKeys[len(s.flushSplitUserKeys)-1])) {
711 1 : s.flushSplitUserKeys = append(s.flushSplitUserKeys, interval.startKey.key)
712 1 : cumulativeBytes = 0
713 1 : }
714 1 : cumulativeBytes += s.orderedIntervals[i].estimatedBytes
715 : }
716 : }
717 :
718 : // InitCompactingFileInfo initializes internal flags relating to compacting
719 : // files. Must be called after sublevel initialization.
720 : //
721 : // Requires DB.mu *and* the manifest lock to be held.
722 1 : func (s *L0Sublevels) InitCompactingFileInfo(inProgress []L0Compaction) {
723 1 : for i := range s.orderedIntervals {
724 1 : s.orderedIntervals[i].compactingFileCount = 0
725 1 : s.orderedIntervals[i].isBaseCompacting = false
726 1 : s.orderedIntervals[i].intervalRangeIsBaseCompacting = false
727 1 : }
728 :
729 1 : iter := s.levelMetadata.Iter()
730 1 : for f := iter.First(); f != nil; f = iter.Next() {
731 1 : if invariants.Enabled {
732 1 : if !bytes.Equal(s.orderedIntervals[f.minIntervalIndex].startKey.key, f.Smallest.UserKey) {
733 0 : panic(fmt.Sprintf("f.minIntervalIndex in FileMetadata out of sync with intervals in L0Sublevels: %s != %s",
734 0 : s.formatKey(s.orderedIntervals[f.minIntervalIndex].startKey.key), s.formatKey(f.Smallest.UserKey)))
735 : }
736 1 : if !bytes.Equal(s.orderedIntervals[f.maxIntervalIndex+1].startKey.key, f.Largest.UserKey) {
737 0 : panic(fmt.Sprintf("f.maxIntervalIndex in FileMetadata out of sync with intervals in L0Sublevels: %s != %s",
738 0 : s.formatKey(s.orderedIntervals[f.maxIntervalIndex+1].startKey.key), s.formatKey(f.Smallest.UserKey)))
739 : }
740 : }
741 1 : if !f.IsCompacting() {
742 1 : continue
743 : }
744 1 : if invariants.Enabled {
745 1 : if s.cmp(s.orderedIntervals[f.minIntervalIndex].startKey.key, f.Smallest.UserKey) != 0 || s.cmp(s.orderedIntervals[f.maxIntervalIndex+1].startKey.key, f.Largest.UserKey) != 0 {
746 0 : panic(fmt.Sprintf("file %s has inconsistent L0 Sublevel interval bounds: %s-%s, %s-%s", f.FileNum,
747 0 : s.orderedIntervals[f.minIntervalIndex].startKey.key, s.orderedIntervals[f.maxIntervalIndex+1].startKey.key,
748 0 : f.Smallest.UserKey, f.Largest.UserKey))
749 : }
750 : }
751 1 : for i := f.minIntervalIndex; i <= f.maxIntervalIndex; i++ {
752 1 : interval := &s.orderedIntervals[i]
753 1 : interval.compactingFileCount++
754 1 : if !f.IsIntraL0Compacting {
755 1 : // If f.Compacting && !f.IsIntraL0Compacting, this file is
756 1 : // being compacted to Lbase.
757 1 : interval.isBaseCompacting = true
758 1 : }
759 : }
760 : }
761 :
762 : // Some intervals may be base compacting without the files contained within
763 : // those intervals being marked as compacting. This is possible if the files
764 : // were added after the compaction initiated, and the active compaction
765 : // files straddle the input file. Mark these intervals as base compacting.
766 1 : for _, c := range inProgress {
767 1 : startIK := intervalKey{key: c.Smallest.UserKey, isInclusiveEndBound: false}
768 1 : endIK := intervalKey{key: c.Largest.UserKey, isInclusiveEndBound: !c.Largest.IsExclusiveSentinel()}
769 1 : start, _ := slices.BinarySearchFunc(s.orderedIntervals, startIK, func(a fileInterval, b intervalKey) int {
770 1 : return intervalKeyCompare(s.cmp, a.startKey, b)
771 1 : })
772 1 : end, _ := slices.BinarySearchFunc(s.orderedIntervals, endIK, func(a fileInterval, b intervalKey) int {
773 1 : return intervalKeyCompare(s.cmp, a.startKey, b)
774 1 : })
775 1 : for i := start; i < end && i < len(s.orderedIntervals); i++ {
776 1 : interval := &s.orderedIntervals[i]
777 1 : if !c.IsIntraL0 {
778 1 : interval.isBaseCompacting = true
779 1 : }
780 : }
781 : }
782 :
783 1 : min := 0
784 1 : for i := range s.orderedIntervals {
785 1 : interval := &s.orderedIntervals[i]
786 1 : if interval.isBaseCompacting {
787 1 : minIndex := interval.filesMinIntervalIndex
788 1 : if minIndex < min {
789 1 : minIndex = min
790 1 : }
791 1 : for j := minIndex; j <= interval.filesMaxIntervalIndex; j++ {
792 1 : min = j
793 1 : s.orderedIntervals[j].intervalRangeIsBaseCompacting = true
794 1 : }
795 : }
796 : }
797 : }
798 :
799 : // String produces a string containing useful debug information. Useful in test
800 : // code and debugging.
801 0 : func (s *L0Sublevels) String() string {
802 0 : return s.describe(false)
803 0 : }
804 :
805 1 : func (s *L0Sublevels) describe(verbose bool) string {
806 1 : var buf strings.Builder
807 1 : fmt.Fprintf(&buf, "file count: %d, sublevels: %d, intervals: %d\nflush split keys(%d): [",
808 1 : s.levelMetadata.Len(), len(s.levelFiles), len(s.orderedIntervals), len(s.flushSplitUserKeys))
809 1 : for i := range s.flushSplitUserKeys {
810 1 : fmt.Fprintf(&buf, "%s", s.formatKey(s.flushSplitUserKeys[i]))
811 1 : if i < len(s.flushSplitUserKeys)-1 {
812 1 : fmt.Fprintf(&buf, ", ")
813 1 : }
814 : }
815 1 : fmt.Fprintln(&buf, "]")
816 1 : numCompactingFiles := 0
817 1 : for i := len(s.levelFiles) - 1; i >= 0; i-- {
818 1 : maxIntervals := 0
819 1 : sumIntervals := 0
820 1 : var totalBytes uint64
821 1 : for _, f := range s.levelFiles[i] {
822 1 : intervals := f.maxIntervalIndex - f.minIntervalIndex + 1
823 1 : if intervals > maxIntervals {
824 1 : maxIntervals = intervals
825 1 : }
826 1 : sumIntervals += intervals
827 1 : totalBytes += f.Size
828 1 : if f.IsCompacting() {
829 1 : numCompactingFiles++
830 1 : }
831 : }
832 1 : fmt.Fprintf(&buf, "0.%d: file count: %d, bytes: %d, width (mean, max): %0.1f, %d, interval range: [%d, %d]\n",
833 1 : i, len(s.levelFiles[i]), totalBytes, float64(sumIntervals)/float64(len(s.levelFiles[i])), maxIntervals, s.levelFiles[i][0].minIntervalIndex,
834 1 : s.levelFiles[i][len(s.levelFiles[i])-1].maxIntervalIndex)
835 1 : for _, f := range s.levelFiles[i] {
836 1 : intervals := f.maxIntervalIndex - f.minIntervalIndex + 1
837 1 : if verbose {
838 1 : fmt.Fprintf(&buf, "\t%s\n", f)
839 1 : }
840 1 : if s.levelMetadata.Len() > 50 && intervals*3 > len(s.orderedIntervals) {
841 0 : var intervalsBytes uint64
842 0 : for k := f.minIntervalIndex; k <= f.maxIntervalIndex; k++ {
843 0 : intervalsBytes += s.orderedIntervals[k].estimatedBytes
844 0 : }
845 0 : fmt.Fprintf(&buf, "wide file: %d, [%d, %d], byte fraction: %f\n",
846 0 : f.FileNum, f.minIntervalIndex, f.maxIntervalIndex,
847 0 : float64(intervalsBytes)/float64(s.fileBytes))
848 : }
849 : }
850 : }
851 :
852 1 : lastCompactingIntervalStart := -1
853 1 : fmt.Fprintf(&buf, "compacting file count: %d, base compacting intervals: ", numCompactingFiles)
854 1 : i := 0
855 1 : foundBaseCompactingIntervals := false
856 1 : for ; i < len(s.orderedIntervals); i++ {
857 1 : interval := &s.orderedIntervals[i]
858 1 : if len(interval.files) == 0 {
859 1 : continue
860 : }
861 1 : if !interval.isBaseCompacting {
862 1 : if lastCompactingIntervalStart != -1 {
863 1 : if foundBaseCompactingIntervals {
864 1 : buf.WriteString(", ")
865 1 : }
866 1 : fmt.Fprintf(&buf, "[%d, %d]", lastCompactingIntervalStart, i-1)
867 1 : foundBaseCompactingIntervals = true
868 : }
869 1 : lastCompactingIntervalStart = -1
870 1 : } else {
871 1 : if lastCompactingIntervalStart == -1 {
872 1 : lastCompactingIntervalStart = i
873 1 : }
874 : }
875 : }
876 1 : if lastCompactingIntervalStart != -1 {
877 1 : if foundBaseCompactingIntervals {
878 1 : buf.WriteString(", ")
879 1 : }
880 1 : fmt.Fprintf(&buf, "[%d, %d]", lastCompactingIntervalStart, i-1)
881 1 : } else if !foundBaseCompactingIntervals {
882 1 : fmt.Fprintf(&buf, "none")
883 1 : }
884 1 : fmt.Fprintln(&buf, "")
885 1 : return buf.String()
886 : }
887 :
888 : // ReadAmplification returns the contribution of L0Sublevels to the read
889 : // amplification for any particular point key. It is the maximum height of any
890 : // tracked fileInterval. This is always less than or equal to the number of
891 : // sublevels.
892 1 : func (s *L0Sublevels) ReadAmplification() int {
893 1 : amp := 0
894 1 : for i := range s.orderedIntervals {
895 1 : interval := &s.orderedIntervals[i]
896 1 : fileCount := len(interval.files)
897 1 : if amp < fileCount {
898 1 : amp = fileCount
899 1 : }
900 : }
901 1 : return amp
902 : }
903 :
904 : // InUseKeyRanges returns the merged table bounds of L0 files overlapping the
905 : // provided user key range. The returned key ranges are sorted and
906 : // nonoverlapping.
907 1 : func (s *L0Sublevels) InUseKeyRanges(smallest, largest []byte) []base.UserKeyBounds {
908 1 : // Binary search to find the provided keys within the intervals.
909 1 : startIK := intervalKey{key: smallest, isInclusiveEndBound: false}
910 1 : endIK := intervalKey{key: largest, isInclusiveEndBound: true}
911 1 : start := sort.Search(len(s.orderedIntervals), func(i int) bool {
912 1 : return intervalKeyCompare(s.cmp, s.orderedIntervals[i].startKey, startIK) > 0
913 1 : })
914 1 : if start > 0 {
915 1 : // Back up to the first interval with a start key <= startIK.
916 1 : start--
917 1 : }
918 1 : end := sort.Search(len(s.orderedIntervals), func(i int) bool {
919 1 : return intervalKeyCompare(s.cmp, s.orderedIntervals[i].startKey, endIK) > 0
920 1 : })
921 :
922 1 : var keyRanges []base.UserKeyBounds
923 1 : var curr *base.UserKeyBounds
924 1 : for i := start; i < end; {
925 1 : // Intervals with no files are not in use and can be skipped, once we
926 1 : // end the current UserKeyRange.
927 1 : if len(s.orderedIntervals[i].files) == 0 {
928 1 : curr = nil
929 1 : i++
930 1 : continue
931 : }
932 :
933 : // If curr is nil, start a new in-use key range.
934 1 : if curr == nil {
935 1 : keyRanges = append(keyRanges, base.UserKeyBounds{
936 1 : Start: s.orderedIntervals[i].startKey.key,
937 1 : })
938 1 : curr = &keyRanges[len(keyRanges)-1]
939 1 : }
940 :
941 : // If the filesMaxIntervalIndex is not the current index, we can jump to
942 : // the max index, knowing that all intermediary intervals are overlapped
943 : // by some file.
944 1 : if maxIdx := s.orderedIntervals[i].filesMaxIntervalIndex; maxIdx != i {
945 1 : // Note that end may be less than or equal to maxIdx if we're
946 1 : // concerned with a key range that ends before the interval at
947 1 : // maxIdx starts. We must set curr.End now, before making that leap,
948 1 : // because this iteration may be the last.
949 1 : i = maxIdx
950 1 : curr.End = s.orderedIntervals[i+1].startKey.toEndBoundary()
951 1 : continue
952 : }
953 :
954 : // No files overlapping with this interval overlap with the next
955 : // interval. Update the current end to be the next interval's start key.
956 : // Note that curr is not necessarily finished, because there may be an
957 : // abutting non-empty interval.
958 1 : curr.End = s.orderedIntervals[i+1].startKey.toEndBoundary()
959 1 : i++
960 : }
961 1 : return keyRanges
962 : }
963 :
964 : // FlushSplitKeys returns a slice of user keys to split flushes at. Used by
965 : // flushes to avoid writing sstables that straddle these split keys. These
966 : // should be interpreted as the keys to start the next sstable (not the last key
967 : // to include in the prev sstable). These are user keys so that range tombstones
968 : // can be properly truncated (untruncated range tombstones are not permitted for
969 : // L0 files).
970 1 : func (s *L0Sublevels) FlushSplitKeys() [][]byte {
971 1 : return s.flushSplitUserKeys
972 1 : }
973 :
974 : // MaxDepthAfterOngoingCompactions returns an estimate of maximum depth of
975 : // sublevels after all ongoing compactions run to completion. Used by compaction
976 : // picker to decide compaction score for L0. There is no scoring for intra-L0
977 : // compactions -- they only run if L0 score is high but we're unable to pick an
978 : // L0 -> Lbase compaction.
979 1 : func (s *L0Sublevels) MaxDepthAfterOngoingCompactions() int {
980 1 : depth := 0
981 1 : for i := range s.orderedIntervals {
982 1 : interval := &s.orderedIntervals[i]
983 1 : intervalDepth := len(interval.files) - interval.compactingFileCount
984 1 : if depth < intervalDepth {
985 1 : depth = intervalDepth
986 1 : }
987 : }
988 1 : return depth
989 : }
990 :
991 : // Only for temporary debugging in the absence of proper tests.
992 : //
993 : // TODO(bilal): Simplify away the debugging statements in this method, and make
994 : // this a pure sanity checker.
995 : //
996 : //lint:ignore U1000 - useful for debugging
997 0 : func (s *L0Sublevels) checkCompaction(c *L0CompactionFiles) error {
998 0 : includedFiles := newBitSet(s.levelMetadata.Len())
999 0 : fileIntervalsByLevel := make([]struct {
1000 0 : min int
1001 0 : max int
1002 0 : }, len(s.levelFiles))
1003 0 : for i := range fileIntervalsByLevel {
1004 0 : fileIntervalsByLevel[i].min = math.MaxInt32
1005 0 : fileIntervalsByLevel[i].max = 0
1006 0 : }
1007 0 : var topLevel int
1008 0 : var increment int
1009 0 : var limitReached func(int) bool
1010 0 : if c.isIntraL0 {
1011 0 : topLevel = len(s.levelFiles) - 1
1012 0 : increment = +1
1013 0 : limitReached = func(level int) bool {
1014 0 : return level == len(s.levelFiles)
1015 0 : }
1016 0 : } else {
1017 0 : topLevel = 0
1018 0 : increment = -1
1019 0 : limitReached = func(level int) bool {
1020 0 : return level < 0
1021 0 : }
1022 : }
1023 0 : for _, f := range c.Files {
1024 0 : if fileIntervalsByLevel[f.SubLevel].min > f.minIntervalIndex {
1025 0 : fileIntervalsByLevel[f.SubLevel].min = f.minIntervalIndex
1026 0 : }
1027 0 : if fileIntervalsByLevel[f.SubLevel].max < f.maxIntervalIndex {
1028 0 : fileIntervalsByLevel[f.SubLevel].max = f.maxIntervalIndex
1029 0 : }
1030 0 : includedFiles.markBit(f.L0Index)
1031 0 : if c.isIntraL0 {
1032 0 : if topLevel > f.SubLevel {
1033 0 : topLevel = f.SubLevel
1034 0 : }
1035 0 : } else {
1036 0 : if topLevel < f.SubLevel {
1037 0 : topLevel = f.SubLevel
1038 0 : }
1039 : }
1040 : }
1041 0 : min := fileIntervalsByLevel[topLevel].min
1042 0 : max := fileIntervalsByLevel[topLevel].max
1043 0 : for level := topLevel; !limitReached(level); level += increment {
1044 0 : if fileIntervalsByLevel[level].min < min {
1045 0 : min = fileIntervalsByLevel[level].min
1046 0 : }
1047 0 : if fileIntervalsByLevel[level].max > max {
1048 0 : max = fileIntervalsByLevel[level].max
1049 0 : }
1050 0 : index, _ := slices.BinarySearchFunc(s.levelFiles[level], min, func(a *FileMetadata, b int) int {
1051 0 : return stdcmp.Compare(a.maxIntervalIndex, b)
1052 0 : })
1053 : // start := index
1054 0 : for ; index < len(s.levelFiles[level]); index++ {
1055 0 : f := s.levelFiles[level][index]
1056 0 : if f.minIntervalIndex > max {
1057 0 : break
1058 : }
1059 0 : if c.isIntraL0 && f.LargestSeqNum >= c.earliestUnflushedSeqNum {
1060 0 : return errors.Errorf(
1061 0 : "sstable %s in compaction has sequence numbers higher than the earliest unflushed seqnum %d: %d-%d",
1062 0 : f.FileNum, c.earliestUnflushedSeqNum, f.SmallestSeqNum,
1063 0 : f.LargestSeqNum)
1064 0 : }
1065 0 : if !includedFiles[f.L0Index] {
1066 0 : var buf strings.Builder
1067 0 : fmt.Fprintf(&buf, "bug %t, seed interval: %d: level %d, sl index %d, f.index %d, min %d, max %d, pre-min %d, pre-max %d, f.min %d, f.max %d, filenum: %d, isCompacting: %t\n%s\n",
1068 0 : c.isIntraL0, c.seedInterval, level, index, f.L0Index, min, max, c.preExtensionMinInterval, c.preExtensionMaxInterval,
1069 0 : f.minIntervalIndex, f.maxIntervalIndex,
1070 0 : f.FileNum, f.IsCompacting(), s)
1071 0 : fmt.Fprintf(&buf, "files included:\n")
1072 0 : for _, f := range c.Files {
1073 0 : fmt.Fprintf(&buf, "filenum: %d, sl: %d, index: %d, [%d, %d]\n",
1074 0 : f.FileNum, f.SubLevel, f.L0Index, f.minIntervalIndex, f.maxIntervalIndex)
1075 0 : }
1076 0 : fmt.Fprintf(&buf, "files added:\n")
1077 0 : for _, f := range c.filesAdded {
1078 0 : fmt.Fprintf(&buf, "filenum: %d, sl: %d, index: %d, [%d, %d]\n",
1079 0 : f.FileNum, f.SubLevel, f.L0Index, f.minIntervalIndex, f.maxIntervalIndex)
1080 0 : }
1081 0 : return errors.New(buf.String())
1082 : }
1083 : }
1084 : }
1085 0 : return nil
1086 : }
1087 :
1088 : // UpdateStateForStartedCompaction updates internal L0Sublevels state for a
1089 : // recently started compaction. isBase specifies if this is a base compaction;
1090 : // if false, this is assumed to be an intra-L0 compaction. The specified
1091 : // compaction must be involving L0 SSTables. It's assumed that the Compacting
1092 : // and IsIntraL0Compacting fields are already set on all [FileMetadata]s passed
1093 : // in.
1094 1 : func (s *L0Sublevels) UpdateStateForStartedCompaction(inputs []LevelSlice, isBase bool) error {
1095 1 : minIntervalIndex := -1
1096 1 : maxIntervalIndex := 0
1097 1 : for i := range inputs {
1098 1 : iter := inputs[i].Iter()
1099 1 : for f := iter.First(); f != nil; f = iter.Next() {
1100 1 : for i := f.minIntervalIndex; i <= f.maxIntervalIndex; i++ {
1101 1 : interval := &s.orderedIntervals[i]
1102 1 : interval.compactingFileCount++
1103 1 : }
1104 1 : if f.minIntervalIndex < minIntervalIndex || minIntervalIndex == -1 {
1105 1 : minIntervalIndex = f.minIntervalIndex
1106 1 : }
1107 1 : if f.maxIntervalIndex > maxIntervalIndex {
1108 1 : maxIntervalIndex = f.maxIntervalIndex
1109 1 : }
1110 : }
1111 : }
1112 1 : if isBase {
1113 1 : for i := minIntervalIndex; i <= maxIntervalIndex; i++ {
1114 1 : interval := &s.orderedIntervals[i]
1115 1 : interval.isBaseCompacting = isBase
1116 1 : for j := interval.filesMinIntervalIndex; j <= interval.filesMaxIntervalIndex; j++ {
1117 1 : s.orderedIntervals[j].intervalRangeIsBaseCompacting = true
1118 1 : }
1119 : }
1120 : }
1121 1 : return nil
1122 : }
1123 :
1124 : // L0CompactionFiles represents a candidate set of L0 files for compaction. Also
1125 : // referred to as "lcf". Contains state information useful for generating the
1126 : // compaction (such as Files), as well as for picking between candidate
1127 : // compactions (eg. fileBytes and seedIntervalStackDepthReduction).
1128 : type L0CompactionFiles struct {
1129 : Files []*FileMetadata
1130 :
1131 : FilesIncluded bitSet
1132 : // A "seed interval" is an interval with a high stack depth that was chosen
1133 : // to bootstrap this compaction candidate. seedIntervalStackDepthReduction
1134 : // is the number of sublevels that have a file in the seed interval that is
1135 : // a part of this compaction.
1136 : seedIntervalStackDepthReduction int
1137 : // For base compactions, seedIntervalMinLevel is 0, and for intra-L0
1138 : // compactions, seedIntervalMaxLevel is len(s.Files)-1 i.e. the highest
1139 : // sublevel.
1140 : seedIntervalMinLevel int
1141 : seedIntervalMaxLevel int
1142 : // Index of the seed interval.
1143 : seedInterval int
1144 : // Sum of file sizes for all files in this compaction.
1145 : fileBytes uint64
1146 : // Intervals with index [minIntervalIndex, maxIntervalIndex] are
1147 : // participating in this compaction; it's the union set of all intervals
1148 : // overlapped by participating files.
1149 : minIntervalIndex int
1150 : maxIntervalIndex int
1151 :
1152 : // Set for intra-L0 compactions. SSTables with sequence numbers greater
1153 : // than earliestUnflushedSeqNum cannot be a part of intra-L0 compactions.
1154 : isIntraL0 bool
1155 : earliestUnflushedSeqNum base.SeqNum
1156 :
1157 : // For debugging purposes only. Used in checkCompaction().
1158 : preExtensionMinInterval int
1159 : preExtensionMaxInterval int
1160 : filesAdded []*FileMetadata
1161 : }
1162 :
1163 : // Clone allocates a new L0CompactionFiles, with the same underlying data. Note
1164 : // that the two fileMetadata slices contain values that point to the same
1165 : // underlying fileMetadata object. This is safe because these objects are read
1166 : // only.
1167 1 : func (l *L0CompactionFiles) Clone() *L0CompactionFiles {
1168 1 : oldLcf := *l
1169 1 : return &oldLcf
1170 1 : }
1171 :
1172 : // String merely prints the starting address of the first file, if it exists.
1173 1 : func (l *L0CompactionFiles) String() string {
1174 1 : if len(l.Files) > 0 {
1175 1 : return fmt.Sprintf("First File Address: %p", &l.Files[0])
1176 1 : }
1177 0 : return ""
1178 : }
1179 :
1180 : // addFile adds the specified file to the LCF.
1181 1 : func (l *L0CompactionFiles) addFile(f *FileMetadata) {
1182 1 : if l.FilesIncluded[f.L0Index] {
1183 1 : return
1184 1 : }
1185 1 : l.FilesIncluded.markBit(f.L0Index)
1186 1 : l.Files = append(l.Files, f)
1187 1 : l.filesAdded = append(l.filesAdded, f)
1188 1 : l.fileBytes += f.Size
1189 1 : if f.minIntervalIndex < l.minIntervalIndex {
1190 1 : l.minIntervalIndex = f.minIntervalIndex
1191 1 : }
1192 1 : if f.maxIntervalIndex > l.maxIntervalIndex {
1193 1 : l.maxIntervalIndex = f.maxIntervalIndex
1194 1 : }
1195 : }
1196 :
1197 : // Helper to order intervals being considered for compaction.
1198 : type intervalAndScore struct {
1199 : interval int
1200 : score int
1201 : }
1202 : type intervalSorterByDecreasingScore []intervalAndScore
1203 :
1204 1 : func (is intervalSorterByDecreasingScore) Len() int { return len(is) }
1205 1 : func (is intervalSorterByDecreasingScore) Less(i, j int) bool {
1206 1 : return is[i].score > is[j].score
1207 1 : }
1208 1 : func (is intervalSorterByDecreasingScore) Swap(i, j int) {
1209 1 : is[i], is[j] = is[j], is[i]
1210 1 : }
1211 :
1212 : // Compactions:
1213 : //
1214 : // The sub-levels and intervals can be visualized in 2 dimensions as the X axis
1215 : // containing intervals in increasing order and the Y axis containing sub-levels
1216 : // (older to younger). The intervals can be sparse wrt sub-levels. We observe
1217 : // that the system is typically under severe pressure in L0 during large numbers
1218 : // of ingestions where most files added to L0 are narrow and non-overlapping.
1219 : //
1220 : // L0.1 d---g
1221 : // L0.0 c--e g--j o--s u--x
1222 : //
1223 : // As opposed to a case with a lot of wide, overlapping L0 files:
1224 : //
1225 : // L0.3 d-----------r
1226 : // L0.2 c--------o
1227 : // L0.1 b-----------q
1228 : // L0.0 a----------------x
1229 : //
1230 : // In that case we expect the rectangle represented in the good visualization
1231 : // above (i.e. the first one) to be wide and short, and not too sparse (most
1232 : // intervals will have fileCount close to the sub-level count), which would make
1233 : // it amenable to concurrent L0 -> Lbase compactions.
1234 : //
1235 : // L0 -> Lbase: The high-level goal of a L0 -> Lbase compaction is to reduce
1236 : // stack depth, by compacting files in the intervals with the highest (fileCount
1237 : // - compactingCount). Additionally, we would like compactions to not involve a
1238 : // huge number of files, so that they finish quickly, and to allow for
1239 : // concurrent L0 -> Lbase compactions when needed. In order to achieve these
1240 : // goals we would like compactions to visualize as capturing thin and tall
1241 : // rectangles. The approach below is to consider intervals in some order and
1242 : // then try to construct a compaction using the interval. The first interval we
1243 : // can construct a compaction for is the compaction that is started. There can
1244 : // be multiple heuristics in choosing the ordering of the intervals -- the code
1245 : // uses one heuristic that worked well for a large ingestion stemming from a
1246 : // cockroachdb import, but additional experimentation is necessary to pick a
1247 : // general heuristic. Additionally, the compaction that gets picked may be not
1248 : // as desirable as one that could be constructed later in terms of reducing
1249 : // stack depth (since adding more files to the compaction can get blocked by
1250 : // needing to encompass files that are already being compacted). So an
1251 : // alternative would be to try to construct more than one compaction and pick
1252 : // the best one.
1253 : //
1254 : // Here's a visualization of an ideal L0->LBase compaction selection:
1255 : //
1256 : // L0.3 a--d g-j
1257 : // L0.2 f--j r-t
1258 : // L0.1 b-d e---j
1259 : // L0.0 a--d f--j l--o p-----x
1260 : //
1261 : // Lbase a--------i m---------w
1262 : //
1263 : // The [g,j] interval has the highest stack depth, so it would have the highest
1264 : // priority for selecting a base compaction candidate. Assuming none of the
1265 : // files are already compacting, this is the compaction that will be chosen:
1266 : //
1267 : // _______
1268 : // L0.3 a--d | g-j|
1269 : // L0.2 | f--j| r-t
1270 : // L0.1 b-d |e---j|
1271 : // L0.0 a--d | f--j| l--o p-----x
1272 : //
1273 : // Lbase a--------i m---------w
1274 : //
1275 : // Note that running this compaction will mark the a--i file in Lbase as
1276 : // compacting, and when ExtendL0ForBaseCompactionTo is called with the bounds of
1277 : // that base file, it'll expand the compaction to also include all L0 files in
1278 : // the a-d interval. The resultant compaction would then be:
1279 : //
1280 : // _____________
1281 : // L0.3 |a--d g-j|
1282 : // L0.2 | f--j| r-t
1283 : // L0.1 | b-d e---j|
1284 : // L0.0 |a--d f--j| l--o p-----x
1285 : //
1286 : // Lbase a--------i m---------w
1287 : //
1288 : // The next best interval for base compaction would therefore be the one
1289 : // including r--t in L0.2 and p--x in L0.0, and both this compaction and the one
1290 : // picked earlier can run in parallel. This is assuming minCompactionDepth >= 2,
1291 : // otherwise the second compaction has too little depth to pick.
1292 : //
1293 : // _____________
1294 : // L0.3 |a--d g-j| _________
1295 : // L0.2 | f--j| | r-t |
1296 : // L0.1 | b-d e---j| | |
1297 : // L0.0 |a--d f--j| l--o |p-----x|
1298 : //
1299 : // Lbase a--------i m---------w
1300 : //
1301 : // Note that when ExtendL0ForBaseCompactionTo is called, the compaction expands
1302 : // to the following, given that the [l,o] file can be added without including
1303 : // additional files in Lbase:
1304 : //
1305 : // _____________
1306 : // L0.3 |a--d g-j| _________
1307 : // L0.2 | f--j| | r-t |
1308 : // L0.1 | b-d e---j|______| |
1309 : // L0.0 |a--d f--j||l--o p-----x|
1310 : //
1311 : // Lbase a--------i m---------w
1312 : //
1313 : // If an additional file existed in LBase that overlapped with [l,o], it would
1314 : // be excluded from the compaction. Concretely:
1315 : //
1316 : // _____________
1317 : // L0.3 |a--d g-j| _________
1318 : // L0.2 | f--j| | r-t |
1319 : // L0.1 | b-d e---j| | |
1320 : // L0.0 |a--d f--j| l--o |p-----x|
1321 : //
1322 : // Lbase a--------ij--lm---------w
1323 : //
1324 : // Intra-L0: If the L0 score is high, but PickBaseCompaction() is unable to pick
1325 : // a compaction, PickIntraL0Compaction will be used to pick an intra-L0
1326 : // compaction. Similar to L0 -> Lbase compactions, we want to allow for multiple
1327 : // intra-L0 compactions and not generate wide output files that hinder later
1328 : // concurrency of L0 -> Lbase compactions. Also compactions that produce wide
1329 : // files don't reduce stack depth -- they represent wide rectangles in our
1330 : // visualization, which means many intervals have their depth reduced by a small
1331 : // amount. Typically, L0 files have non-overlapping sequence numbers, and
1332 : // sticking to that invariant would require us to consider intra-L0 compactions
1333 : // that proceed from youngest to oldest files, which could result in the
1334 : // aforementioned undesirable wide rectangle shape. But this non-overlapping
1335 : // sequence number is already relaxed in RocksDB -- sstables are primarily
1336 : // ordered by their largest sequence number. So we can arrange for intra-L0
1337 : // compactions to capture thin and tall rectangles starting with the top of the
1338 : // stack (youngest files). Like the L0 -> Lbase case we order the intervals
1339 : // using a heuristic and consider each in turn. The same comment about better L0
1340 : // -> Lbase heuristics and not being greedy applies here.
1341 : //
1342 : // Going back to a modified version of our example from earlier, let's say these
1343 : // are the base compactions in progress:
1344 : // _______
1345 : // L0.3 a--d | g-j| _________
1346 : // L0.2 | f--j| | r-t |
1347 : // L0.1 b-d |e---j| | |
1348 : // L0.0 a--d | f--j| l--o |p-----x|
1349 : //
1350 : // Lbase a---------i m---------w
1351 : //
1352 : // Since both LBase files are compacting, the only L0 compaction that can be
1353 : // picked is an intra-L0 compaction. For this, the b--d interval has the highest
1354 : // stack depth (3), and starting with a--d in L0.3 as the seed file, we can
1355 : // iterate downward and build this compaction, assuming all files in that
1356 : // interval are not compacting and have a highest sequence number less than
1357 : // earliestUnflushedSeqNum:
1358 : //
1359 : // _______
1360 : // L0.3 |a--d| | g-j| _________
1361 : // L0.2 | | | f--j| | r-t |
1362 : // L0.1 | b-d| |e---j| | |
1363 : // L0.0 |a--d| | f--j| l--o |p-----x|
1364 : // ------
1365 : // Lbase a---------i m---------w
1366 : //
1367 :
1368 : // PickBaseCompaction picks a base compaction based on the above specified
1369 : // heuristics, for the specified Lbase files and a minimum depth of overlapping
1370 : // files that can be selected for compaction. Returns nil if no compaction is
1371 : // possible.
1372 : func (s *L0Sublevels) PickBaseCompaction(
1373 : minCompactionDepth int, baseFiles LevelSlice,
1374 1 : ) (*L0CompactionFiles, error) {
1375 1 : // For LBase compactions, we consider intervals in a greedy manner in the
1376 1 : // following order:
1377 1 : // - Intervals that are unlikely to be blocked due
1378 1 : // to ongoing L0 -> Lbase compactions. These are the ones with
1379 1 : // !isBaseCompacting && !intervalRangeIsBaseCompacting.
1380 1 : // - Intervals that are !isBaseCompacting && intervalRangeIsBaseCompacting.
1381 1 : //
1382 1 : // The ordering heuristic exists just to avoid wasted work. Ideally,
1383 1 : // we would consider all intervals with isBaseCompacting = false and
1384 1 : // construct a compaction for it and compare the constructed compactions
1385 1 : // and pick the best one. If microbenchmarks show that we can afford
1386 1 : // this cost we can eliminate this heuristic.
1387 1 : scoredIntervals := make([]intervalAndScore, 0, len(s.orderedIntervals))
1388 1 : sublevelCount := len(s.levelFiles)
1389 1 : for i := range s.orderedIntervals {
1390 1 : interval := &s.orderedIntervals[i]
1391 1 : depth := len(interval.files) - interval.compactingFileCount
1392 1 : if interval.isBaseCompacting || minCompactionDepth > depth {
1393 1 : continue
1394 : }
1395 1 : if interval.intervalRangeIsBaseCompacting {
1396 1 : scoredIntervals = append(scoredIntervals, intervalAndScore{interval: i, score: depth})
1397 1 : } else {
1398 1 : // Prioritize this interval by incrementing the score by the number
1399 1 : // of sublevels.
1400 1 : scoredIntervals = append(scoredIntervals, intervalAndScore{interval: i, score: depth + sublevelCount})
1401 1 : }
1402 : }
1403 1 : sort.Sort(intervalSorterByDecreasingScore(scoredIntervals))
1404 1 :
1405 1 : // Optimization to avoid considering different intervals that
1406 1 : // are likely to choose the same seed file. Again this is just
1407 1 : // to reduce wasted work.
1408 1 : consideredIntervals := newBitSet(len(s.orderedIntervals))
1409 1 : for _, scoredInterval := range scoredIntervals {
1410 1 : interval := &s.orderedIntervals[scoredInterval.interval]
1411 1 : if consideredIntervals[interval.index] {
1412 1 : continue
1413 : }
1414 :
1415 : // Pick the seed file for the interval as the file
1416 : // in the lowest sub-level.
1417 1 : f := interval.files[0]
1418 1 : // Don't bother considering the intervals that are covered by the seed
1419 1 : // file since they are likely nearby. Note that it is possible that
1420 1 : // those intervals have seed files at lower sub-levels so could be
1421 1 : // viable for compaction.
1422 1 : if f == nil {
1423 0 : return nil, errors.New("no seed file found in sublevel intervals")
1424 0 : }
1425 1 : consideredIntervals.markBits(f.minIntervalIndex, f.maxIntervalIndex+1)
1426 1 : if f.IsCompacting() {
1427 1 : if f.IsIntraL0Compacting {
1428 0 : // If we're picking a base compaction and we came across a seed
1429 0 : // file candidate that's being intra-L0 compacted, skip the
1430 0 : // interval instead of erroring out.
1431 0 : continue
1432 : }
1433 : // We chose a compaction seed file that should not be compacting.
1434 : // Usually means the score is not accurately accounting for files
1435 : // already compacting, or internal state is inconsistent.
1436 1 : return nil, errors.Errorf("file %s chosen as seed file for compaction should not be compacting", f.FileNum)
1437 : }
1438 :
1439 1 : c := s.baseCompactionUsingSeed(f, interval.index, minCompactionDepth)
1440 1 : if c != nil {
1441 1 : // Check if the chosen compaction overlaps with any files in Lbase
1442 1 : // that have Compacting = true. If that's the case, this compaction
1443 1 : // cannot be chosen.
1444 1 : baseIter := baseFiles.Iter()
1445 1 : // An interval starting at ImmediateSuccessor(key) can never be the
1446 1 : // first interval of a compaction since no file can start at that
1447 1 : // interval.
1448 1 : m := baseIter.SeekGE(s.cmp, s.orderedIntervals[c.minIntervalIndex].startKey.key)
1449 1 :
1450 1 : var baseCompacting bool
1451 1 : for ; m != nil && !baseCompacting; m = baseIter.Next() {
1452 1 : cmp := s.cmp(m.Smallest.UserKey, s.orderedIntervals[c.maxIntervalIndex+1].startKey.key)
1453 1 : // Compaction is ending at exclusive bound of c.maxIntervalIndex+1
1454 1 : if cmp > 0 || (cmp == 0 && !s.orderedIntervals[c.maxIntervalIndex+1].startKey.isInclusiveEndBound) {
1455 1 : break
1456 : }
1457 1 : baseCompacting = baseCompacting || m.IsCompacting()
1458 : }
1459 1 : if baseCompacting {
1460 1 : continue
1461 : }
1462 1 : return c, nil
1463 : }
1464 : }
1465 1 : return nil, nil
1466 : }
1467 :
1468 : // Helper function for building an L0 -> Lbase compaction using a seed interval
1469 : // and seed file in that seed interval.
1470 : func (s *L0Sublevels) baseCompactionUsingSeed(
1471 : f *FileMetadata, intervalIndex int, minCompactionDepth int,
1472 1 : ) *L0CompactionFiles {
1473 1 : c := &L0CompactionFiles{
1474 1 : FilesIncluded: newBitSet(s.levelMetadata.Len()),
1475 1 : seedInterval: intervalIndex,
1476 1 : seedIntervalMinLevel: 0,
1477 1 : minIntervalIndex: f.minIntervalIndex,
1478 1 : maxIntervalIndex: f.maxIntervalIndex,
1479 1 : }
1480 1 : c.addFile(f)
1481 1 :
1482 1 : // The first iteration of this loop builds the compaction at the seed file's
1483 1 : // sublevel. Future iterations expand on this compaction by stacking more
1484 1 : // files from intervalIndex and repeating. This is an optional activity so
1485 1 : // when it fails we can fallback to the last successful candidate.
1486 1 : var lastCandidate *L0CompactionFiles
1487 1 : interval := &s.orderedIntervals[intervalIndex]
1488 1 :
1489 1 : for i := 0; i < len(interval.files); i++ {
1490 1 : f2 := interval.files[i]
1491 1 : sl := f2.SubLevel
1492 1 : c.seedIntervalStackDepthReduction++
1493 1 : c.seedIntervalMaxLevel = sl
1494 1 : c.addFile(f2)
1495 1 : // The seed file is in the lowest sublevel in the seed interval, but it
1496 1 : // may overlap with other files in even lower sublevels. For correctness
1497 1 : // we need to grow our interval to include those files, and capture all
1498 1 : // files in the next level that fall in this extended interval and so
1499 1 : // on. This can result in a triangular shape like the following where
1500 1 : // again the X axis is the key intervals and the Y axis is oldest to
1501 1 : // youngest. Note that it is not necessary for correctness to fill out
1502 1 : // the shape at the higher sub-levels to make it more rectangular since
1503 1 : // the invariant only requires that younger versions of a key not be
1504 1 : // moved to Lbase while leaving behind older versions.
1505 1 : // -
1506 1 : // ---
1507 1 : // -----
1508 1 : // It may be better for performance to have a more rectangular shape
1509 1 : // since the files being left behind will overlap with the same Lbase
1510 1 : // key range as that of this compaction. But there is also the danger
1511 1 : // that in trying to construct a more rectangular shape we will be
1512 1 : // forced to pull in a file that is already compacting. We expect
1513 1 : // extendCandidateToRectangle to eventually be called on this compaction
1514 1 : // if it's chosen, at which point we would iterate backward and choose
1515 1 : // those files. This logic is similar to compaction.grow for non-L0
1516 1 : // compactions.
1517 1 : done := false
1518 1 : for currLevel := sl - 1; currLevel >= 0; currLevel-- {
1519 1 : if !s.extendFiles(currLevel, math.MaxUint64, c) {
1520 1 : // Failed to extend due to ongoing compaction.
1521 1 : done = true
1522 1 : break
1523 : }
1524 : }
1525 1 : if done {
1526 1 : break
1527 : }
1528 : // Observed some compactions using > 1GB from L0 in an import
1529 : // experiment. Very long running compactions are not great as they
1530 : // reduce concurrency while they run, and take a while to produce
1531 : // results, though they're sometimes unavoidable. There is a tradeoff
1532 : // here in that adding more depth is more efficient in reducing stack
1533 : // depth, but long running compactions reduce flexibility in what can
1534 : // run concurrently in L0 and even Lbase -> Lbase+1. An increase more
1535 : // than 150% in bytes since the last candidate compaction (along with a
1536 : // total compaction size in excess of 100mb), or a total compaction size
1537 : // beyond a hard limit of 500mb, is criteria for rejecting this
1538 : // candidate. This lets us prefer slow growths as we add files, while
1539 : // still having a hard limit. Note that if this is the first compaction
1540 : // candidate to reach a stack depth reduction of minCompactionDepth or
1541 : // higher, this candidate will be chosen regardless.
1542 1 : if lastCandidate == nil {
1543 1 : lastCandidate = &L0CompactionFiles{}
1544 1 : } else if lastCandidate.seedIntervalStackDepthReduction >= minCompactionDepth &&
1545 1 : c.fileBytes > 100<<20 &&
1546 1 : (float64(c.fileBytes)/float64(lastCandidate.fileBytes) > 1.5 || c.fileBytes > 500<<20) {
1547 1 : break
1548 : }
1549 1 : *lastCandidate = *c
1550 : }
1551 1 : if lastCandidate != nil && lastCandidate.seedIntervalStackDepthReduction >= minCompactionDepth {
1552 1 : lastCandidate.FilesIncluded.clearAllBits()
1553 1 : for _, f := range lastCandidate.Files {
1554 1 : lastCandidate.FilesIncluded.markBit(f.L0Index)
1555 1 : }
1556 1 : return lastCandidate
1557 : }
1558 1 : return nil
1559 : }
1560 :
1561 : // Expands fields in the provided L0CompactionFiles instance (cFiles) to
1562 : // include overlapping files in the specified sublevel. Returns true if the
1563 : // compaction is possible (i.e. does not conflict with any base/intra-L0
1564 : // compacting files).
1565 : func (s *L0Sublevels) extendFiles(
1566 : sl int, earliestUnflushedSeqNum base.SeqNum, cFiles *L0CompactionFiles,
1567 1 : ) bool {
1568 1 : index, _ := slices.BinarySearchFunc(s.levelFiles[sl], cFiles.minIntervalIndex, func(a *FileMetadata, b int) int {
1569 1 : return stdcmp.Compare(a.maxIntervalIndex, b)
1570 1 : })
1571 1 : for ; index < len(s.levelFiles[sl]); index++ {
1572 1 : f := s.levelFiles[sl][index]
1573 1 : if f.minIntervalIndex > cFiles.maxIntervalIndex {
1574 1 : break
1575 : }
1576 1 : if f.IsCompacting() {
1577 1 : return false
1578 1 : }
1579 : // Skip over files that are newer than earliestUnflushedSeqNum. This is
1580 : // okay because this compaction can just pretend these files are not in
1581 : // L0 yet. These files must be in higher sublevels than any overlapping
1582 : // files with f.LargestSeqNum < earliestUnflushedSeqNum, and the output
1583 : // of the compaction will also go in a lower (older) sublevel than this
1584 : // file by definition.
1585 1 : if f.LargestSeqNum >= earliestUnflushedSeqNum {
1586 1 : continue
1587 : }
1588 1 : cFiles.addFile(f)
1589 : }
1590 1 : return true
1591 : }
1592 :
1593 : // PickIntraL0Compaction picks an intra-L0 compaction for files in this
1594 : // sublevel. This method is only called when a base compaction cannot be chosen.
1595 : // See comment above [PickBaseCompaction] for heuristics involved in this
1596 : // selection.
1597 : func (s *L0Sublevels) PickIntraL0Compaction(
1598 : earliestUnflushedSeqNum base.SeqNum, minCompactionDepth int,
1599 1 : ) (*L0CompactionFiles, error) {
1600 1 : scoredIntervals := make([]intervalAndScore, len(s.orderedIntervals))
1601 1 : for i := range s.orderedIntervals {
1602 1 : interval := &s.orderedIntervals[i]
1603 1 : depth := len(interval.files) - interval.compactingFileCount
1604 1 : if minCompactionDepth > depth {
1605 1 : continue
1606 : }
1607 1 : scoredIntervals[i] = intervalAndScore{interval: i, score: depth}
1608 : }
1609 1 : sort.Sort(intervalSorterByDecreasingScore(scoredIntervals))
1610 1 :
1611 1 : // Optimization to avoid considering different intervals that are likely to
1612 1 : // choose the same seed file. Again this is just to reduce wasted work.
1613 1 : consideredIntervals := newBitSet(len(s.orderedIntervals))
1614 1 : for _, scoredInterval := range scoredIntervals {
1615 1 : interval := &s.orderedIntervals[scoredInterval.interval]
1616 1 : if consideredIntervals[interval.index] {
1617 1 : continue
1618 : }
1619 :
1620 1 : var f *FileMetadata
1621 1 : // Pick the seed file for the interval as the file in the highest
1622 1 : // sub-level.
1623 1 : stackDepthReduction := scoredInterval.score
1624 1 : for i := len(interval.files) - 1; i >= 0; i-- {
1625 1 : f = interval.files[i]
1626 1 : if f.IsCompacting() {
1627 1 : break
1628 : }
1629 1 : consideredIntervals.markBits(f.minIntervalIndex, f.maxIntervalIndex+1)
1630 1 : // Can this be the seed file? Files with newer sequence numbers than
1631 1 : // earliestUnflushedSeqNum cannot be in the compaction.
1632 1 : if f.LargestSeqNum >= earliestUnflushedSeqNum {
1633 1 : stackDepthReduction--
1634 1 : if stackDepthReduction == 0 {
1635 1 : break
1636 : }
1637 1 : } else {
1638 1 : break
1639 : }
1640 : }
1641 1 : if stackDepthReduction < minCompactionDepth {
1642 1 : // Can't use this interval.
1643 1 : continue
1644 : }
1645 :
1646 1 : if f == nil {
1647 0 : return nil, errors.New("no seed file found in sublevel intervals")
1648 0 : }
1649 1 : if f.IsCompacting() {
1650 1 : // This file could be in a concurrent intra-L0 or base compaction.
1651 1 : // Try another interval.
1652 1 : continue
1653 : }
1654 :
1655 : // We have a seed file. Build a compaction off of that seed.
1656 1 : c := s.intraL0CompactionUsingSeed(
1657 1 : f, interval.index, earliestUnflushedSeqNum, minCompactionDepth)
1658 1 : if c != nil {
1659 1 : return c, nil
1660 1 : }
1661 : }
1662 1 : return nil, nil
1663 : }
1664 :
1665 : func (s *L0Sublevels) intraL0CompactionUsingSeed(
1666 : f *FileMetadata, intervalIndex int, earliestUnflushedSeqNum base.SeqNum, minCompactionDepth int,
1667 1 : ) *L0CompactionFiles {
1668 1 : // We know that all the files that overlap with intervalIndex have
1669 1 : // LargestSeqNum < earliestUnflushedSeqNum, but for other intervals
1670 1 : // we need to exclude files >= earliestUnflushedSeqNum
1671 1 :
1672 1 : c := &L0CompactionFiles{
1673 1 : FilesIncluded: newBitSet(s.levelMetadata.Len()),
1674 1 : seedInterval: intervalIndex,
1675 1 : seedIntervalMaxLevel: len(s.levelFiles) - 1,
1676 1 : minIntervalIndex: f.minIntervalIndex,
1677 1 : maxIntervalIndex: f.maxIntervalIndex,
1678 1 : isIntraL0: true,
1679 1 : earliestUnflushedSeqNum: earliestUnflushedSeqNum,
1680 1 : }
1681 1 : c.addFile(f)
1682 1 :
1683 1 : var lastCandidate *L0CompactionFiles
1684 1 : interval := &s.orderedIntervals[intervalIndex]
1685 1 : slIndex := len(interval.files) - 1
1686 1 : for {
1687 1 : if interval.files[slIndex] == f {
1688 1 : break
1689 : }
1690 1 : slIndex--
1691 : }
1692 : // The first iteration of this loop produces an intra-L0 compaction at the
1693 : // seed level. Iterations after that optionally add to the compaction by
1694 : // stacking more files from intervalIndex and repeating. This is an optional
1695 : // activity so when it fails we can fallback to the last successful
1696 : // candidate. The code stops adding when it can't add more, or when
1697 : // fileBytes grows too large.
1698 1 : for ; slIndex >= 0; slIndex-- {
1699 1 : f2 := interval.files[slIndex]
1700 1 : sl := f2.SubLevel
1701 1 : if f2.IsCompacting() {
1702 1 : break
1703 : }
1704 1 : c.seedIntervalStackDepthReduction++
1705 1 : c.seedIntervalMinLevel = sl
1706 1 : c.addFile(f2)
1707 1 : // The seed file captures all files in the higher level that fall in the
1708 1 : // range of intervals. That may extend the range of intervals so for
1709 1 : // correctness we need to capture all files in the next higher level
1710 1 : // that fall in this extended interval and so on. This can result in an
1711 1 : // inverted triangular shape like the following where again the X axis
1712 1 : // is the key intervals and the Y axis is oldest to youngest. Note that
1713 1 : // it is not necessary for correctness to fill out the shape at lower
1714 1 : // sub-levels to make it more rectangular since the invariant only
1715 1 : // requires that if we move an older seqnum for key k into a file that
1716 1 : // has a higher seqnum, we also move all younger seqnums for that key k
1717 1 : // into that file.
1718 1 : // -----
1719 1 : // ---
1720 1 : // -
1721 1 : // It may be better for performance to have a more rectangular shape
1722 1 : // since it will reduce the stack depth for more intervals. But there is
1723 1 : // also the danger that in explicitly trying to construct a more
1724 1 : // rectangular shape we will be forced to pull in a file that is already
1725 1 : // compacting. We assume that the performance concern is not a practical
1726 1 : // issue.
1727 1 : done := false
1728 1 : for currLevel := sl + 1; currLevel < len(s.levelFiles); currLevel++ {
1729 1 : if !s.extendFiles(currLevel, earliestUnflushedSeqNum, c) {
1730 0 : // Failed to extend due to ongoing compaction.
1731 0 : done = true
1732 0 : break
1733 : }
1734 : }
1735 1 : if done {
1736 0 : break
1737 : }
1738 1 : if lastCandidate == nil {
1739 1 : lastCandidate = &L0CompactionFiles{}
1740 1 : } else if lastCandidate.seedIntervalStackDepthReduction >= minCompactionDepth &&
1741 1 : c.fileBytes > 100<<20 &&
1742 1 : (float64(c.fileBytes)/float64(lastCandidate.fileBytes) > 1.5 || c.fileBytes > 500<<20) {
1743 0 : break
1744 : }
1745 1 : *lastCandidate = *c
1746 : }
1747 1 : if lastCandidate != nil && lastCandidate.seedIntervalStackDepthReduction >= minCompactionDepth {
1748 1 : lastCandidate.FilesIncluded.clearAllBits()
1749 1 : for _, f := range lastCandidate.Files {
1750 1 : lastCandidate.FilesIncluded.markBit(f.L0Index)
1751 1 : }
1752 1 : s.extendCandidateToRectangle(
1753 1 : lastCandidate.minIntervalIndex, lastCandidate.maxIntervalIndex, lastCandidate, false)
1754 1 : return lastCandidate
1755 : }
1756 0 : return nil
1757 : }
1758 :
1759 : // ExtendL0ForBaseCompactionTo extends the specified base compaction candidate
1760 : // L0CompactionFiles to optionally cover more files in L0 without "touching" any
1761 : // of the passed-in keys (i.e. the smallest/largest bounds are exclusive), as
1762 : // including any user keys for those internal keys could require choosing more
1763 : // files in LBase which is undesirable. Unbounded start/end keys are indicated
1764 : // by passing in the InvalidInternalKey.
1765 : func (s *L0Sublevels) ExtendL0ForBaseCompactionTo(
1766 : smallest, largest InternalKey, candidate *L0CompactionFiles,
1767 1 : ) bool {
1768 1 : firstIntervalIndex := 0
1769 1 : lastIntervalIndex := len(s.orderedIntervals) - 1
1770 1 : if smallest.Kind() != base.InternalKeyKindInvalid {
1771 1 : if smallest.Trailer == base.InternalKeyRangeDeleteSentinel {
1772 1 : // Starting at smallest.UserKey == interval.startKey is okay.
1773 1 : firstIntervalIndex = sort.Search(len(s.orderedIntervals), func(i int) bool {
1774 1 : return s.cmp(smallest.UserKey, s.orderedIntervals[i].startKey.key) <= 0
1775 1 : })
1776 1 : } else {
1777 1 : firstIntervalIndex = sort.Search(len(s.orderedIntervals), func(i int) bool {
1778 1 : // Need to start at >= smallest since if we widen too much we may miss
1779 1 : // an Lbase file that overlaps with an L0 file that will get picked in
1780 1 : // this widening, which would be bad. This interval will not start with
1781 1 : // an immediate successor key.
1782 1 : return s.cmp(smallest.UserKey, s.orderedIntervals[i].startKey.key) < 0
1783 1 : })
1784 : }
1785 : }
1786 1 : if largest.Kind() != base.InternalKeyKindInvalid {
1787 1 : // First interval that starts at or beyond the largest. This interval will not
1788 1 : // start with an immediate successor key.
1789 1 : lastIntervalIndex = sort.Search(len(s.orderedIntervals), func(i int) bool {
1790 1 : return s.cmp(largest.UserKey, s.orderedIntervals[i].startKey.key) <= 0
1791 1 : })
1792 : // Right now, lastIntervalIndex has a startKey that extends beyond largest.
1793 : // The previous interval, by definition, has an end key higher than largest.
1794 : // Iterate back twice to get the last interval that's completely within
1795 : // (smallest, largest). Except in the case where we went past the end of the
1796 : // list; in that case, the last interval to include is the very last
1797 : // interval in the list.
1798 1 : if lastIntervalIndex < len(s.orderedIntervals) {
1799 1 : lastIntervalIndex--
1800 1 : }
1801 1 : lastIntervalIndex--
1802 : }
1803 1 : if lastIntervalIndex < firstIntervalIndex {
1804 0 : return false
1805 0 : }
1806 1 : return s.extendCandidateToRectangle(firstIntervalIndex, lastIntervalIndex, candidate, true)
1807 : }
1808 :
1809 : // Best-effort attempt to make the compaction include more files in the
1810 : // rectangle defined by [minIntervalIndex, maxIntervalIndex] on the X axis and
1811 : // bounded on the Y axis by seedIntervalMinLevel and seedIntervalMaxLevel.
1812 : //
1813 : // This is strictly an optional extension; at any point where we can't feasibly
1814 : // add more files, the sublevel iteration can be halted early and candidate will
1815 : // still be a correct compaction candidate.
1816 : //
1817 : // Consider this scenario (original candidate is inside the rectangle), with
1818 : // isBase = true and interval bounds a-j (from the union of base file bounds and
1819 : // that of compaction candidate):
1820 : //
1821 : // _______
1822 : // L0.3 a--d | g-j|
1823 : // L0.2 | f--j| r-t
1824 : // L0.1 b-d |e---j|
1825 : // L0.0 a--d | f--j| l--o p-----x
1826 : //
1827 : // Lbase a--------i m---------w
1828 : //
1829 : // This method will iterate from the bottom up. At L0.0, it will add a--d since
1830 : // it's in the bounds, then add b-d, then a--d, and so on, to produce this:
1831 : //
1832 : // _____________
1833 : // L0.3 |a--d g-j|
1834 : // L0.2 | f--j| r-t
1835 : // L0.1 | b-d e---j|
1836 : // L0.0 |a--d f--j| l--o p-----x
1837 : //
1838 : // Lbase a-------i m---------w
1839 : //
1840 : // Let's assume that, instead of a--d in the top sublevel, we had 3 files, a-b,
1841 : // bb-c, and cc-d, of which bb-c is compacting. Let's also add another sublevel
1842 : // L0.4 with some files, all of which aren't compacting:
1843 : //
1844 : // L0.4 a------c ca--d _______
1845 : // L0.3 a-b bb-c cc-d | g-j|
1846 : // L0.2 | f--j| r-t
1847 : // L0.1 b----------d |e---j|
1848 : // L0.0 a------------d | f--j| l--o p-----x
1849 : //
1850 : // Lbase a------------------i m---------w
1851 : //
1852 : // This method then needs to choose between the left side of L0.3 bb-c (i.e.
1853 : // a-b), or the right side (i.e. cc-d and g-j) for inclusion in this compaction.
1854 : // Since the right side has more files as well as one file that has already been
1855 : // picked, it gets chosen at that sublevel, resulting in this intermediate
1856 : // compaction:
1857 : //
1858 : // L0.4 a------c ca--d
1859 : // ______________
1860 : // L0.3 a-b bb-c| cc-d g-j|
1861 : // L0.2 _________| f--j| r-t
1862 : // L0.1 | b----------d e---j|
1863 : // L0.0 |a------------d f--j| l--o p-----x
1864 : //
1865 : // Lbase a------------------i m---------w
1866 : //
1867 : // Since bb-c had to be excluded at L0.3, the interval bounds for L0.4 are
1868 : // actually ca-j, since ca is the next interval start key after the end interval
1869 : // of bb-c. This would result in only ca-d being chosen at that sublevel, even
1870 : // though a--c is also not compacting. This is the final result:
1871 : //
1872 : // ______________
1873 : // L0.4 a------c|ca--d |
1874 : // L0.3 a-b bb-c| cc-d g-j|
1875 : // L0.2 _________| f--j| r-t
1876 : // L0.1 | b----------d e---j|
1877 : // L0.0 |a------------d f--j| l--o p-----x
1878 : //
1879 : // Lbase a------------------i m---------w
1880 : //
1881 : // TODO(bilal): Add more targeted tests for this method, through
1882 : // ExtendL0ForBaseCompactionTo and intraL0CompactionUsingSeed.
1883 : func (s *L0Sublevels) extendCandidateToRectangle(
1884 : minIntervalIndex int, maxIntervalIndex int, candidate *L0CompactionFiles, isBase bool,
1885 1 : ) bool {
1886 1 : candidate.preExtensionMinInterval = candidate.minIntervalIndex
1887 1 : candidate.preExtensionMaxInterval = candidate.maxIntervalIndex
1888 1 : // Extend {min,max}IntervalIndex to include all of the candidate's current
1889 1 : // bounds.
1890 1 : if minIntervalIndex > candidate.minIntervalIndex {
1891 1 : minIntervalIndex = candidate.minIntervalIndex
1892 1 : }
1893 1 : if maxIntervalIndex < candidate.maxIntervalIndex {
1894 1 : maxIntervalIndex = candidate.maxIntervalIndex
1895 1 : }
1896 1 : var startLevel, increment, endLevel int
1897 1 : if isBase {
1898 1 : startLevel = 0
1899 1 : increment = +1
1900 1 : // seedIntervalMaxLevel is inclusive, while endLevel is exclusive.
1901 1 : endLevel = candidate.seedIntervalMaxLevel + 1
1902 1 : } else {
1903 1 : startLevel = len(s.levelFiles) - 1
1904 1 : increment = -1
1905 1 : // seedIntervalMinLevel is inclusive, while endLevel is exclusive.
1906 1 : endLevel = candidate.seedIntervalMinLevel - 1
1907 1 : }
1908 : // Stats for files.
1909 1 : addedCount := 0
1910 1 : // Iterate from the oldest sub-level for L0 -> Lbase and youngest sub-level
1911 1 : // for intra-L0. The idea here is that anything that can't be included from
1912 1 : // that level constrains what can be included from the next level. This
1913 1 : // change in constraint is directly incorporated into minIntervalIndex,
1914 1 : // maxIntervalIndex.
1915 1 : for sl := startLevel; sl != endLevel; sl += increment {
1916 1 : files := s.levelFiles[sl]
1917 1 : // Find the first file that overlaps with minIntervalIndex.
1918 1 : index := sort.Search(len(files), func(i int) bool {
1919 1 : return minIntervalIndex <= files[i].maxIntervalIndex
1920 1 : })
1921 : // Track the files that are fully within the current constraint of
1922 : // [minIntervalIndex, maxIntervalIndex].
1923 1 : firstIndex := -1
1924 1 : lastIndex := -1
1925 1 : for ; index < len(files); index++ {
1926 1 : f := files[index]
1927 1 : if f.minIntervalIndex > maxIntervalIndex {
1928 1 : break
1929 : }
1930 1 : include := true
1931 1 : // Extends out on the left so can't be included. This narrows what
1932 1 : // we can included in the next level.
1933 1 : if f.minIntervalIndex < minIntervalIndex {
1934 1 : include = false
1935 1 : minIntervalIndex = f.maxIntervalIndex + 1
1936 1 : }
1937 : // Extends out on the right so can't be included.
1938 1 : if f.maxIntervalIndex > maxIntervalIndex {
1939 1 : include = false
1940 1 : maxIntervalIndex = f.minIntervalIndex - 1
1941 1 : }
1942 1 : if !include {
1943 1 : continue
1944 : }
1945 1 : if firstIndex == -1 {
1946 1 : firstIndex = index
1947 1 : }
1948 1 : lastIndex = index
1949 : }
1950 1 : if minIntervalIndex > maxIntervalIndex {
1951 0 : // We excluded files that prevent continuation.
1952 0 : break
1953 : }
1954 1 : if firstIndex < 0 {
1955 1 : // No files to add in this sub-level.
1956 1 : continue
1957 : }
1958 : // We have the files in [firstIndex, lastIndex] as potential for
1959 : // inclusion. Some of these may already have been picked. Some of them
1960 : // may be already compacting. The latter is tricky since we have to
1961 : // decide whether to contract minIntervalIndex or maxIntervalIndex when
1962 : // we encounter an already compacting file. We pick the longest sequence
1963 : // between firstIndex and lastIndex of non-compacting files -- this is
1964 : // represented by [candidateNonCompactingFirst,
1965 : // candidateNonCompactingLast].
1966 1 : nonCompactingFirst := -1
1967 1 : currentRunHasAlreadyPickedFiles := false
1968 1 : candidateNonCompactingFirst := -1
1969 1 : candidateNonCompactingLast := -1
1970 1 : candidateHasAlreadyPickedFiles := false
1971 1 : for index = firstIndex; index <= lastIndex; index++ {
1972 1 : f := files[index]
1973 1 : if f.IsCompacting() {
1974 1 : if nonCompactingFirst != -1 {
1975 1 : last := index - 1
1976 1 : // Prioritize runs of consecutive non-compacting files that
1977 1 : // have files that have already been picked. That is to say,
1978 1 : // if candidateHasAlreadyPickedFiles == true, we stick with
1979 1 : // it, and if currentRunHasAlreadyPickedfiles == true, we
1980 1 : // pick that run even if it contains fewer files than the
1981 1 : // previous candidate.
1982 1 : if !candidateHasAlreadyPickedFiles && (candidateNonCompactingFirst == -1 ||
1983 1 : currentRunHasAlreadyPickedFiles ||
1984 1 : (last-nonCompactingFirst) > (candidateNonCompactingLast-candidateNonCompactingFirst)) {
1985 1 : candidateNonCompactingFirst = nonCompactingFirst
1986 1 : candidateNonCompactingLast = last
1987 1 : candidateHasAlreadyPickedFiles = currentRunHasAlreadyPickedFiles
1988 1 : }
1989 : }
1990 1 : nonCompactingFirst = -1
1991 1 : currentRunHasAlreadyPickedFiles = false
1992 1 : continue
1993 : }
1994 1 : if nonCompactingFirst == -1 {
1995 1 : nonCompactingFirst = index
1996 1 : }
1997 1 : if candidate.FilesIncluded[f.L0Index] {
1998 1 : currentRunHasAlreadyPickedFiles = true
1999 1 : }
2000 : }
2001 : // Logic duplicated from inside the for loop above.
2002 1 : if nonCompactingFirst != -1 {
2003 1 : last := index - 1
2004 1 : if !candidateHasAlreadyPickedFiles && (candidateNonCompactingFirst == -1 ||
2005 1 : currentRunHasAlreadyPickedFiles ||
2006 1 : (last-nonCompactingFirst) > (candidateNonCompactingLast-candidateNonCompactingFirst)) {
2007 1 : candidateNonCompactingFirst = nonCompactingFirst
2008 1 : candidateNonCompactingLast = last
2009 1 : }
2010 : }
2011 1 : if candidateNonCompactingFirst == -1 {
2012 0 : // All files are compacting. There will be gaps that we could
2013 0 : // exploit to continue, but don't bother.
2014 0 : break
2015 : }
2016 : // May need to shrink [minIntervalIndex, maxIntervalIndex] for the next level.
2017 1 : if candidateNonCompactingFirst > firstIndex {
2018 1 : minIntervalIndex = files[candidateNonCompactingFirst-1].maxIntervalIndex + 1
2019 1 : }
2020 1 : if candidateNonCompactingLast < lastIndex {
2021 1 : maxIntervalIndex = files[candidateNonCompactingLast+1].minIntervalIndex - 1
2022 1 : }
2023 1 : for index := candidateNonCompactingFirst; index <= candidateNonCompactingLast; index++ {
2024 1 : f := files[index]
2025 1 : if f.IsCompacting() {
2026 0 : // TODO(bilal): Do a logger.Fatalf instead of a panic, for
2027 0 : // cleaner unwinding and error messages.
2028 0 : panic(fmt.Sprintf("expected %s to not be compacting", f.FileNum))
2029 : }
2030 1 : if candidate.isIntraL0 && f.LargestSeqNum >= candidate.earliestUnflushedSeqNum {
2031 1 : continue
2032 : }
2033 1 : if !candidate.FilesIncluded[f.L0Index] {
2034 1 : addedCount++
2035 1 : candidate.addFile(f)
2036 1 : }
2037 : }
2038 : }
2039 1 : return addedCount > 0
2040 : }
|