|
| 1 | +// Copyright 2025 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 tieredmeta |
| 6 | + |
| 7 | +import ( |
| 8 | + "encoding/binary" |
| 9 | + |
| 10 | + "github.com/RaduBerinde/tdigest" |
| 11 | + "github.com/cockroachdb/pebble/internal/base" |
| 12 | + "github.com/pkg/errors" |
| 13 | +) |
| 14 | + |
| 15 | +// digestDelta is the compression argument for t-digest, used to specify the |
| 16 | +// tradeoff between accuracy and memory consumption: meaning higher values give |
| 17 | +// more accuracy, but use more memory/space. Specifically, the digest has at most |
| 18 | +// 2*compression centroids, with ~1.3*compression in practice. |
| 19 | +// |
| 20 | +// A value of 100 is a common default for t-digest implementations, which should |
| 21 | +// provide at least ±1% quantile accuracy (and much better at the tails). |
| 22 | +const digestDelta = 100 |
| 23 | + |
| 24 | +// StatsHistogram is a quantile sketch using t-digest to track the distribution |
| 25 | +// of a bytes value (with a caller-determined meaning) by TieringAttribute. It |
| 26 | +// can efficiently answer questions like: |
| 27 | +// - What fraction of bytes have attribute <= threshold? (CDF) |
| 28 | +// - What attribute value covers q% of bytes? (Quantile) |
| 29 | +// - How many bytes are "cold" vs "hot"? |
| 30 | +// |
| 31 | +// The sketch is mergeable, making it easy to combine statistics from |
| 32 | +// multiple files without bucket alignment issues. |
| 33 | +type StatsHistogram struct { |
| 34 | + // TotalBytes is the sum of all bytes recorded (including BytesNoAttr). |
| 35 | + TotalBytes uint64 |
| 36 | + // TotalCount is the number of records added. |
| 37 | + TotalCount uint64 |
| 38 | + // BytesNoAttr tracks bytes with attribute=0 separately, as this typically |
| 39 | + // indicates unset/special values that shouldn't be tiered. |
| 40 | + BytesNoAttr uint64 |
| 41 | + // digest is the t-digest for non-zero attributes (read-only). |
| 42 | + digest tdigest.TDigest |
| 43 | +} |
| 44 | + |
| 45 | +// CDF returns the fraction of non-zero bytes with attribute <= threshold. |
| 46 | +// Returns a value in [0, 1]. |
| 47 | +// Example: CDF(coldThreshold) tells you what fraction of bytes are "cold". |
| 48 | +func (s *StatsHistogram) CDF(threshold base.TieringAttribute) float64 { |
| 49 | + if s.BytesWithAttr() == 0 { |
| 50 | + return 0 |
| 51 | + } |
| 52 | + return s.digest.CDF(float64(threshold)) |
| 53 | +} |
| 54 | + |
| 55 | +// Quantile returns the attribute value at quantile ~q (where q is in [0, 1]) of |
| 56 | +// bytes with a tiering attribute set. |
| 57 | +// Example: Quantile(0.5) returns a value close to the median value. |
| 58 | +func (s *StatsHistogram) Quantile(q float64) base.TieringAttribute { |
| 59 | + return base.TieringAttribute(s.digest.Quantile(q)) |
| 60 | +} |
| 61 | + |
| 62 | +// BytesWithAttr returns bytes that have a tiering attribute set, excluding |
| 63 | +// bytes with attr=0 (which typically indicates unset/special values). |
| 64 | +func (s *StatsHistogram) BytesWithAttr() uint64 { |
| 65 | + return s.TotalBytes - s.BytesNoAttr |
| 66 | +} |
| 67 | + |
| 68 | +// BytesBelowThreshold estimates how many bytes (excluding NoAttrBytes) have |
| 69 | +// attribute <= threshold. This is useful for tiering decisions. |
| 70 | +func (s *StatsHistogram) BytesBelowThreshold(threshold base.TieringAttribute) uint64 { |
| 71 | + return uint64(s.CDF(threshold) * float64(s.BytesWithAttr())) |
| 72 | +} |
| 73 | + |
| 74 | +// BytesAboveThreshold estimates how many non-zero bytes have attribute > threshold. |
| 75 | +// This is useful for tiering decisions. |
| 76 | +func (s *StatsHistogram) BytesAboveThreshold(threshold base.TieringAttribute) uint64 { |
| 77 | + return s.BytesWithAttr() - s.BytesBelowThreshold(threshold) |
| 78 | +} |
| 79 | + |
| 80 | +// encode serializes the histogram to bytes. The encoding format is: |
| 81 | +// |
| 82 | +// <total bytes> <total count> <zero count> <digest size> <digest data> |
| 83 | +func (s *StatsHistogram) encode() []byte { |
| 84 | + // Calculate the size needed for the t-digest. |
| 85 | + digestSize := s.digest.SerializedSize() |
| 86 | + |
| 87 | + // Pre-allocate with estimated capacity (4 uvarints + digest). |
| 88 | + // Each uvarint is at most 10 bytes for uint64. |
| 89 | + buf := make([]byte, 0, 4*binary.MaxVarintLen64+digestSize) |
| 90 | + |
| 91 | + buf = binary.AppendUvarint(buf, s.TotalBytes) |
| 92 | + buf = binary.AppendUvarint(buf, s.TotalCount) |
| 93 | + buf = binary.AppendUvarint(buf, s.BytesNoAttr) |
| 94 | + buf = binary.AppendUvarint(buf, uint64(digestSize)) |
| 95 | + buf = s.digest.Serialize(buf) |
| 96 | + |
| 97 | + return buf |
| 98 | +} |
| 99 | + |
| 100 | +// DecodeStatsHistogram decodes a StatsHistogram from the provided buffer. |
| 101 | +// The encoding format is: |
| 102 | +// |
| 103 | +// <total bytes> <total count> <zero bytes> <digest size> <digest data> |
| 104 | +func DecodeStatsHistogram(buf []byte) (StatsHistogram, error) { |
| 105 | + var h StatsHistogram |
| 106 | + var n int |
| 107 | + |
| 108 | + h.TotalBytes, n = binary.Uvarint(buf) |
| 109 | + if n <= 0 { |
| 110 | + return StatsHistogram{}, base.CorruptionErrorf("cannot decode TotalBytes from buf %x", buf) |
| 111 | + } |
| 112 | + buf = buf[n:] |
| 113 | + |
| 114 | + h.TotalCount, n = binary.Uvarint(buf) |
| 115 | + if n <= 0 { |
| 116 | + return StatsHistogram{}, base.CorruptionErrorf("cannot decode TotalCount from buf %x", buf) |
| 117 | + } |
| 118 | + buf = buf[n:] |
| 119 | + |
| 120 | + h.BytesNoAttr, n = binary.Uvarint(buf) |
| 121 | + if n <= 0 { |
| 122 | + return StatsHistogram{}, base.CorruptionErrorf("cannot decode BytesNoAttr from buf %x", buf) |
| 123 | + } |
| 124 | + buf = buf[n:] |
| 125 | + |
| 126 | + digestSize, n := binary.Uvarint(buf) |
| 127 | + if n <= 0 { |
| 128 | + return StatsHistogram{}, base.CorruptionErrorf("cannot decode digest size from buf %x", buf) |
| 129 | + } |
| 130 | + buf = buf[n:] |
| 131 | + |
| 132 | + if int(digestSize) != len(buf) { |
| 133 | + return StatsHistogram{}, errors.Errorf("histogram digest size %d does not match remaining data %d", |
| 134 | + digestSize, len(buf)) |
| 135 | + } |
| 136 | + |
| 137 | + if digestSize > 0 { |
| 138 | + var digest tdigest.TDigest |
| 139 | + _, err := tdigest.Deserialize(&digest, buf[:digestSize]) |
| 140 | + if err != nil { |
| 141 | + return StatsHistogram{}, err |
| 142 | + } |
| 143 | + h.digest = digest |
| 144 | + } |
| 145 | + |
| 146 | + return h, nil |
| 147 | +} |
| 148 | + |
| 149 | +// Merge combines another histogram into this one using a t-digest Merger. |
| 150 | +// This is used to aggregate statistics from multiple files. |
| 151 | +func (s *StatsHistogram) Merge(other *StatsHistogram) { |
| 152 | + s.TotalBytes += other.TotalBytes |
| 153 | + s.TotalCount += other.TotalCount |
| 154 | + s.BytesNoAttr += other.BytesNoAttr |
| 155 | + |
| 156 | + merger := tdigest.MakeMerger(digestDelta) |
| 157 | + merger.Merge(&s.digest) |
| 158 | + merger.Merge(&other.digest) |
| 159 | + merged := merger.Digest() |
| 160 | + s.digest = merged |
| 161 | +} |
| 162 | + |
| 163 | +// histogramWriter wraps a tdigest.Builder for building during sstable/blob file |
| 164 | +// writing. |
| 165 | +type histogramWriter struct { |
| 166 | + builder tdigest.Builder |
| 167 | + totalBytes uint64 |
| 168 | + totalCount uint64 |
| 169 | + zeroBytes uint64 |
| 170 | +} |
| 171 | + |
| 172 | +func newHistogramWriter() *histogramWriter { |
| 173 | + return &histogramWriter{ |
| 174 | + builder: tdigest.MakeBuilder(digestDelta), |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +// record adds a data point to the histogram. Records with attr=0 are tracked |
| 179 | +// separately and excluded from the t-digest - as zero typically indicates |
| 180 | +// an unset or special value that shouldn't influence tiering decisions. |
| 181 | +func (w *histogramWriter) record(attr base.TieringAttribute, bytes uint64) { |
| 182 | + w.totalCount++ |
| 183 | + w.totalBytes += bytes |
| 184 | + if attr == 0 { |
| 185 | + w.zeroBytes += bytes |
| 186 | + return |
| 187 | + } |
| 188 | + w.builder.Add(float64(attr), float64(bytes)) |
| 189 | +} |
| 190 | + |
| 191 | +func (w *histogramWriter) encode() []byte { |
| 192 | + digest := w.builder.Digest() |
| 193 | + h := StatsHistogram{ |
| 194 | + TotalBytes: w.totalBytes, |
| 195 | + TotalCount: w.totalCount, |
| 196 | + BytesNoAttr: w.zeroBytes, |
| 197 | + digest: digest, |
| 198 | + } |
| 199 | + return h.encode() |
| 200 | +} |
0 commit comments