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 pebble
6 :
7 : import (
8 : "fmt"
9 : "math"
10 :
11 : "github.com/cockroachdb/errors"
12 : "github.com/cockroachdb/pebble/internal/base"
13 : "github.com/cockroachdb/pebble/internal/invariants"
14 : "github.com/cockroachdb/pebble/internal/keyspan"
15 : "github.com/cockroachdb/pebble/internal/keyspan/keyspanimpl"
16 : "github.com/cockroachdb/pebble/internal/manifest"
17 : "github.com/cockroachdb/pebble/sstable"
18 : )
19 :
20 : // In-memory statistics about tables help inform compaction picking, but may
21 : // be expensive to calculate or load from disk. Every time a database is
22 : // opened, these statistics must be reloaded or recalculated. To minimize
23 : // impact on user activity and compactions, we load these statistics
24 : // asynchronously in the background and store loaded statistics in each
25 : // table's *FileMetadata.
26 : //
27 : // This file implements the asynchronous loading of statistics by maintaining
28 : // a list of files that require statistics, alongside their LSM levels.
29 : // Whenever new files are added to the LSM, the files are appended to
30 : // d.mu.tableStats.pending. If a stats collection job is not currently
31 : // running, one is started in a separate goroutine.
32 : //
33 : // The stats collection job grabs and clears the pending list, computes table
34 : // statistics relative to the current readState and updates the tables' file
35 : // metadata. New pending files may accumulate during a stats collection job,
36 : // so a completing job triggers a new job if necessary. Only one job runs at a
37 : // time.
38 : //
39 : // When an existing database is opened, all files lack in-memory statistics.
40 : // These files' stats are loaded incrementally whenever the pending list is
41 : // empty by scanning a current readState for files missing statistics. Once a
42 : // job completes a scan without finding any remaining files without
43 : // statistics, it flips a `loadedInitial` flag. From then on, the stats
44 : // collection job only needs to load statistics for new files appended to the
45 : // pending list.
46 :
47 1 : func (d *DB) maybeCollectTableStatsLocked() {
48 1 : if d.shouldCollectTableStatsLocked() {
49 1 : go d.collectTableStats()
50 1 : }
51 : }
52 :
53 : // updateTableStatsLocked is called when new files are introduced, after the
54 : // read state has been updated. It may trigger a new stat collection.
55 : // DB.mu must be locked when calling.
56 1 : func (d *DB) updateTableStatsLocked(newFiles []manifest.NewFileEntry) {
57 1 : var needStats bool
58 1 : for _, nf := range newFiles {
59 1 : if !nf.Meta.StatsValid() {
60 1 : needStats = true
61 1 : break
62 : }
63 : }
64 1 : if !needStats {
65 1 : return
66 1 : }
67 :
68 1 : d.mu.tableStats.pending = append(d.mu.tableStats.pending, newFiles...)
69 1 : d.maybeCollectTableStatsLocked()
70 : }
71 :
72 1 : func (d *DB) shouldCollectTableStatsLocked() bool {
73 1 : return !d.mu.tableStats.loading &&
74 1 : d.closed.Load() == nil &&
75 1 : !d.opts.DisableTableStats &&
76 1 : (len(d.mu.tableStats.pending) > 0 || !d.mu.tableStats.loadedInitial)
77 1 : }
78 :
79 : // collectTableStats runs a table stats collection job, returning true if the
80 : // invocation did the collection work, false otherwise (e.g. if another job was
81 : // already running).
82 1 : func (d *DB) collectTableStats() bool {
83 1 : const maxTableStatsPerScan = 50
84 1 :
85 1 : d.mu.Lock()
86 1 : if !d.shouldCollectTableStatsLocked() {
87 1 : d.mu.Unlock()
88 1 : return false
89 1 : }
90 :
91 1 : pending := d.mu.tableStats.pending
92 1 : d.mu.tableStats.pending = nil
93 1 : d.mu.tableStats.loading = true
94 1 : jobID := d.newJobIDLocked()
95 1 : loadedInitial := d.mu.tableStats.loadedInitial
96 1 : // Drop DB.mu before performing IO.
97 1 : d.mu.Unlock()
98 1 :
99 1 : // Every run of collectTableStats either collects stats from the pending
100 1 : // list (if non-empty) or from scanning the version (loadedInitial is
101 1 : // false). This job only runs if at least one of those conditions holds.
102 1 :
103 1 : // Grab a read state to scan for tables.
104 1 : rs := d.loadReadState()
105 1 : var collected []collectedStats
106 1 : var hints []deleteCompactionHint
107 1 : if len(pending) > 0 {
108 1 : collected, hints = d.loadNewFileStats(rs, pending)
109 1 : } else {
110 1 : var moreRemain bool
111 1 : var buf [maxTableStatsPerScan]collectedStats
112 1 : collected, hints, moreRemain = d.scanReadStateTableStats(rs, buf[:0])
113 1 : loadedInitial = !moreRemain
114 1 : }
115 1 : rs.unref()
116 1 :
117 1 : // Update the FileMetadata with the loaded stats while holding d.mu.
118 1 : d.mu.Lock()
119 1 : defer d.mu.Unlock()
120 1 : d.mu.tableStats.loading = false
121 1 : if loadedInitial && !d.mu.tableStats.loadedInitial {
122 1 : d.mu.tableStats.loadedInitial = loadedInitial
123 1 : d.opts.EventListener.TableStatsLoaded(TableStatsInfo{
124 1 : JobID: int(jobID),
125 1 : })
126 1 : }
127 :
128 1 : maybeCompact := false
129 1 : for _, c := range collected {
130 1 : c.fileMetadata.Stats = c.TableStats
131 1 : maybeCompact = maybeCompact || fileCompensation(c.fileMetadata) > 0
132 1 : c.fileMetadata.StatsMarkValid()
133 1 : }
134 1 : d.mu.tableStats.cond.Broadcast()
135 1 : d.maybeCollectTableStatsLocked()
136 1 : if len(hints) > 0 && !d.opts.private.disableDeleteOnlyCompactions {
137 1 : // Verify that all of the hint tombstones' files still exist in the
138 1 : // current version. Otherwise, the tombstone itself may have been
139 1 : // compacted into L6 and more recent keys may have had their sequence
140 1 : // numbers zeroed.
141 1 : //
142 1 : // Note that it's possible that the tombstone file is being compacted
143 1 : // presently. In that case, the file will be present in v. When the
144 1 : // compaction finishes compacting the tombstone file, it will detect
145 1 : // and clear the hint.
146 1 : //
147 1 : // See DB.maybeUpdateDeleteCompactionHints.
148 1 : v := d.mu.versions.currentVersion()
149 1 : keepHints := hints[:0]
150 1 : for _, h := range hints {
151 1 : if v.Contains(h.tombstoneLevel, h.tombstoneFile) {
152 1 : keepHints = append(keepHints, h)
153 1 : }
154 : }
155 1 : d.mu.compact.deletionHints = append(d.mu.compact.deletionHints, keepHints...)
156 : }
157 1 : if maybeCompact {
158 1 : d.maybeScheduleCompaction()
159 1 : }
160 1 : return true
161 : }
162 :
163 : type collectedStats struct {
164 : *fileMetadata
165 : manifest.TableStats
166 : }
167 :
168 : func (d *DB) loadNewFileStats(
169 : rs *readState, pending []manifest.NewFileEntry,
170 1 : ) ([]collectedStats, []deleteCompactionHint) {
171 1 : var hints []deleteCompactionHint
172 1 : collected := make([]collectedStats, 0, len(pending))
173 1 : for _, nf := range pending {
174 1 : // A file's stats might have been populated by an earlier call to
175 1 : // loadNewFileStats if the file was moved.
176 1 : // NB: We're not holding d.mu which protects f.Stats, but only
177 1 : // collectTableStats updates f.Stats for active files, and we
178 1 : // ensure only one goroutine runs it at a time through
179 1 : // d.mu.tableStats.loading.
180 1 : if nf.Meta.StatsValid() {
181 1 : continue
182 : }
183 :
184 : // The file isn't guaranteed to still be live in the readState's
185 : // version. It may have been deleted or moved. Skip it if it's not in
186 : // the expected level.
187 1 : if !rs.current.Contains(nf.Level, nf.Meta) {
188 1 : continue
189 : }
190 :
191 1 : stats, newHints, err := d.loadTableStats(
192 1 : rs.current, nf.Level,
193 1 : nf.Meta,
194 1 : )
195 1 : if err != nil {
196 0 : d.opts.EventListener.BackgroundError(err)
197 0 : continue
198 : }
199 : // NB: We don't update the FileMetadata yet, because we aren't
200 : // holding DB.mu. We'll copy it to the FileMetadata after we're
201 : // finished with IO.
202 1 : collected = append(collected, collectedStats{
203 1 : fileMetadata: nf.Meta,
204 1 : TableStats: stats,
205 1 : })
206 1 : hints = append(hints, newHints...)
207 : }
208 1 : return collected, hints
209 : }
210 :
211 : // scanReadStateTableStats is run by an active stat collection job when there
212 : // are no pending new files, but there might be files that existed at Open for
213 : // which we haven't loaded table stats.
214 : func (d *DB) scanReadStateTableStats(
215 : rs *readState, fill []collectedStats,
216 1 : ) ([]collectedStats, []deleteCompactionHint, bool) {
217 1 : moreRemain := false
218 1 : var hints []deleteCompactionHint
219 1 : sizesChecked := make(map[base.DiskFileNum]struct{})
220 1 : for l, levelMetadata := range rs.current.Levels {
221 1 : iter := levelMetadata.Iter()
222 1 : for f := iter.First(); f != nil; f = iter.Next() {
223 1 : // NB: We're not holding d.mu which protects f.Stats, but only the
224 1 : // active stats collection job updates f.Stats for active files,
225 1 : // and we ensure only one goroutine runs it at a time through
226 1 : // d.mu.tableStats.loading. This makes it safe to read validity
227 1 : // through f.Stats.ValidLocked despite not holding d.mu.
228 1 : if f.StatsValid() {
229 1 : continue
230 : }
231 :
232 : // Limit how much work we do per read state. The older the read
233 : // state is, the higher the likelihood files are no longer being
234 : // used in the current version. If we've exhausted our allowance,
235 : // return true for the last return value to signal there's more
236 : // work to do.
237 1 : if len(fill) == cap(fill) {
238 1 : moreRemain = true
239 1 : return fill, hints, moreRemain
240 1 : }
241 :
242 : // If the file is remote and not SharedForeign, we should check if its size
243 : // matches. This is because checkConsistency skips over remote files.
244 : //
245 : // SharedForeign and External files are skipped as their sizes are allowed
246 : // to have a mismatch; the size stored in the FileBacking is just the part
247 : // of the file that is referenced by this Pebble instance, not the size of
248 : // the whole object.
249 1 : objMeta, err := d.objProvider.Lookup(fileTypeTable, f.FileBacking.DiskFileNum)
250 1 : if err != nil {
251 0 : // Set `moreRemain` so we'll try again.
252 0 : moreRemain = true
253 0 : d.opts.EventListener.BackgroundError(err)
254 0 : continue
255 : }
256 :
257 1 : shouldCheckSize := objMeta.IsRemote() &&
258 1 : !d.objProvider.IsSharedForeign(objMeta) &&
259 1 : !objMeta.IsExternal()
260 1 : if _, ok := sizesChecked[f.FileBacking.DiskFileNum]; !ok && shouldCheckSize {
261 1 : size, err := d.objProvider.Size(objMeta)
262 1 : fileSize := f.FileBacking.Size
263 1 : if err != nil {
264 0 : moreRemain = true
265 0 : d.opts.EventListener.BackgroundError(err)
266 0 : continue
267 : }
268 1 : if size != int64(fileSize) {
269 0 : err := errors.Errorf(
270 0 : "during consistency check in loadTableStats: L%d: %s: object size mismatch (%s): %d (provider) != %d (MANIFEST)",
271 0 : errors.Safe(l), f.FileNum, d.objProvider.Path(objMeta),
272 0 : errors.Safe(size), errors.Safe(fileSize))
273 0 : d.opts.EventListener.BackgroundError(err)
274 0 : d.opts.Logger.Fatalf("%s", err)
275 0 : }
276 :
277 1 : sizesChecked[f.FileBacking.DiskFileNum] = struct{}{}
278 : }
279 :
280 1 : stats, newHints, err := d.loadTableStats(
281 1 : rs.current, l, f,
282 1 : )
283 1 : if err != nil {
284 0 : // Set `moreRemain` so we'll try again.
285 0 : moreRemain = true
286 0 : d.opts.EventListener.BackgroundError(err)
287 0 : continue
288 : }
289 1 : fill = append(fill, collectedStats{
290 1 : fileMetadata: f,
291 1 : TableStats: stats,
292 1 : })
293 1 : hints = append(hints, newHints...)
294 : }
295 : }
296 1 : return fill, hints, moreRemain
297 : }
298 :
299 : func (d *DB) loadTableStats(
300 : v *version, level int, meta *fileMetadata,
301 1 : ) (manifest.TableStats, []deleteCompactionHint, error) {
302 1 : var stats manifest.TableStats
303 1 : var compactionHints []deleteCompactionHint
304 1 : err := d.tableCache.withCommonReader(
305 1 : meta, func(r sstable.CommonReader) (err error) {
306 1 : props := r.CommonProperties()
307 1 : stats.NumEntries = props.NumEntries
308 1 : stats.NumDeletions = props.NumDeletions
309 1 : if props.NumPointDeletions() > 0 {
310 1 : if err = d.loadTablePointKeyStats(props, v, level, meta, &stats); err != nil {
311 0 : return
312 0 : }
313 : }
314 1 : if props.NumRangeDeletions > 0 || props.NumRangeKeyDels > 0 {
315 1 : if compactionHints, err = d.loadTableRangeDelStats(
316 1 : r, v, level, meta, &stats,
317 1 : ); err != nil {
318 0 : return
319 0 : }
320 : }
321 : // TODO(travers): Once we have real-world data, consider collecting
322 : // additional stats that may provide improved heuristics for compaction
323 : // picking.
324 1 : stats.NumRangeKeySets = props.NumRangeKeySets
325 1 : stats.ValueBlocksSize = props.ValueBlocksSize
326 1 : stats.CompressionType = sstable.CompressionFromString(props.CompressionName)
327 1 : return
328 : })
329 1 : if err != nil {
330 0 : return stats, nil, err
331 0 : }
332 1 : return stats, compactionHints, nil
333 : }
334 :
335 : // loadTablePointKeyStats calculates the point key statistics for the given
336 : // table. The provided manifest.TableStats are updated.
337 : func (d *DB) loadTablePointKeyStats(
338 : props *sstable.CommonProperties,
339 : v *version,
340 : level int,
341 : meta *fileMetadata,
342 : stats *manifest.TableStats,
343 1 : ) error {
344 1 : // TODO(jackson): If the file has a wide keyspace, the average
345 1 : // value size beneath the entire file might not be representative
346 1 : // of the size of the keys beneath the point tombstones.
347 1 : // We could write the ranges of 'clusters' of point tombstones to
348 1 : // a sstable property and call averageValueSizeBeneath for each of
349 1 : // these narrower ranges to improve the estimate.
350 1 : avgValLogicalSize, compressionRatio, err := d.estimateSizesBeneath(v, level, meta, props)
351 1 : if err != nil {
352 0 : return err
353 0 : }
354 1 : stats.PointDeletionsBytesEstimate =
355 1 : pointDeletionsBytesEstimate(meta.Size, props, avgValLogicalSize, compressionRatio)
356 1 : return nil
357 : }
358 :
359 : // loadTableRangeDelStats calculates the range deletion and range key deletion
360 : // statistics for the given table.
361 : func (d *DB) loadTableRangeDelStats(
362 : r sstable.CommonReader, v *version, level int, meta *fileMetadata, stats *manifest.TableStats,
363 1 : ) ([]deleteCompactionHint, error) {
364 1 : iter, err := newCombinedDeletionKeyspanIter(d.opts.Comparer, r, meta)
365 1 : if err != nil {
366 0 : return nil, err
367 0 : }
368 1 : defer iter.Close()
369 1 : var compactionHints []deleteCompactionHint
370 1 : // We iterate over the defragmented range tombstones and range key deletions,
371 1 : // which ensures we don't double count ranges deleted at different sequence
372 1 : // numbers. Also, merging abutting tombstones reduces the number of calls to
373 1 : // estimateReclaimedSizeBeneath which is costly, and improves the accuracy of
374 1 : // our overall estimate.
375 1 : s, err := iter.First()
376 1 : for ; s != nil; s, err = iter.Next() {
377 1 : start, end := s.Start, s.End
378 1 : // We only need to consider deletion size estimates for tables that contain
379 1 : // RANGEDELs.
380 1 : var maxRangeDeleteSeqNum uint64
381 1 : for _, k := range s.Keys {
382 1 : if k.Kind() == base.InternalKeyKindRangeDelete && maxRangeDeleteSeqNum < k.SeqNum() {
383 1 : maxRangeDeleteSeqNum = k.SeqNum()
384 1 : break
385 : }
386 : }
387 :
388 : // If the file is in the last level of the LSM, there is no data beneath
389 : // it. The fact that there is still a range tombstone in a bottommost file
390 : // indicates two possibilites:
391 : // 1. an open snapshot kept the tombstone around, and the data the
392 : // tombstone deletes is contained within the file itself.
393 : // 2. the file was ingested.
394 : // In the first case, we'd like to estimate disk usage within the file
395 : // itself since compacting the file will drop that covered data. In the
396 : // second case, we expect that compacting the file will NOT drop any
397 : // data and rewriting the file is a waste of write bandwidth. We can
398 : // distinguish these cases by looking at the file metadata's sequence
399 : // numbers. A file's range deletions can only delete data within the
400 : // file at lower sequence numbers. All keys in an ingested sstable adopt
401 : // the same sequence number, preventing tombstones from deleting keys
402 : // within the same file. We check here if the largest RANGEDEL sequence
403 : // number is greater than the file's smallest sequence number. If it is,
404 : // the RANGEDEL could conceivably (although inconclusively) delete data
405 : // within the same file.
406 : //
407 : // Note that this heuristic is imperfect. If a table containing a range
408 : // deletion is ingested into L5 and subsequently compacted into L6 but
409 : // an open snapshot prevents elision of covered keys in L6, the
410 : // resulting RangeDeletionsBytesEstimate will incorrectly include all
411 : // covered keys.
412 : //
413 : // TODO(jackson): We could prevent the above error in the heuristic by
414 : // computing the file's RangeDeletionsBytesEstimate during the
415 : // compaction itself. It's unclear how common this is.
416 : //
417 : // NOTE: If the span `s` wholly contains a table containing range keys,
418 : // the returned size estimate will be slightly inflated by the range key
419 : // block. However, in practice, range keys are expected to be rare, and
420 : // the size of the range key block relative to the overall size of the
421 : // table is expected to be small.
422 1 : if level == numLevels-1 && meta.SmallestSeqNum < maxRangeDeleteSeqNum {
423 1 : size, err := r.EstimateDiskUsage(start, end)
424 1 : if err != nil {
425 0 : return nil, err
426 0 : }
427 1 : stats.RangeDeletionsBytesEstimate += size
428 1 :
429 1 : // As the file is in the bottommost level, there is no need to collect a
430 1 : // deletion hint.
431 1 : continue
432 : }
433 :
434 : // While the size estimates for point keys should only be updated if this
435 : // span contains a range del, the sequence numbers are required for the
436 : // hint. Unconditionally descend, but conditionally update the estimates.
437 1 : hintType := compactionHintFromKeys(s.Keys)
438 1 : estimate, hintSeqNum, err := d.estimateReclaimedSizeBeneath(v, level, start, end, hintType)
439 1 : if err != nil {
440 0 : return nil, err
441 0 : }
442 1 : stats.RangeDeletionsBytesEstimate += estimate
443 1 :
444 1 : // If any files were completely contained with the range,
445 1 : // hintSeqNum is the smallest sequence number contained in any
446 1 : // such file.
447 1 : if hintSeqNum == math.MaxUint64 {
448 1 : continue
449 : }
450 1 : hint := deleteCompactionHint{
451 1 : hintType: hintType,
452 1 : start: make([]byte, len(start)),
453 1 : end: make([]byte, len(end)),
454 1 : tombstoneFile: meta,
455 1 : tombstoneLevel: level,
456 1 : tombstoneLargestSeqNum: s.LargestSeqNum(),
457 1 : tombstoneSmallestSeqNum: s.SmallestSeqNum(),
458 1 : fileSmallestSeqNum: hintSeqNum,
459 1 : }
460 1 : copy(hint.start, start)
461 1 : copy(hint.end, end)
462 1 : compactionHints = append(compactionHints, hint)
463 : }
464 1 : if err != nil {
465 0 : return nil, err
466 0 : }
467 1 : return compactionHints, nil
468 : }
469 :
470 : func (d *DB) estimateSizesBeneath(
471 : v *version, level int, meta *fileMetadata, fileProps *sstable.CommonProperties,
472 1 : ) (avgValueLogicalSize, compressionRatio float64, err error) {
473 1 : // Find all files in lower levels that overlap with meta,
474 1 : // summing their value sizes and entry counts.
475 1 : file := meta
476 1 : var fileSum, keySum, valSum, entryCount uint64
477 1 : // Include the file itself. This is important because in some instances, the
478 1 : // computed compression ratio is applied to the tombstones contained within
479 1 : // `meta` itself. If there are no files beneath `meta` in the LSM, we would
480 1 : // calculate a compression ratio of 0 which is not accurate for the file's
481 1 : // own tombstones.
482 1 : fileSum += file.Size
483 1 : entryCount += fileProps.NumEntries
484 1 : keySum += fileProps.RawKeySize
485 1 : valSum += fileProps.RawValueSize
486 1 :
487 1 : addPhysicalTableStats := func(r *sstable.Reader) (err error) {
488 1 : fileSum += file.Size
489 1 : entryCount += r.Properties.NumEntries
490 1 : keySum += r.Properties.RawKeySize
491 1 : valSum += r.Properties.RawValueSize
492 1 : return nil
493 1 : }
494 1 : addVirtualTableStats := func(v sstable.VirtualReader) (err error) {
495 1 : fileSum += file.Size
496 1 : entryCount += file.Stats.NumEntries
497 1 : keySum += v.Properties.RawKeySize
498 1 : valSum += v.Properties.RawValueSize
499 1 : return nil
500 1 : }
501 :
502 1 : for l := level + 1; l < numLevels; l++ {
503 1 : overlaps := v.Overlaps(l, meta.UserKeyBounds())
504 1 : iter := overlaps.Iter()
505 1 : for file = iter.First(); file != nil; file = iter.Next() {
506 1 : var err error
507 1 : if file.Virtual {
508 1 : err = d.tableCache.withVirtualReader(file.VirtualMeta(), addVirtualTableStats)
509 1 : } else {
510 1 : err = d.tableCache.withReader(file.PhysicalMeta(), addPhysicalTableStats)
511 1 : }
512 1 : if err != nil {
513 0 : return 0, 0, err
514 0 : }
515 : }
516 : }
517 1 : if entryCount == 0 {
518 0 : return 0, 0, nil
519 0 : }
520 : // RawKeySize and RawValueSize are uncompressed totals. We'll need to scale
521 : // the value sum according to the data size to account for compression,
522 : // index blocks and metadata overhead. Eg:
523 : //
524 : // Compression rate × Average uncompressed value size
525 : //
526 : // ↓
527 : //
528 : // FileSize RawValueSize
529 : // ----------------------- × ------------
530 : // RawKeySize+RawValueSize NumEntries
531 : //
532 : // We return the average logical value size plus the compression ratio,
533 : // leaving the scaling to the caller. This allows the caller to perform
534 : // additional compression ratio scaling if necessary.
535 1 : uncompressedSum := float64(keySum + valSum)
536 1 : compressionRatio = float64(fileSum) / uncompressedSum
537 1 : avgValueLogicalSize = (float64(valSum) / float64(entryCount))
538 1 : return avgValueLogicalSize, compressionRatio, nil
539 : }
540 :
541 : func (d *DB) estimateReclaimedSizeBeneath(
542 : v *version, level int, start, end []byte, hintType deleteCompactionHintType,
543 1 : ) (estimate uint64, hintSeqNum uint64, err error) {
544 1 : // Find all files in lower levels that overlap with the deleted range
545 1 : // [start, end).
546 1 : //
547 1 : // An overlapping file might be completely contained by the range
548 1 : // tombstone, in which case we can count the entire file size in
549 1 : // our estimate without doing any additional I/O.
550 1 : //
551 1 : // Otherwise, estimating the range for the file requires
552 1 : // additional I/O to read the file's index blocks.
553 1 : hintSeqNum = math.MaxUint64
554 1 : for l := level + 1; l < numLevels; l++ {
555 1 : overlaps := v.Overlaps(l, base.UserKeyBoundsEndExclusive(start, end))
556 1 : iter := overlaps.Iter()
557 1 : for file := iter.First(); file != nil; file = iter.Next() {
558 1 : startCmp := d.cmp(start, file.Smallest.UserKey)
559 1 : endCmp := d.cmp(file.Largest.UserKey, end)
560 1 : if startCmp <= 0 && (endCmp < 0 || endCmp == 0 && file.Largest.IsExclusiveSentinel()) {
561 1 : // The range fully contains the file, so skip looking it up in table
562 1 : // cache/looking at its indexes and add the full file size. Whether the
563 1 : // disk estimate and hint seqnums are updated depends on a) the type of
564 1 : // hint that requested the estimate and b) the keys contained in this
565 1 : // current file.
566 1 : var updateEstimates, updateHints bool
567 1 : switch hintType {
568 1 : case deleteCompactionHintTypePointKeyOnly:
569 1 : // The range deletion byte estimates should only be updated if this
570 1 : // table contains point keys. This ends up being an overestimate in
571 1 : // the case that table also has range keys, but such keys are expected
572 1 : // to contribute a negligible amount of the table's overall size,
573 1 : // relative to point keys.
574 1 : if file.HasPointKeys {
575 1 : updateEstimates = true
576 1 : }
577 : // As the initiating span contained only range dels, hints can only be
578 : // updated if this table does _not_ contain range keys.
579 1 : if !file.HasRangeKeys {
580 1 : updateHints = true
581 1 : }
582 1 : case deleteCompactionHintTypeRangeKeyOnly:
583 1 : // The initiating span contained only range key dels. The estimates
584 1 : // apply only to point keys, and are therefore not updated.
585 1 : updateEstimates = false
586 1 : // As the initiating span contained only range key dels, hints can
587 1 : // only be updated if this table does _not_ contain point keys.
588 1 : if !file.HasPointKeys {
589 1 : updateHints = true
590 1 : }
591 1 : case deleteCompactionHintTypePointAndRangeKey:
592 1 : // Always update the estimates and hints, as this hint type can drop a
593 1 : // file, irrespective of the mixture of keys. Similar to above, the
594 1 : // range del bytes estimates is an overestimate.
595 1 : updateEstimates, updateHints = true, true
596 0 : default:
597 0 : panic(fmt.Sprintf("pebble: unknown hint type %s", hintType))
598 : }
599 1 : if updateEstimates {
600 1 : estimate += file.Size
601 1 : }
602 1 : if updateHints && hintSeqNum > file.SmallestSeqNum {
603 1 : hintSeqNum = file.SmallestSeqNum
604 1 : }
605 1 : } else if d.cmp(file.Smallest.UserKey, end) <= 0 && d.cmp(start, file.Largest.UserKey) <= 0 {
606 1 : // Partial overlap.
607 1 : if hintType == deleteCompactionHintTypeRangeKeyOnly {
608 1 : // If the hint that generated this overlap contains only range keys,
609 1 : // there is no need to calculate disk usage, as the reclaimable space
610 1 : // is expected to be minimal relative to point keys.
611 1 : continue
612 : }
613 1 : var size uint64
614 1 : var err error
615 1 : if file.Virtual {
616 1 : err = d.tableCache.withVirtualReader(
617 1 : file.VirtualMeta(), func(r sstable.VirtualReader) (err error) {
618 1 : size, err = r.EstimateDiskUsage(start, end)
619 1 : return err
620 1 : })
621 1 : } else {
622 1 : err = d.tableCache.withReader(
623 1 : file.PhysicalMeta(), func(r *sstable.Reader) (err error) {
624 1 : size, err = r.EstimateDiskUsage(start, end)
625 1 : return err
626 1 : })
627 : }
628 :
629 1 : if err != nil {
630 0 : return 0, hintSeqNum, err
631 0 : }
632 1 : estimate += size
633 : }
634 : }
635 : }
636 1 : return estimate, hintSeqNum, nil
637 : }
638 :
639 1 : func maybeSetStatsFromProperties(meta physicalMeta, props *sstable.Properties) bool {
640 1 : // If a table contains range deletions or range key deletions, we defer the
641 1 : // stats collection. There are two main reasons for this:
642 1 : //
643 1 : // 1. Estimating the potential for reclaimed space due to a range deletion
644 1 : // tombstone requires scanning the LSM - a potentially expensive operation
645 1 : // that should be deferred.
646 1 : // 2. Range deletions and / or range key deletions present an opportunity to
647 1 : // compute "deletion hints", which also requires a scan of the LSM to
648 1 : // compute tables that would be eligible for deletion.
649 1 : //
650 1 : // These two tasks are deferred to the table stats collector goroutine.
651 1 : if props.NumRangeDeletions != 0 || props.NumRangeKeyDels != 0 {
652 1 : return false
653 1 : }
654 :
655 : // If a table is more than 10% point deletions without user-provided size
656 : // estimates, don't calculate the PointDeletionsBytesEstimate statistic
657 : // using our limited knowledge. The table stats collector can populate the
658 : // stats and calculate an average of value size of all the tables beneath
659 : // the table in the LSM, which will be more accurate.
660 1 : if unsizedDels := (props.NumDeletions - props.NumSizedDeletions); unsizedDels > props.NumEntries/10 {
661 1 : return false
662 1 : }
663 :
664 1 : var pointEstimate uint64
665 1 : if props.NumEntries > 0 {
666 1 : // Use the file's own average key and value sizes as an estimate. This
667 1 : // doesn't require any additional IO and since the number of point
668 1 : // deletions in the file is low, the error introduced by this crude
669 1 : // estimate is expected to be small.
670 1 : commonProps := &props.CommonProperties
671 1 : avgValSize, compressionRatio := estimatePhysicalSizes(meta.Size, commonProps)
672 1 : pointEstimate = pointDeletionsBytesEstimate(meta.Size, commonProps, avgValSize, compressionRatio)
673 1 : }
674 :
675 1 : meta.Stats.NumEntries = props.NumEntries
676 1 : meta.Stats.NumDeletions = props.NumDeletions
677 1 : meta.Stats.NumRangeKeySets = props.NumRangeKeySets
678 1 : meta.Stats.PointDeletionsBytesEstimate = pointEstimate
679 1 : meta.Stats.RangeDeletionsBytesEstimate = 0
680 1 : meta.Stats.ValueBlocksSize = props.ValueBlocksSize
681 1 : meta.Stats.CompressionType = sstable.CompressionFromString(props.CompressionName)
682 1 : meta.StatsMarkValid()
683 1 : return true
684 : }
685 :
686 : func pointDeletionsBytesEstimate(
687 : fileSize uint64, props *sstable.CommonProperties, avgValLogicalSize, compressionRatio float64,
688 1 : ) (estimate uint64) {
689 1 : if props.NumEntries == 0 {
690 0 : return 0
691 0 : }
692 1 : numPointDels := props.NumPointDeletions()
693 1 : if numPointDels == 0 {
694 1 : return 0
695 1 : }
696 : // Estimate the potential space to reclaim using the table's own properties.
697 : // There may or may not be keys covered by any individual point tombstone.
698 : // If not, compacting the point tombstone into L6 will at least allow us to
699 : // drop the point deletion key and will reclaim the tombstone's key bytes.
700 : // If there are covered key(s), we also get to drop key and value bytes for
701 : // each covered key.
702 : //
703 : // Some point tombstones (DELSIZEDs) carry a user-provided estimate of the
704 : // uncompressed size of entries that will be elided by fully compacting the
705 : // tombstone. For these tombstones, there's no guesswork—we use the
706 : // RawPointTombstoneValueSizeHint property which is the sum of all these
707 : // tombstones' encoded values.
708 : //
709 : // For un-sized point tombstones (DELs), we estimate assuming that each
710 : // point tombstone on average covers 1 key and using average value sizes.
711 : // This is almost certainly an overestimate, but that's probably okay
712 : // because point tombstones can slow range iterations even when they don't
713 : // cover a key.
714 : //
715 : // TODO(jackson): This logic doesn't directly incorporate fixed per-key
716 : // overhead (8-byte trailer, plus at least 1 byte encoding the length of the
717 : // key and 1 byte encoding the length of the value). This overhead is
718 : // indirectly incorporated through the compression ratios, but that results
719 : // in the overhead being smeared per key-byte and value-byte, rather than
720 : // per-entry. This per-key fixed overhead can be nontrivial, especially for
721 : // dense swaths of point tombstones. Give some thought as to whether we
722 : // should directly include fixed per-key overhead in the calculations.
723 :
724 : // Below, we calculate the tombstone contributions and the shadowed keys'
725 : // contributions separately.
726 1 : var tombstonesLogicalSize float64
727 1 : var shadowedLogicalSize float64
728 1 :
729 1 : // 1. Calculate the contribution of the tombstone keys themselves.
730 1 : if props.RawPointTombstoneKeySize > 0 {
731 1 : tombstonesLogicalSize += float64(props.RawPointTombstoneKeySize)
732 1 : } else {
733 0 : // This sstable predates the existence of the RawPointTombstoneKeySize
734 0 : // property. We can use the average key size within the file itself and
735 0 : // the count of point deletions to estimate the size.
736 0 : tombstonesLogicalSize += float64(numPointDels * props.RawKeySize / props.NumEntries)
737 0 : }
738 :
739 : // 2. Calculate the contribution of the keys shadowed by tombstones.
740 : //
741 : // 2a. First account for keys shadowed by DELSIZED tombstones. THE DELSIZED
742 : // tombstones encode the size of both the key and value of the shadowed KV
743 : // entries. These sizes are aggregated into a sstable property.
744 1 : shadowedLogicalSize += float64(props.RawPointTombstoneValueSize)
745 1 :
746 1 : // 2b. Calculate the contribution of the KV entries shadowed by ordinary DEL
747 1 : // keys.
748 1 : numUnsizedDels := numPointDels - props.NumSizedDeletions
749 1 : {
750 1 : // The shadowed keys have the same exact user keys as the tombstones
751 1 : // themselves, so we can use the `tombstonesLogicalSize` we computed
752 1 : // earlier as an estimate. There's a complication that
753 1 : // `tombstonesLogicalSize` may include DELSIZED keys we already
754 1 : // accounted for.
755 1 : shadowedLogicalSize += float64(tombstonesLogicalSize) / float64(numPointDels) * float64(numUnsizedDels)
756 1 :
757 1 : // Calculate the contribution of the deleted values. The caller has
758 1 : // already computed an average logical size (possibly computed across
759 1 : // many sstables).
760 1 : shadowedLogicalSize += float64(numUnsizedDels) * avgValLogicalSize
761 1 : }
762 :
763 : // Scale both tombstone and shadowed totals by logical:physical ratios to
764 : // account for compression, metadata overhead, etc.
765 : //
766 : // Physical FileSize
767 : // ----------- = -----------------------
768 : // Logical RawKeySize+RawValueSize
769 : //
770 1 : return uint64((tombstonesLogicalSize + shadowedLogicalSize) * compressionRatio)
771 : }
772 :
773 : func estimatePhysicalSizes(
774 : fileSize uint64, props *sstable.CommonProperties,
775 1 : ) (avgValLogicalSize, compressionRatio float64) {
776 1 : // RawKeySize and RawValueSize are uncompressed totals. Scale according to
777 1 : // the data size to account for compression, index blocks and metadata
778 1 : // overhead. Eg:
779 1 : //
780 1 : // Compression rate × Average uncompressed value size
781 1 : //
782 1 : // ↓
783 1 : //
784 1 : // FileSize RawValSize
785 1 : // ----------------------- × ----------
786 1 : // RawKeySize+RawValueSize NumEntries
787 1 : //
788 1 : uncompressedSum := props.RawKeySize + props.RawValueSize
789 1 : compressionRatio = float64(fileSize) / float64(uncompressedSum)
790 1 : avgValLogicalSize = (float64(props.RawValueSize) / float64(props.NumEntries))
791 1 : return avgValLogicalSize, compressionRatio
792 1 : }
793 :
794 : // newCombinedDeletionKeyspanIter returns a keyspan.FragmentIterator that
795 : // returns "ranged deletion" spans for a single table, providing a combined view
796 : // of both range deletion and range key deletion spans. The
797 : // tableRangedDeletionIter is intended for use in the specific case of computing
798 : // the statistics and deleteCompactionHints for a single table.
799 : //
800 : // As an example, consider the following set of spans from the range deletion
801 : // and range key blocks of a table:
802 : //
803 : // |---------| |---------| |-------| RANGEKEYDELs
804 : // |-----------|-------------| |-----| RANGEDELs
805 : // __________________________________________________________
806 : // 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
807 : //
808 : // The tableRangedDeletionIter produces the following set of output spans, where
809 : // '1' indicates a span containing only range deletions, '2' is a span
810 : // containing only range key deletions, and '3' is a span containing a mixture
811 : // of both range deletions and range key deletions.
812 : //
813 : // 1 3 1 3 2 1 3 2
814 : // |-----|---------|-----|---|-----| |---|-|-----|
815 : // __________________________________________________________
816 : // 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
817 : //
818 : // Algorithm.
819 : //
820 : // The iterator first defragments the range deletion and range key blocks
821 : // separately. During this defragmentation, the range key block is also filtered
822 : // so that keys other than range key deletes are ignored. The range delete and
823 : // range key delete keyspaces are then merged.
824 : //
825 : // Note that the only fragmentation introduced by merging is from where a range
826 : // del span overlaps with a range key del span. Within the bounds of any overlap
827 : // there is guaranteed to be no further fragmentation, as the constituent spans
828 : // have already been defragmented. To the left and right of any overlap, the
829 : // same reasoning applies. For example,
830 : //
831 : // |--------| |-------| RANGEKEYDEL
832 : // |---------------------------| RANGEDEL
833 : // |----1---|----3---|----1----|---2---| Merged, fragmented spans.
834 : // __________________________________________________________
835 : // 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
836 : //
837 : // Any fragmented abutting spans produced by the merging iter will be of
838 : // differing types (i.e. a transition from a span with homogenous key kinds to a
839 : // heterogeneous span, or a transition from a span with exclusively range dels
840 : // to a span with exclusively range key dels). Therefore, further
841 : // defragmentation is not required.
842 : //
843 : // Each span returned by the tableRangeDeletionIter will have at most four keys,
844 : // corresponding to the largest and smallest sequence numbers encountered across
845 : // the range deletes and range keys deletes that comprised the merged spans.
846 : func newCombinedDeletionKeyspanIter(
847 : comparer *base.Comparer, cr sstable.CommonReader, m *fileMetadata,
848 1 : ) (keyspan.FragmentIterator, error) {
849 1 : // The range del iter and range key iter are each wrapped in their own
850 1 : // defragmenting iter. For each iter, abutting spans can always be merged.
851 1 : var equal = keyspan.DefragmentMethodFunc(func(_ base.Equal, a, b *keyspan.Span) bool { return true })
852 : // Reduce keys by maintaining a slice of at most length two, corresponding to
853 : // the largest and smallest keys in the defragmented span. This maintains the
854 : // contract that the emitted slice is sorted by (SeqNum, Kind) descending.
855 1 : reducer := func(current, incoming []keyspan.Key) []keyspan.Key {
856 1 : if len(current) == 0 && len(incoming) == 0 {
857 0 : // While this should never occur in practice, a defensive return is used
858 0 : // here to preserve correctness.
859 0 : return current
860 0 : }
861 1 : var largest, smallest keyspan.Key
862 1 : var set bool
863 1 : for _, keys := range [2][]keyspan.Key{current, incoming} {
864 1 : if len(keys) == 0 {
865 0 : continue
866 : }
867 1 : first, last := keys[0], keys[len(keys)-1]
868 1 : if !set {
869 1 : largest, smallest = first, last
870 1 : set = true
871 1 : continue
872 : }
873 1 : if first.Trailer > largest.Trailer {
874 1 : largest = first
875 1 : }
876 1 : if last.Trailer < smallest.Trailer {
877 1 : smallest = last
878 1 : }
879 : }
880 1 : if largest.Equal(comparer.Equal, smallest) {
881 1 : current = append(current[:0], largest)
882 1 : } else {
883 1 : current = append(current[:0], largest, smallest)
884 1 : }
885 1 : return current
886 : }
887 :
888 : // The separate iters for the range dels and range keys are wrapped in a
889 : // merging iter to join the keyspaces into a single keyspace. The separate
890 : // iters are only added if the particular key kind is present.
891 1 : mIter := &keyspanimpl.MergingIter{}
892 1 : var transform = keyspan.TransformerFunc(func(cmp base.Compare, in keyspan.Span, out *keyspan.Span) error {
893 1 : if in.KeysOrder != keyspan.ByTrailerDesc {
894 0 : panic("pebble: combined deletion iter encountered keys in non-trailer descending order")
895 : }
896 1 : out.Start, out.End = in.Start, in.End
897 1 : out.Keys = append(out.Keys[:0], in.Keys...)
898 1 : out.KeysOrder = keyspan.ByTrailerDesc
899 1 : // NB: The order of by-trailer descending may have been violated,
900 1 : // because we've layered rangekey and rangedel iterators from the same
901 1 : // sstable into the same keyspanimpl.MergingIter. The MergingIter will
902 1 : // return the keys in the order that the child iterators were provided.
903 1 : // Sort the keys to ensure they're sorted by trailer descending.
904 1 : keyspan.SortKeysByTrailer(&out.Keys)
905 1 : return nil
906 : })
907 1 : mIter.Init(comparer, transform, new(keyspanimpl.MergingBuffers))
908 1 :
909 1 : iter, err := cr.NewRawRangeDelIter(m.IterTransforms())
910 1 : if err != nil {
911 0 : return nil, err
912 0 : }
913 1 : if iter != nil {
914 1 : // Assert expected bounds. In previous versions of Pebble, range
915 1 : // deletions persisted to sstables could exceed the bounds of the
916 1 : // containing files due to "split user keys." This required readers to
917 1 : // constrain the tombstones' bounds to the containing file at read time.
918 1 : // See docs/range_deletions.md for an extended discussion of the design
919 1 : // and invariants at that time.
920 1 : //
921 1 : // We've since compacted away all 'split user-keys' and in the process
922 1 : // eliminated all "untruncated range tombstones" for physical sstables.
923 1 : // We no longer need to perform truncation at read time for these
924 1 : // sstables.
925 1 : //
926 1 : // At the same time, we've also introduced the concept of "virtual
927 1 : // SSTables" where the file metadata's effective bounds can again be
928 1 : // reduced to be narrower than the contained tombstones. These virtual
929 1 : // SSTables handle truncation differently, performing it using
930 1 : // keyspan.Truncate when the sstable's range deletion iterator is
931 1 : // opened.
932 1 : //
933 1 : // Together, these mean that we should never see untruncated range
934 1 : // tombstones any more—and the merging iterator no longer accounts for
935 1 : // their existence. Since there's abundant subtlety that we're relying
936 1 : // on, we choose to be conservative and assert that these invariants
937 1 : // hold. We could (and previously did) choose to only validate these
938 1 : // bounds in invariants builds, but the most likely avenue for these
939 1 : // tombstones' existence is through a bug in a migration and old data
940 1 : // sitting around in an old store from long ago.
941 1 : //
942 1 : // The table stats collector will read all files range deletions
943 1 : // asynchronously after Open, and provides a perfect opportunity to
944 1 : // validate our invariants without harming user latency. We also
945 1 : // previously performed truncation here which similarly required key
946 1 : // comparisons, so replacing those key comparisons with assertions
947 1 : // should be roughly similar in performance.
948 1 : //
949 1 : // TODO(jackson): Only use AssertBounds in invariants builds in the
950 1 : // following release.
951 1 : iter = keyspan.AssertBounds(
952 1 : iter, m.SmallestPointKey, m.LargestPointKey.UserKey, comparer.Compare,
953 1 : )
954 1 : dIter := &keyspan.DefragmentingIter{}
955 1 : dIter.Init(comparer, iter, equal, reducer, new(keyspan.DefragmentingBuffers))
956 1 : iter = dIter
957 1 : mIter.AddLevel(iter)
958 1 : }
959 :
960 1 : iter, err = cr.NewRawRangeKeyIter(m.IterTransforms())
961 1 : if err != nil {
962 0 : return nil, err
963 0 : }
964 1 : if iter != nil {
965 1 : // Assert expected bounds in tests.
966 1 : if invariants.Enabled {
967 1 : iter = keyspan.AssertBounds(
968 1 : iter, m.SmallestRangeKey, m.LargestRangeKey.UserKey, comparer.Compare,
969 1 : )
970 1 : }
971 : // Wrap the range key iterator in a filter that elides keys other than range
972 : // key deletions.
973 1 : iter = keyspan.Filter(iter, func(in *keyspan.Span, buf []keyspan.Key) []keyspan.Key {
974 1 : keys := buf[:0]
975 1 : for _, k := range in.Keys {
976 1 : if k.Kind() != base.InternalKeyKindRangeKeyDelete {
977 1 : continue
978 : }
979 1 : keys = append(keys, k)
980 : }
981 1 : return keys
982 : }, comparer.Compare)
983 1 : dIter := &keyspan.DefragmentingIter{}
984 1 : dIter.Init(comparer, iter, equal, reducer, new(keyspan.DefragmentingBuffers))
985 1 : iter = dIter
986 1 : mIter.AddLevel(iter)
987 : }
988 :
989 1 : return mIter, nil
990 : }
991 :
992 : // rangeKeySetsAnnotator implements manifest.Annotator, annotating B-Tree nodes
993 : // with the sum of the files' counts of range key fragments. Its annotation type
994 : // is a *uint64. The count of range key sets may change once a table's stats are
995 : // loaded asynchronously, so its values are marked as cacheable only if a file's
996 : // stats have been loaded.
997 : type rangeKeySetsAnnotator struct{}
998 :
999 : var _ manifest.Annotator = rangeKeySetsAnnotator{}
1000 :
1001 1 : func (a rangeKeySetsAnnotator) Zero(dst interface{}) interface{} {
1002 1 : if dst == nil {
1003 1 : return new(uint64)
1004 1 : }
1005 0 : v := dst.(*uint64)
1006 0 : *v = 0
1007 0 : return v
1008 : }
1009 :
1010 : func (a rangeKeySetsAnnotator) Accumulate(
1011 : f *fileMetadata, dst interface{},
1012 1 : ) (v interface{}, cacheOK bool) {
1013 1 : vptr := dst.(*uint64)
1014 1 : *vptr = *vptr + f.Stats.NumRangeKeySets
1015 1 : return vptr, f.StatsValid()
1016 1 : }
1017 :
1018 0 : func (a rangeKeySetsAnnotator) Merge(src interface{}, dst interface{}) interface{} {
1019 0 : srcV := src.(*uint64)
1020 0 : dstV := dst.(*uint64)
1021 0 : *dstV = *dstV + *srcV
1022 0 : return dstV
1023 0 : }
1024 :
1025 : // countRangeKeySetFragments counts the number of RANGEKEYSET keys across all
1026 : // files of the LSM. It only counts keys in files for which table stats have
1027 : // been loaded. It uses a b-tree annotator to cache intermediate values between
1028 : // calculations when possible.
1029 1 : func countRangeKeySetFragments(v *version) (count uint64) {
1030 1 : for l := 0; l < numLevels; l++ {
1031 1 : if v.RangeKeyLevels[l].Empty() {
1032 1 : continue
1033 : }
1034 1 : count += *v.RangeKeyLevels[l].Annotation(rangeKeySetsAnnotator{}).(*uint64)
1035 : }
1036 1 : return count
1037 : }
1038 :
1039 : // tombstonesAnnotator implements manifest.Annotator, annotating B-Tree nodes
1040 : // with the sum of the files' counts of tombstones (DEL, SINGLEDEL and RANGEDELk
1041 : // eys). Its annotation type is a *uint64. The count of tombstones may change
1042 : // once a table's stats are loaded asynchronously, so its values are marked as
1043 : // cacheable only if a file's stats have been loaded.
1044 : type tombstonesAnnotator struct{}
1045 :
1046 : var _ manifest.Annotator = tombstonesAnnotator{}
1047 :
1048 1 : func (a tombstonesAnnotator) Zero(dst interface{}) interface{} {
1049 1 : if dst == nil {
1050 1 : return new(uint64)
1051 1 : }
1052 1 : v := dst.(*uint64)
1053 1 : *v = 0
1054 1 : return v
1055 : }
1056 :
1057 : func (a tombstonesAnnotator) Accumulate(
1058 : f *fileMetadata, dst interface{},
1059 1 : ) (v interface{}, cacheOK bool) {
1060 1 : vptr := dst.(*uint64)
1061 1 : *vptr = *vptr + f.Stats.NumDeletions
1062 1 : return vptr, f.StatsValid()
1063 1 : }
1064 :
1065 1 : func (a tombstonesAnnotator) Merge(src interface{}, dst interface{}) interface{} {
1066 1 : srcV := src.(*uint64)
1067 1 : dstV := dst.(*uint64)
1068 1 : *dstV = *dstV + *srcV
1069 1 : return dstV
1070 1 : }
1071 :
1072 : // countTombstones counts the number of tombstone (DEL, SINGLEDEL and RANGEDEL)
1073 : // internal keys across all files of the LSM. It only counts keys in files for
1074 : // which table stats have been loaded. It uses a b-tree annotator to cache
1075 : // intermediate values between calculations when possible.
1076 1 : func countTombstones(v *version) (count uint64) {
1077 1 : for l := 0; l < numLevels; l++ {
1078 1 : if v.Levels[l].Empty() {
1079 1 : continue
1080 : }
1081 1 : count += *v.Levels[l].Annotation(tombstonesAnnotator{}).(*uint64)
1082 : }
1083 1 : return count
1084 : }
1085 :
1086 : // valueBlocksSizeAnnotator implements manifest.Annotator, annotating B-Tree
1087 : // nodes with the sum of the files' Properties.ValueBlocksSize. Its annotation
1088 : // type is a *uint64. The value block size may change once a table's stats are
1089 : // loaded asynchronously, so its values are marked as cacheable only if a
1090 : // file's stats have been loaded.
1091 : type valueBlocksSizeAnnotator struct{}
1092 :
1093 : var _ manifest.Annotator = valueBlocksSizeAnnotator{}
1094 :
1095 1 : func (a valueBlocksSizeAnnotator) Zero(dst interface{}) interface{} {
1096 1 : if dst == nil {
1097 1 : return new(uint64)
1098 1 : }
1099 1 : v := dst.(*uint64)
1100 1 : *v = 0
1101 1 : return v
1102 : }
1103 :
1104 : func (a valueBlocksSizeAnnotator) Accumulate(
1105 : f *fileMetadata, dst interface{},
1106 1 : ) (v interface{}, cacheOK bool) {
1107 1 : vptr := dst.(*uint64)
1108 1 : *vptr = *vptr + f.Stats.ValueBlocksSize
1109 1 : return vptr, f.StatsValid()
1110 1 : }
1111 :
1112 1 : func (a valueBlocksSizeAnnotator) Merge(src interface{}, dst interface{}) interface{} {
1113 1 : srcV := src.(*uint64)
1114 1 : dstV := dst.(*uint64)
1115 1 : *dstV = *dstV + *srcV
1116 1 : return dstV
1117 1 : }
1118 :
1119 : // valueBlocksSizeForLevel returns the Properties.ValueBlocksSize across all
1120 : // files for a level of the LSM. It only includes the size for files for which
1121 : // table stats have been loaded. It uses a b-tree annotator to cache
1122 : // intermediate values between calculations when possible. It must not be
1123 : // called concurrently.
1124 : //
1125 : // REQUIRES: 0 <= level <= numLevels.
1126 1 : func valueBlocksSizeForLevel(v *version, level int) (count uint64) {
1127 1 : if v.Levels[level].Empty() {
1128 1 : return 0
1129 1 : }
1130 1 : return *v.Levels[level].Annotation(valueBlocksSizeAnnotator{}).(*uint64)
1131 : }
1132 :
1133 : // compressionTypeAnnotator implements manifest.Annotator, annotating B-tree
1134 : // nodes with the compression type of the file. Its annotation type is a
1135 : // *compressionTypes. The compression type may change once a table's stats are
1136 : // loaded asynchronously, so its values are marked as cacheable only if a file's
1137 : // stats have been loaded.
1138 : type compressionTypeAnnotator struct{}
1139 :
1140 : type compressionTypes struct {
1141 : snappy, zstd, none, unknown uint64
1142 : }
1143 :
1144 : var _ manifest.Annotator = compressionTypeAnnotator{}
1145 :
1146 1 : func (a compressionTypeAnnotator) Zero(dst interface{}) interface{} {
1147 1 : if dst == nil {
1148 1 : return new(compressionTypes)
1149 1 : }
1150 1 : v := dst.(*compressionTypes)
1151 1 : *v = compressionTypes{}
1152 1 : return v
1153 : }
1154 :
1155 : func (a compressionTypeAnnotator) Accumulate(
1156 : f *fileMetadata, dst interface{},
1157 1 : ) (v interface{}, cacheOK bool) {
1158 1 : vptr := dst.(*compressionTypes)
1159 1 : switch f.Stats.CompressionType {
1160 1 : case sstable.SnappyCompression:
1161 1 : vptr.snappy++
1162 0 : case sstable.ZstdCompression:
1163 0 : vptr.zstd++
1164 1 : case sstable.NoCompression:
1165 1 : vptr.none++
1166 1 : default:
1167 1 : vptr.unknown++
1168 : }
1169 1 : return vptr, f.StatsValid()
1170 : }
1171 :
1172 1 : func (a compressionTypeAnnotator) Merge(src interface{}, dst interface{}) interface{} {
1173 1 : srcV := src.(*compressionTypes)
1174 1 : dstV := dst.(*compressionTypes)
1175 1 : dstV.snappy = dstV.snappy + srcV.snappy
1176 1 : dstV.zstd = dstV.zstd + srcV.zstd
1177 1 : dstV.none = dstV.none + srcV.none
1178 1 : dstV.unknown = dstV.unknown + srcV.unknown
1179 1 : return dstV
1180 1 : }
1181 :
1182 : // compressionTypesForLevel returns the count of sstables by compression type
1183 : // used for a level in the LSM. Sstables with compression type snappy or zstd
1184 : // are returned, while others are ignored.
1185 1 : func compressionTypesForLevel(v *version, level int) (unknown, snappy, none, zstd uint64) {
1186 1 : if v.Levels[level].Empty() {
1187 1 : return
1188 1 : }
1189 1 : compression := v.Levels[level].Annotation(compressionTypeAnnotator{}).(*compressionTypes)
1190 1 : if compression == nil {
1191 0 : return
1192 0 : }
1193 1 : return compression.unknown, compression.snappy, compression.none, compression.zstd
1194 : }
|