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