Unverified Commit 08d7a524 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

turbo-persistence: space-amplification driven compaction with adaptive hash shards (#99268)

## Summary

Turbo-tasks GC can only shrink the persistent cache if compaction merges
each tombstone with the data it deletes. Canary's compaction algorithm
leaves many tombstones behind so with GC enabled the cache is only 5%
smaller than without it. This PR replaces compaction with a
space-amplification policy on hash shards, modeled on RocksDB universal
compaction and Cassandra UCS. With GC enabled, the cache stays ~flat.

### Cache size over 31 consecutive vercel-site builds

Same canary base and the same commits in every arm. The size is measured
after each build, including its compaction on shutdown.

| build | canary, GC off | canary, GC on | this PR, GC off | this PR, GC
on |
|---|---|---|---|---|
| 1 | 2.59 GB | 2.60 GB | 2.63 GB | 2.64 GB |
| 10 | 3.15 GB | 3.12 GB | 3.24 GB | 3.07 GB |
| 20 | 3.42 GB | 2.92 GB | 3.20 GB | 3.06 GB |
| 22 | 4.57 GB | 3.87 GB | 3.55 GB | 3.18 GB |
| 31 | **4.19 GB** | **3.96 GB** | **3.75 GB** | **3.00 GB** |
| growth, build 1 → 31 | +1.60 GB | +1.36 GB | +1.12 GB | **+0.36 GB** |

- **GC saves 5% with canary's compaction and 20% with this one** (final
size, GC on vs. off). A full compaction of the final cache puts the live
data at about 2.8 GB, so this PR with GC is within about 8% of it.
- **Build 22 rewrites a lot of task data.** Canary grows by about 1 GB
at that build in both modes and never recovers the space. This PR
absorbs it and merges the superseded versions away within a few builds.

### Why canary's compaction can't keep up with GC

- **Old versions and tombstones don't reliably meet the data they
supersede.** Canary wrote recently read keys and the rest into separate
warm and cold files and never merged across them.
- **Its merge triggers couldn't see the duplication.** There were
duplication-byte thresholds and `max_merge_bytes`. Most of the garbage
is superseded versions of a relatively small set of large, frequently
rewritten `TaskData` values, so those triggers missed it and produced
inefficient merge groups.

### New Compaction policy
- **Shards:** each family's key space is split into power-of-two
hash-prefix shards. The count starts at
`FamilyConfig::initial_shard_bits` (TaskData 8 shards, TaskMeta 4,
TaskCache and Infra 1) and then follows the family's size, targeting
about 256 MB per shard.
- It doubles once shards exceed 1.5× the target and halves below 0.5×,
so a size near a boundary doesn't flip it.
- Commits and merges split SST files at shard boundaries, so each shard
is compacted on its own. Files written with an old count are re-split by
their shard's next merge, not by a rewrite.
- Write batches still buffer a family in at most 4 collectors (64 MB
each) as on canary, split by a prefix of the shard bits, so their memory
doesn't grow with the shard count. Families with more than 4 shards
write proportionally smaller commit files.
- **Bottom merge:** when the files above a shard's bottom run exceed 50%
of it, the whole shard is merged into a new bottom run. Tombstones count
as the entries they delete. This is the merge that reliably drops
superseded entries and tombstones.
- This is analogous to a 'full compaction' but it targets a single shard
and is targeting files covering typically <0.5G of data.
- **Intermediate merge:** more than 4 files above the bottom run are
merged together, which bounds the number of files a lookup consults.
- **Budget:** bottom merges per family stop after rewriting 3× the
family's fresh (not yet compacted) bytes, so cost follows new writes and
shards spread over multiple compactions. 3× is how often a written byte
is copied in steady state: a bottom merge at the 50% trigger rewrites
1.5× the bytes above the bottom run for every 0.5× of them.
- **Hard cap:** a shard over twice the trigger (100% space
amplification), or with more than twice `max_files_above_bottom` files
above its bottom run, is bottom-merged even when the budget is spent.
This bounds how far a shard can fall behind, e.g. after a GC purge: its
tombstones count as the entries they delete, but they're small and give
little budget.
- **Tiny families:** a 1 MB floor keeps families like Infra, which
rewrite ~everything on every commit, out of bottom merges.
- **Ranking:** jobs are ranked across families by how far over their
trigger they are, so intermediate merges aren't starved.

**Hot/cold split, only in bottom merges.** A bottom merge writes
recently read keys and the rest into separate hot and cold files. It
always includes every file of its shard, hot and cold, so this does not
interfere with deduplication. Used-key tracking is unchanged from
canary: each commit records the keys it read in its meta file, and
compaction uses the union of all live meta files. The marks are never
copied into meta files written by compaction, so they expire with the
commit that recorded them.
- This Hot/cold split is less aggressive than canary. See below for Read
locality impacts.

**Reads:** a lookup only consults the SST files of its key's shard. A
per-family index keeps each shard's hash ranges densely, newest first,
so lookups scan them sequentially.

## Verification

- The cache size benchmark above: vercel-site, 31 commits, GC with
`rootTtlMs=0`. Earlier runs on the same base reproduce the GC-on results
(canary 3.93–3.99 GB, this PR 3.00–3.05 GB).
- **Read locality**, measured with temporary instrumentation that isn't
part of this PR. It counts the distinct SST blocks each build reads, and
the distinct 128 KiB file regions they touch as an estimate of squashfs
decompression. Same base, same builds, builds 2–31, GC on:

  | | canary | no split | this PR (bottom split) |
  |---|---|---|---|
| distinct blocks read per build, median | 1.35 GB | 1.80 GB | 1.55 GB |
| 128 KiB regions touched per build, median / total | 2.42 / 64.2 GB | —
| 2.63 / 68.8 GB |

The bottom split recovers most of the locality that dropping the split
cost. Light builds still read about a third more than on canary, because
a shard's hot set only refreshes at its bottom merge. Splitting
intermediate merges as well gained about 1%, so it isn't included.
- **Lookup microbenchmark**, 16 shards × 20 uncompacted commits (320
SSTs), alternating before and after: `get` hit −14%, miss −28%,
`batch_get` −5%.
- `cargo test -p turbo-persistence` and `cargo test -p
turbo-tasks-backend --tests` pass. The selector has unit tests, and a
simulation whose sweep supports the 50% threshold.

<!-- NEXT_JS_LLM -->
parent bd932b38
...@@ -37,6 +37,7 @@ fn main() -> Result<()> { ...@@ -37,6 +37,7 @@ fn main() -> Result<()> {
sst_size, sst_size,
flags, flags,
block_count, block_count,
entry_count,
} in meta_file.entries } in meta_file.entries
{ {
println!( println!(
...@@ -46,7 +47,7 @@ fn main() -> Result<()> { ...@@ -46,7 +47,7 @@ fn main() -> Result<()> {
); );
println!(" AMQF {amqf_entries} entries = {} KiB", amqf_size / 1024); println!(" AMQF {amqf_entries} entries = {} KiB", amqf_size / 1024);
println!( println!(
" {} KiB = {block_count} blocks (avg {} bytes/block)", " {} KiB = {block_count} blocks (avg {} bytes/block), {entry_count} entries",
sst_size / 1024, sst_size / 1024,
sst_size / block_count as u64 sst_size / block_count as u64
); );
......
...@@ -19,7 +19,7 @@ auto-hash-map = { workspace = true } ...@@ -19,7 +19,7 @@ auto-hash-map = { workspace = true }
bitfield = { workspace = true } bitfield = { workspace = true }
byteorder = { workspace = true } byteorder = { workspace = true }
crc32fast = { workspace = true } crc32fast = { workspace = true }
dashmap = { workspace = true} dashmap = { workspace = true }
either = { workspace = true } either = { workspace = true }
fs-err = { workspace = true } fs-err = { workspace = true }
jiff = { version = "0.2.10", features = ["serde"] } jiff = { version = "0.2.10", features = ["serde"] }
......
...@@ -57,6 +57,7 @@ A meta file can contain metadata about multiple SST files. The metadata is store ...@@ -57,6 +57,7 @@ A meta file can contain metadata about multiple SST files. The metadata is store
- 4 bytes magic number (0xFE4ADA4A) - 4 bytes magic number (0xFE4ADA4A)
- 4 bytes key family - 4 bytes key family
- 1 byte compression algorithm, which must match the configuration used to open the database - 1 byte compression algorithm, which must match the configuration used to open the database
- 1 byte shard bits: the family had `2^bits` shards when the SST files were split
- 4 bytes count of obsolete SST files - 4 bytes count of obsolete SST files
- foreach obsolete SST file - foreach obsolete SST file
- 4 bytes sequence number of the obsolete SST file - 4 bytes sequence number of the obsolete SST file
...@@ -70,11 +71,14 @@ A meta file can contain metadata about multiple SST files. The metadata is store ...@@ -70,11 +71,14 @@ A meta file can contain metadata about multiple SST files. The metadata is store
- 4 bytes flags - 4 bytes flags
- bit 0: cold (compacted and not recently accessed) - bit 0: cold (compacted and not recently accessed)
- bit 1: fresh (not yet compacted) - bit 1: fresh (not yet compacted)
- bit 2: bottom (part of the bottom run of its shard, written by merging all SST files of the shard; without the cold bit it holds the recently read keys)
- 4 bytes entry count
- 4 bytes tombstone count (entries that delete a key or a key-value pair), used by compaction to estimate reclaimable bytes
- 4 bytes end of AMQF offset relative to start of all AMQF data - 4 bytes end of AMQF offset relative to start of all AMQF data
- 4 bytes end of AMQF offset relative to start of all AMQF data of the "used key hashes" AMQF - 4 bytes end of AMQF offset relative to start of all AMQF data of the "used key hashes" AMQF
- foreach described SST file - foreach described SST file
- serialized AMQF - serialized AMQF
- serialized "used key hashes" AMQF - serialized "used key hashes" AMQF: the keys read since the previous commit (only in meta files written by a commit)
### SST file ### SST file
...@@ -376,10 +380,16 @@ DEL 17: (2, 3, 4, 5, 6, 7, 8, 9) ...@@ -376,10 +380,16 @@ DEL 17: (2, 3, 4, 5, 6, 7, 8, 9)
CURRENT: 17 CURRENT: 17
``` ```
Configuration options for compactions are: ### Choosing merge jobs
- max number of SST files that are merged at once The key space of each family is split into a power-of-two number of shards by the leading bits of the key hash (starting at `FamilyConfig::initial_shard_bits`, then following the size of the family so that a shard holds about `DbConfig::target_shard_size` after compaction). The shard count doubles once a shard's bottom run exceeds 1.5 times the target and halves once it falls below half of it, so it doesn't flip back and forth. The size is estimated from the shards that have a bottom run, and the count is kept until one exists; the current count is recorded in each meta file. Commits and merges split SST files at shard boundaries, so each shard is compacted on its own. A shard has a bottom run (SST files flagged `bottom`, written by merging all files of the shard) and the files written since, above it.
- coverage when compaction is triggered (otherwise calling compact is a noop)
- A bottom merge merges all files of a shard into a new bottom run, dropping superseded entries and tombstones. It runs when the files above the bottom run exceed `max_space_amplification_percent` of the bottom run, counting each tombstone as an average bottom entry since it deletes one. This bounds the space amplification.
- An intermediate merge merges only the files above the bottom run when there are more than `max_files_above_bottom`, to bound the number of files a lookup consults.
A bottom merge writes the entries of recently read keys (the union of the "used key hashes" AMQFs of all meta files) into separate hot SST files, and the rest into cold ones. Processes tend to read the same keys again, so this packs them into fewer blocks, which matters on storage where reads are expensive. Since a bottom merge always includes the whole shard, hot and cold files are merged together and every version of a key meets. The used keys are never copied into the meta files written by compaction, so they expire once all SST files of the commit that recorded them are merged.
Bottom merges are paced by the fresh (not yet compacted) files of the family: they are scheduled until they rewrote `rewrite_per_fresh_byte` times the size of those files (the last one may go past it, and the first one always runs), so compaction cost follows the amount of new data. Since keys are hashes, shards grow at the same rate; the rewrite quota spreads their bottom merges over multiple compactions. A skipped compaction leaves the fresh files in place, which increases the next quota. The default is 3: a bottom merge at the 50% trigger rewrites 1.5 times the bytes above the bottom run for each 0.5 of them, so in steady state a written byte is copied about 3 times. A shard over twice the trigger, or with over twice `max_files_above_bottom` files above its bottom run, is bottom merged even when the quota is reached, which bounds how far a shard can fall behind (e.g. after a GC purge, whose small tombstone files give a small quota).
## Opening ## Opening
......
...@@ -14,7 +14,8 @@ use tempfile::TempDir; ...@@ -14,7 +14,8 @@ use tempfile::TempDir;
use turbo_persistence::{ use turbo_persistence::{
ArcBytes, BlockCache, CompactConfig, Compression, DbConfig as TpDbConfig, Entry, EntryValue, ArcBytes, BlockCache, CompactConfig, Compression, DbConfig as TpDbConfig, Entry, EntryValue,
FamilyConfig, FamilyKind, MetaEntryFlags, SerialScheduler, StaticSortedFile, FamilyConfig, FamilyKind, MetaEntryFlags, SerialScheduler, StaticSortedFile,
StaticSortedFileMetaData, TurboPersistence, hash_key, write_static_stored_file, StaticSortedFileMetaData, TurboPersistence, hash_key, shard::ShardBits,
write_static_stored_file,
}; };
use turbo_tasks_malloc::TurboMalloc; use turbo_tasks_malloc::TurboMalloc;
...@@ -625,6 +626,7 @@ fn prefill_multi_value_database( ...@@ -625,6 +626,7 @@ fn prefill_multi_value_database(
name: "test", name: "test",
kind: FamilyKind::MultiValue, kind: FamilyKind::MultiValue,
compression: Compression::Lz4, compression: Compression::Lz4,
initial_shard_bits: ShardBits::new(0),
}], }],
..TpDbConfig::new() ..TpDbConfig::new()
}; };
...@@ -701,6 +703,7 @@ fn open_multi_value_db(path: &Path) -> TurboPersistence<SerialScheduler, 1> { ...@@ -701,6 +703,7 @@ fn open_multi_value_db(path: &Path) -> TurboPersistence<SerialScheduler, 1> {
name: "test", name: "test",
kind: FamilyKind::MultiValue, kind: FamilyKind::MultiValue,
compression: Compression::Lz4, compression: Compression::Lz4,
initial_shard_bits: ShardBits::new(0),
}], }],
..TpDbConfig::new() ..TpDbConfig::new()
}; };
...@@ -862,6 +865,7 @@ fn bench_family_sharding(c: &mut Criterion) { ...@@ -862,6 +865,7 @@ fn bench_family_sharding(c: &mut Criterion) {
name, name,
kind: FamilyKind::SingleValue, kind: FamilyKind::SingleValue,
compression: Compression::Lz4, compression: Compression::Lz4,
initial_shard_bits: ShardBits::new(0),
} }
}), }),
..TpDbConfig::new() ..TpDbConfig::new()
...@@ -968,13 +972,11 @@ fn bench_compaction(c: &mut Criterion) { ...@@ -968,13 +972,11 @@ fn bench_compaction(c: &mut Criterion) {
|(_tempdir, db)| { |(_tempdir, db)| {
// Timed: run normal compaction // Timed: run normal compaction
db.compact(&CompactConfig { db.compact(&CompactConfig {
min_merge_count: 3, max_space_amplification_percent: 50,
optimal_merge_count: 8, min_bottom_merge_bytes: 1024 * 1024,
max_merge_count: 64, max_files_above_bottom: 6,
max_merge_bytes: 512 * MB, rewrite_per_fresh_byte: 3.0,
min_merge_duplication_bytes: 50 * MB, max_merge_jobs: 16,
optimal_merge_duplication_bytes: 100 * MB,
max_merge_segment_count: 16,
}) })
.unwrap(); .unwrap();
black_box(db) black_box(db)
...@@ -1048,6 +1050,7 @@ fn bench_write_multi_value(c: &mut Criterion) { ...@@ -1048,6 +1050,7 @@ fn bench_write_multi_value(c: &mut Criterion) {
name: "test", name: "test",
kind: FamilyKind::MultiValue, kind: FamilyKind::MultiValue,
compression: Compression::Lz4, compression: Compression::Lz4,
initial_shard_bits: ShardBits::new(0),
}], }],
..TpDbConfig::new() ..TpDbConfig::new()
}; };
......
...@@ -148,7 +148,7 @@ impl<K: StoreKey, const SIZE_SHIFT: usize> Collector<K, SIZE_SHIFT> { ...@@ -148,7 +148,7 @@ impl<K: StoreKey, const SIZE_SHIFT: usize> Collector<K, SIZE_SHIFT> {
/// This method does not deduplicate entries. /// This method does not deduplicate entries.
/// ///
/// In debug builds, asserts that SingleValue families have no duplicate keys. /// In debug builds, asserts that SingleValue families have no duplicate keys.
pub fn sorted(&mut self, family_kind: FamilyKind) -> (&[CollectorEntry<K>], usize) { pub fn sorted(&mut self, family_kind: FamilyKind) -> &[CollectorEntry<K>] {
// We can use unstable sort because the relative order of equal elements // We can use unstable sort because the relative order of equal elements
// doesn't matter — duplicates are either disallowed (SingleValue) or // doesn't matter — duplicates are either disallowed (SingleValue) or
// allowed without deduplication (MultiValue). // allowed without deduplication (MultiValue).
...@@ -181,7 +181,7 @@ impl<K: StoreKey, const SIZE_SHIFT: usize> Collector<K, SIZE_SHIFT> { ...@@ -181,7 +181,7 @@ impl<K: StoreKey, const SIZE_SHIFT: usize> Collector<K, SIZE_SHIFT> {
// Suppress unused variable warning in release builds // Suppress unused variable warning in release builds
let _ = family_kind; let _ = family_kind;
(&self.entries, self.total_key_size) &self.entries
} }
/// Clears the collector. /// Clears the collector.
...@@ -202,7 +202,7 @@ impl<K: StoreKey, const SIZE_SHIFT: usize> Collector<K, SIZE_SHIFT> { ...@@ -202,7 +202,7 @@ impl<K: StoreKey, const SIZE_SHIFT: usize> Collector<K, SIZE_SHIFT> {
} }
/// Clears the collector and drops the capacity /// Clears the collector and drops the capacity
pub fn drop_contents(&mut self) { pub fn clear_and_drop_capacity(&mut self) {
drop(take(&mut self.entries)); drop(take(&mut self.entries));
self.total_key_size = 0; self.total_key_size = 0;
self.total_value_size = 0; self.total_value_size = 0;
......
use std::{
collections::{BTreeMap, btree_map},
iter::Peekable,
ops::{Bound, RangeBounds, RangeInclusive},
};
/// Values that can be used as the bound of an interval.
///
/// Currently only implemented for `u64`.
pub trait IntervalBound: Copy + Ord {
fn bound_min() -> Self;
fn bound_max() -> Self;
fn checked_increment(&self) -> Option<Self>;
fn checked_decrement(&self) -> Option<Self>;
}
impl IntervalBound for u64 {
fn bound_min() -> Self {
Self::MIN
}
fn bound_max() -> Self {
Self::MAX
}
fn checked_increment(&self) -> Option<Self> {
self.checked_add(1)
}
fn checked_decrement(&self) -> Option<Self> {
self.checked_sub(1)
}
}
fn into_range_inclusive<B>(bounds: impl RangeBounds<B>) -> RangeInclusive<B>
where
B: IntervalBound,
{
let start = match bounds.start_bound() {
Bound::Included(b) => *b,
Bound::Excluded(b) => b.checked_increment().unwrap_or_else(B::bound_max),
Bound::Unbounded => B::bound_min(),
};
let end = match bounds.end_bound() {
Bound::Included(b) => *b,
Bound::Excluded(b) => b.checked_decrement().unwrap_or_else(B::bound_min),
Bound::Unbounded => B::bound_max(),
};
start..=end
}
/// This is a conceptually more efficient version of an array `[T: u64::MAX]` (or `[T:
/// B::bound_max()]`), where entries are deduplicated using a variation on [run-length
/// encoding][rle].
///
/// Ranges can be split or merged by [`IntervalMap::update`] and [`IntervalMap::replace`].
///
/// [rle]: https://en.wikipedia.org/wiki/Run-length_encoding
pub struct IntervalMap<T, B = u64> {
/// Represents the start of non-overlapping ranges with values.
///
/// When constructing `IntervalMap`, we add a `Default::default()` interval starting at
/// `B::bound_min()`.
///
/// Each interval extends until the start of the next one (exclusive). The last span in the map
/// extends to `B::bound_max()` (inclusive).
interval_starts: BTreeMap<B, T>,
}
impl<T, B> Default for IntervalMap<T, B>
where
T: Default,
B: IntervalBound,
{
fn default() -> Self {
Self::new()
}
}
impl<T, B> IntervalMap<T, B>
where
T: Default,
B: IntervalBound,
{
/// Creates a new [`IntervalMap`] with a [`Default::default`] value spanning from
/// [`IntervalBound::bound_min`] to [`IntervalBound::bound_max`] (inclusive). Typically, that's
/// `0..=u64::MAX`.
///
/// Note: Unlike many stdlib collections, this collection will perform an allocation during
/// construction. This could be avoided in the future by special-casing of the initial default
/// interval as a lazily constructed or stack allocated value.
pub fn new() -> Self {
let mut interval_starts = BTreeMap::new();
interval_starts.insert(B::bound_min(), Default::default());
Self { interval_starts }
}
}
impl<T, B> IntervalMap<T, B>
where
B: Ord,
{
/// Returns the largest value that's less than ([`Bound::Excluded`]) or equal to
/// ([`Bound::Included`]) the given `bound`.
///
/// It is guaranteed to return a value, as there's always an interval starting at
/// [`IntervalBound::bound_min`].
///
/// This is an approximation of the nightly-only `BTreeMap::upper_bound` API, but it returns a
/// key-value pair instead of a cursor.
///
/// Panics if `bound` is `Bound::Excluded(IntervalBound::bound_min())`, as that would imply an
/// empty range.
fn upper_bound(&self, bound: Bound<&B>) -> Option<(&B, &T)> {
self.interval_starts
.range((Bound::Unbounded, bound))
.next_back()
}
}
impl<T, B> IntervalMap<T, B>
where
B: IntervalBound,
T: Clone + Eq,
{
/// Applies the update function to all values in the specified range. It doesn't iterate over
/// every value one-by-one, but instead it iterates over intersecting ranges.
///
/// Newly equal intervals are merged.
pub fn update(&mut self, range: impl RangeBounds<B>, mut update: impl FnMut(&mut T)) {
let range = into_range_inclusive(range);
let start_bound = *range.start();
let end_bound = *range.end();
if start_bound > end_bound {
return;
}
let tail = end_bound.checked_increment().map(|tb| {
(
tb,
self.upper_bound(Bound::Included(&tb))
.expect("at least one interval starting at `B::bound_min`")
.1
.clone(),
)
});
// defer insertions and removals to avoid multiple simultaneous mutable borrows
let mut updated_start_value = None;
let mut remove_list = Vec::new();
// N.B. `prev_value` can be `None` if `start_bound` is `B::bound_min()`
// this value must be cloned because we mutably borrow `interval_starts` below
let prev_value = self
.upper_bound(Bound::Excluded(&start_bound))
.map(|(_, v)| v.clone());
let mut starts_iter = self
.interval_starts
.range_mut((Bound::Included(start_bound), Bound::Included(end_bound)))
.peekable();
// insert or update an interval starting at `start_bound`
let mut prev_value_inner;
let mut prev_value =
if let Some((_, cur_value)) = starts_iter.next_if(|(b, _)| *b == &start_bound) {
update(cur_value);
if Some(&*cur_value) == prev_value.as_ref() {
// merge identical adjacent intervals
remove_list.push(start_bound);
}
cur_value
} else {
prev_value_inner = prev_value.expect(
"there's no interval starting at `start_bound`, so there must be one before it",
);
let mut cur_value = prev_value_inner.clone();
update(&mut cur_value);
if cur_value != prev_value_inner {
// only start a new interval if it's different
updated_start_value.get_or_insert(cur_value)
} else {
&mut prev_value_inner
}
};
// update existing intervals from start_bound (exclusive) to end_bound (inclusive)
if start_bound < end_bound {
for (cur_bound, cur_value) in starts_iter {
update(cur_value);
if cur_value == prev_value {
remove_list.push(*cur_bound);
}
prev_value = cur_value;
}
}
// don't modify any intervals following the ones we updated
if let Some((tail_bound, tail_value)) = tail {
if prev_value != &tail_value {
self.interval_starts.insert(tail_bound, tail_value);
} else {
// there *might* be a no-longer-needed interval start here, try to remove it
remove_list.push(tail_bound);
}
}
// apply deferred insertions and removals
for pos in remove_list {
self.interval_starts.remove(&pos);
}
if let Some(start_value) = updated_start_value {
self.interval_starts.insert(start_bound, start_value);
}
}
pub fn replace(&mut self, bounds: impl RangeBounds<B>, value: T) {
// it would be more efficient to implement this directly, but this is good enough for our
// current use-cases
self.update(bounds, |v| *v = value.clone());
}
}
impl<T, B> IntervalMap<T, B>
where
B: IntervalBound,
{
/// Returns an iterator over all the intervals intersecting with the given range and their
/// associated values.
pub fn iter_intersecting(&self, range: impl RangeBounds<B>) -> IntervalMapIterator<'_, T, B> {
fn inner<T, B>(
this: &IntervalMap<T, B>,
range: RangeInclusive<B>,
) -> IntervalMapIterator<'_, T, B>
where
B: IntervalBound,
{
// the first intersecting range may begin before `range.start()`
let (start_position, _) = this
.upper_bound(Bound::Included(range.start()))
.expect("at least one interval starting at `B::bound_min`");
IntervalMapIterator {
starts_iter: this.interval_starts.range(start_position..).peekable(),
end_bound: *range.end(),
}
}
// slightly reduce monomorphization
inner(self, into_range_inclusive(range))
}
/// Returns an iterator over all the intervals and their associated values.
pub fn iter(&self) -> IntervalMapIterator<'_, T, B> {
IntervalMapIterator {
starts_iter: self.interval_starts.range(..).peekable(),
end_bound: B::bound_max(),
}
}
}
pub struct IntervalMapIterator<'a, T, B> {
/// An iterator of `interval_starts` with an unbounded end.
starts_iter: Peekable<btree_map::Range<'a, B, T>>,
end_bound: B,
}
impl<'a, T, B> Iterator for IntervalMapIterator<'a, T, B>
where
B: IntervalBound,
{
type Item = (RangeInclusive<B>, &'a T);
fn next(&mut self) -> Option<Self::Item> {
let (start_bound, value) = self.starts_iter.next()?;
if start_bound > &self.end_bound {
return None;
}
let bound_end = self
.starts_iter
.peek()
.map(|entry| entry.0.checked_decrement().unwrap_or_else(B::bound_min))
.unwrap_or_else(|| B::bound_max());
Some(((*start_bound)..=bound_end, value))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compaction::naive_interval_map::{NaiveIntervalMap, TinyInt};
#[test]
fn test_interval_map() {
let mut map = IntervalMap::new();
map.update(5..=15, |v| *v |= 1);
map.update(10..=15, |v| *v |= 2);
map.update(10..=20, |v| *v |= 4);
map.update(0..=u64::MAX, |v| *v |= 8);
map.update(15..=20, |v| *v |= 16);
map.update(25..=30, |v| *v |= 32);
let result: Vec<_> = map.iter().collect();
let expected = vec![
(0..=4, &8),
(5..=9, &(1 | 8)),
(10..=14, &(1 | 2 | 4 | 8)),
(15..=15, &(1 | 2 | 4 | 8 | 16)),
(16..=20, &(4 | 8 | 16)),
(21..=24, &8),
(25..=30, &(8 | 32)),
(31..=u64::MAX, &8),
];
assert_eq!(result, expected);
// re-use expecting from above
let result: Vec<_> = map.iter_intersecting(..).collect();
assert_eq!(result, expected);
let result: Vec<_> = map.iter_intersecting(14..=20).collect();
let expected = vec![
(10..=14, &(1 | 2 | 4 | 8)),
(15..=15, &(1 | 2 | 4 | 8 | 16)),
(16..=20, &(4 | 8 | 16)),
];
assert_eq!(result, expected);
let result: Vec<_> = map.iter_intersecting(..=0).collect();
let expected = vec![(0..=4, &8)];
assert_eq!(result, expected);
let result: Vec<_> = map.iter_intersecting(u64::MAX..).collect();
let expected = vec![(31..=u64::MAX, &8)];
assert_eq!(result, expected);
assert!(map.iter_intersecting(0..=10).any(|(_, v)| *v & 1 != 0));
assert!(map.iter_intersecting(0..=10).any(|(_, v)| *v & 2 != 0));
assert!(!map.iter_intersecting(0..10).any(|(_, v)| *v & 2 != 0));
assert!(map.iter_intersecting(0..=50).any(|(_, v)| *v & 4 != 0));
assert!(map.iter_intersecting(15..=15).all(|(_, v)| *v & 16 != 0));
assert!(!map.iter_intersecting(0..=15).all(|(_, v)| *v & 16 != 0));
assert!(map.iter_intersecting(0..=15).any(|(_, v)| *v & 16 != 0));
assert!(map.iter_intersecting(20..=20).all(|(_, v)| *v & 16 != 0));
assert!(map.iter_intersecting(20..).any(|(_, v)| *v & 16 != 0));
assert!(map.iter_intersecting(..).all(|(_, v)| *v & 8 != 0));
assert!(map.iter_intersecting(0..=0).all(|(_, v)| *v & 8 != 0));
assert!(map.iter_intersecting(u64::MAX..).all(|(_, v)| *v & 8 != 0));
assert!(map.iter_intersecting(123..=1234).all(|(_, v)| *v & 8 != 0));
}
#[test]
fn test_interval_map_empty() {
let map: IntervalMap<u32> = IntervalMap::new();
let result: Vec<_> = map.iter().collect();
assert_eq!(result.len(), 1);
assert_eq!(result[0], (0..=u64::MAX, &0));
}
#[test]
fn test_interval_map_single_point() {
let mut map: IntervalMap<u32> = IntervalMap::new();
map.replace(10..=10, 1);
let expected = vec![(0..=9, &0), (10..=10, &1), (11..=u64::MAX, &0)];
let result: Vec<_> = map.iter().collect();
assert_eq!(result, expected);
}
fn for_all_tiny_int_ranges<T: Copy>(
values: impl IntoIterator<Item = T>,
mut cb: impl FnMut((RangeInclusive<TinyInt>, T)),
) {
for value in values {
for start in 0..=TinyInt::MAX.0 {
for end in start..=TinyInt::MAX.0 {
cb((TinyInt(start)..=TinyInt(end), value));
}
}
}
}
#[cfg(not(miri))]
#[test]
fn test_exhaustive_replace_versus_naive() {
for_all_tiny_int_ranges([0, 1], |a| {
for_all_tiny_int_ranges([1, 2], |b| {
for_all_tiny_int_ranges([2, 3], |c| {
let mut real_map = IntervalMap::<u32, TinyInt>::new();
let mut naive_map = NaiveIntervalMap::<u32, TinyInt>::new();
for (range, value) in [&a, &b, &c] {
real_map.replace(range.clone(), *value);
naive_map.replace(range.clone(), *value);
}
assert_eq!(
real_map.iter().collect::<Vec<_>>(),
naive_map.iter().collect::<Vec<_>>(),
)
});
});
});
}
#[cfg(not(miri))]
#[test]
fn test_exhaustive_update_versus_naive() {
for_all_tiny_int_ranges([1, 2], |a| {
for_all_tiny_int_ranges([2, 4], |b| {
for_all_tiny_int_ranges([4, 8], |c| {
let mut real_map = IntervalMap::<u32, TinyInt>::new();
let mut naive_map = NaiveIntervalMap::<u32, TinyInt>::new();
for (range, flag) in [&a, &b, &c] {
real_map.update(range.clone(), |v| *v |= flag);
naive_map.update(range.clone(), |v| *v |= flag);
}
assert_eq!(
real_map.iter().collect::<Vec<_>>(),
naive_map.iter().collect::<Vec<_>>(),
)
});
});
});
}
}
mod interval_map;
pub mod selector; pub mod selector;
#[cfg(test)]
mod naive_interval_map;
use std::{
fmt::{self, Display},
iter::Peekable,
ops::{RangeBounds, RangeInclusive},
slice,
};
use crate::compaction::interval_map::IntervalBound;
/// An integer with a very limited range to allow for exhaustive unit tests of
/// all possible values.
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub struct TinyInt(pub u8);
impl TinyInt {
pub const MIN: TinyInt = TinyInt(0);
pub const MAX: TinyInt = TinyInt(6);
}
impl IntervalBound for TinyInt {
fn bound_min() -> Self {
Self::MIN
}
fn bound_max() -> Self {
Self::MAX
}
fn checked_increment(&self) -> Option<Self> {
if self < &Self::bound_max() {
Some(Self(self.0 + 1))
} else {
None
}
}
fn checked_decrement(&self) -> Option<Self> {
if self > &Self::bound_min() {
Some(Self(self.0 - 1))
} else {
None
}
}
}
impl Display for TinyInt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
/// An impractically slow but very simple implementation of `IntervalMap` used as a known-good
/// version for testing the correctness of `IntervalMap`.
#[allow(dead_code)]
pub struct NaiveIntervalMap<T, B = TinyInt> {
values: Vec<(B, T)>,
}
impl<T, B> NaiveIntervalMap<T, B>
where
T: Default,
B: IntervalBound,
{
pub fn new() -> Self {
let mut values = Vec::new();
let mut pos = Some(B::bound_min());
while let Some(cur) = &pos {
values.push((*cur, T::default()));
pos = cur.checked_increment();
}
Self { values }
}
}
impl<T, B> NaiveIntervalMap<T, B>
where
B: IntervalBound,
T: Clone,
{
pub fn update(&mut self, bounds: impl RangeBounds<B>, mut update: impl FnMut(&mut T)) {
for (pos, cur_value) in &mut self.values {
if bounds.contains(pos) {
update(cur_value);
}
}
}
pub fn replace(&mut self, bounds: impl RangeBounds<B>, value: T) {
self.update(bounds, |v| *v = value.clone());
}
}
impl<T, B> NaiveIntervalMap<T, B>
where
B: IntervalBound,
{
pub fn iter(&self) -> NaiveIntervalMapIterator<'_, T, B> {
NaiveIntervalMapIterator {
values_iter: self.values.iter().peekable(),
}
}
}
pub struct NaiveIntervalMapIterator<'a, T, B> {
values_iter: Peekable<slice::Iter<'a, (B, T)>>,
}
impl<'a, T, B> Iterator for NaiveIntervalMapIterator<'a, T, B>
where
B: IntervalBound,
T: Eq,
{
type Item = (RangeInclusive<B>, &'a T);
fn next(&mut self) -> Option<Self::Item> {
let (start_pos, cur_value) = self.values_iter.next()?;
let mut end_pos = *start_pos;
while self.values_iter.peek().is_some_and(|(_, v)| v == cur_value) {
end_pos = self.values_iter.next().unwrap().0;
}
Some(((*start_pos)..=end_pos, cur_value))
}
}
use std::ops::RangeInclusive; //! Chooses which SST files to merge.
//!
//! The key space of each family is split into shards (see [`crate::shard`]). Divide the SST files
//! into disjoint components (mostly this is Per shard but during shard resizes SST files can span
//! shards). For each 'component' of files we consider two kinds of merges
//!
//! - A 'bottom merge' merges all files of the component into a new bottom run. This is selected
//! based on how much the`max_space_amplification_percent` is exceeded. This bounds the bytes of
//! the shard
//! - An intermediate merge merges only the files above the bottom run, when there are more than
//! `max_files_above_bottom` of them. This bounds the number of files a lookup has to consult
//! without rewriting the bottom run.
//!
//! Bottom merges are paced by the fresh bytes (written by commits and not compacted yet) of the
//! family: they are scheduled until they rewrote `rewrite_per_fresh_byte` times the fresh bytes, so
//! that the cost of compaction follows the amount of new data.
//!
//! A shard that is far behind, over twice the space amplification trigger or with over twice
//! `max_files_above_bottom` files above its bottom run, is bottom merged even when the rewrite
//! quota is reached. That bounds how far a shard can fall behind if the quota is too conservative
//!
//! If a 'component' spans multiple shards it will always be split across shard boundaries when
//! re-written.
use rustc_hash::FxHashMap; use std::ops::RangeInclusive;
use smallvec::{SmallVec, smallvec};
use crate::compaction::interval_map::IntervalMap; use crate::shard::ShardBits;
/// Represents part of a database (i.e. an SST file) with a range of keys (i.e. hashes) and a size /// Represents part of a database (i.e. an SST file) with a range of keys (i.e. hashes) and a size
/// of that data in bytes. /// of that data in bytes.
...@@ -14,399 +35,315 @@ pub trait Compactable { ...@@ -14,399 +35,315 @@ pub trait Compactable {
/// The size of the compactable database segment in bytes. /// The size of the compactable database segment in bytes.
fn size(&self) -> u64; fn size(&self) -> u64;
/// The category of the compactable. Overlap between different categories is not considered for /// Whether the segment is part of the bottom run of its shard.
/// compaction. fn is_bottom(&self) -> bool;
fn category(&self) -> u8 {
0
}
}
fn is_overlapping(a: &RangeInclusive<u64>, b: &RangeInclusive<u64>) -> bool { /// Whether the segment was written by a commit and not compacted yet.
a.start() <= b.end() && b.start() <= a.end() fn is_fresh(&self) -> bool;
}
fn spread(range: &RangeInclusive<u64>) -> u128 {
// the spread of `0..=u64::MAX` is `u64::MAX + 1`, so this could overflow as u64
u128::from(range.end() - range.start()) + 1
}
/// Extends the range `a` to include the range `b`, returns `true` if the range was extended.
fn extend_range(a: &mut RangeInclusive<u64>, b: &RangeInclusive<u64>) -> bool {
let mut extended = false;
if b.start() < a.start() {
*a = (*b.start())..=(*a.end());
extended = true;
}
if b.end() > a.end() {
*a = (*a.start())..=(*b.end());
extended = true;
}
extended
}
#[cfg(test)]
#[derive(Debug)]
pub struct CompactableMetrics {
/// The total coverage of the compactables.
pub coverage: f32,
/// The maximum overlap of the compactables. /// The number of entries in the segment.
pub overlap: f32, fn entry_count(&self) -> u64;
/// The possible duplication of the compactables.
pub duplicated_size: u64,
/// The possible duplication of the compactables as factor to total size.
pub duplication: f32,
}
/// Computes metrics about the compactables.
#[cfg(test)]
pub fn compute_metrics<T: Compactable>(
compactables: &[T],
full_range: RangeInclusive<u64>,
) -> CompactableMetrics {
let mut interval_map = IntervalMap::<Option<(DuplicationInfo, usize)>>::new();
let mut coverage = 0.0f32;
for c in compactables {
let range = c.range();
coverage += spread(&range) as f32;
interval_map.update(range.clone(), |value| {
let (dup_info, count) = value.get_or_insert_default();
dup_info.add(c.size(), &range);
*count += 1;
});
}
let full_spread = spread(&full_range) as f32;
let (duplicated_size, duplication, overlap) = interval_map
.iter()
.flat_map(|(range, value)| Some((range, value.as_ref()?)))
.map(|(range, (dup_info, count))| {
let duplicated_size = dup_info.duplication(&range);
let total_size = dup_info.size(&range);
let overlap = spread(&range) as f32 * count.saturating_sub(1) as f32;
(duplicated_size, total_size, overlap)
})
.reduce(|(dup1, total1, overlap1), (dup2, total2, overlap2)| {
(dup1 + dup2, total1 + total2, overlap1 + overlap2)
})
.map(|(duplicated_size, total_size, overlap)| {
(
duplicated_size,
if total_size > 0 {
duplicated_size as f32 / total_size as f32
} else {
0.0
},
overlap,
)
})
.unwrap_or((0, 0.0, 0.0));
CompactableMetrics { /// The number of tombstones in the segment.
coverage: coverage / full_spread, fn tombstone_count(&self) -> u64;
overlap: overlap / full_spread,
duplicated_size,
duplication,
}
} }
/// Configuration for the compaction algorithm. /// Configuration for the compaction algorithm.
#[derive(Clone)] #[derive(Clone, Copy, Debug)]
pub struct CompactConfig { pub struct CompactConfig {
/// The minimum number of files to merge at once. /// A shard is merged into a new bottom run when the files above its bottom run are larger than
pub min_merge_count: usize, /// this percentage of the bottom run. E.g. `50` merges a shard with a 100MB bottom run once
/// more than 50MB are above it. `0` merges every shard that has files above its bottom run.
/// The optimal number of files to merge at once. pub max_space_amplification_percent: u16,
pub optimal_merge_count: usize,
/// A shard is only merged into a new bottom run when at least this many bytes are above its
/// The maximum number of files to merge at once. /// bottom run. This is to avoid tiny families that always rewrite everything doing constant
pub max_merge_count: usize, /// full merges and starving other work.
pub min_bottom_merge_bytes: u64,
/// The maximum size of all files to merge at once.
pub max_merge_bytes: u64, /// The files above the bottom run of a shard are merged when there are more than this many
/// (at least one, since merging a single file would only move it).
/// The amount of duplication that need to be in a merge job to be considered for merging. pub max_files_above_bottom: usize,
pub min_merge_duplication_bytes: u64,
/// Bottom merges of a family are scheduled until they rewrote this many bytes per byte of its
/// The optimal duplication size for merging. /// fresh files; the last one may go past it, and the first one always runs. E.g. with `3.0`,
pub optimal_merge_duplication_bytes: u64, /// after commits wrote 10MB to a family, no more bottom merges are scheduled once they rewrote
/// 30MB, except for shards far behind.
/// The maximum number of merge segments to determine. ///
pub max_merge_segment_count: usize, /// A bottom merge at a space amplification of `a` rewrites `1 + a` times the bytes above the
/// bottom run for every `a` of them, i.e. `(1 + a) / a` rewritten bytes per fresh byte: 3 at
/// the default 50% trigger. So `3.0` is how often a written byte is copied in steady state.
pub rewrite_per_fresh_byte: f32,
/// The maximum number of merge jobs in a compaction, across all families. Merge jobs run in
/// parallel, so this bounds the work of a compaction. It doesn't limit the number of files
/// merged by a job.
pub max_merge_jobs: usize,
} }
impl Default for CompactConfig { impl Default for CompactConfig {
fn default() -> Self { fn default() -> Self {
const MB: u64 = 1024 * 1024;
Self { Self {
min_merge_count: 2, max_space_amplification_percent: 50,
optimal_merge_count: 8, min_bottom_merge_bytes: 1024 * 1024,
max_merge_count: 32, max_files_above_bottom: 6,
max_merge_bytes: 500 * MB, rewrite_per_fresh_byte: 3.0,
min_merge_duplication_bytes: 50 * MB, max_merge_jobs: 8,
optimal_merge_duplication_bytes: 100 * MB,
max_merge_segment_count: 8,
} }
} }
} }
#[derive(Clone, Default, Eq, PartialEq)] impl CompactConfig {
struct DuplicationInfo { /// A config that merges every shard with files above its bottom run into a new bottom run.
/// The sum of all encountered scaled sizes. pub fn full() -> Self {
total_size: u64, Self {
/// The largest encountered single scaled size. max_space_amplification_percent: 0,
max_size: u64, min_bottom_merge_bytes: 0,
} // Irrelevant, as bottom merges are always chosen.
max_files_above_bottom: usize::MAX,
impl DuplicationInfo { rewrite_per_fresh_byte: f32::INFINITY,
/// Get a value in the range `0..=u64` that represents the estimated amount of duplication max_merge_jobs: usize::MAX,
/// across the given range. The units are arbitrary, but linear.
fn duplication(&self, range: &RangeInclusive<u64>) -> u64 {
if self.max_size == self.total_size {
return 0;
}
// the maximum numerator value is `u64::MAX + 1`
u64::try_from(
u128::from(self.total_size - self.max_size) * spread(range)
/ (u128::from(u64::MAX) + 1),
)
.expect("should not overflow, denominator was `u64::MAX+1`")
}
/// The estimated size (in bytes) of a database segment containing `range` keys.
#[cfg(test)]
fn size(&self, range: &RangeInclusive<u64>) -> u64 {
if self.total_size == 0 {
return 0;
} }
// the maximum numerator value is `u64::MAX + 1`
u64::try_from(u128::from(self.total_size) * spread(range) / (u128::from(u64::MAX) + 1))
.expect("should not overflow, denominator was `u64::MAX+1`")
} }
}
fn add(&mut self, size: u64, range: &RangeInclusive<u64>) { /// A set of compactables to merge.
// Assumption: `size` is typically much smaller than `spread(range)`. The spread is some #[derive(Debug, Clone, PartialEq, Eq)]
// fraction of `u64` (the full possible key-space), but no SST file is anywhere close to pub struct MergeJob {
// `u64::MAX` bytes. /// Indices of the compactables, in ascending (read) order.
pub members: Vec<usize>,
/// Whether the job merges all files of its shards, i.e. writes a new bottom run.
pub bottom: bool,
}
// Scale size to full range: /// A planned merge job and how urgent it is, before merge jobs are selected across families.
let scaled_size = struct Candidate {
u64::try_from(u128::from(size) * (u128::from(u64::MAX) + 1) / spread(range)) job: MergeJob,
.unwrap_or(u64::MAX); /// How far the shard is over the limit that triggers the job, e.g. `2.0` for twice the allowed
self.total_size = self.total_size.saturating_add(scaled_size); /// space amplification or file count. Higher is more urgent.
self.max_size = self.max_size.max(scaled_size); priority: f32,
}
} }
fn total_duplication_size(duplication: &IntervalMap<FxHashMap<u8, DuplicationInfo>>) -> u64 { /// Groups the compactables into components, sets of shards that are merged together.
duplication ///
/// Normally a compactable is within a single shard and a component is one shard. But when the
/// shard count of a family grows, compactables written before cover multiple of the new shards.
/// Such a compactable can only be merged together with everything else in the shards it covers, so
/// all shards it covers belong to one component. Returns the members of each component in
/// ascending order.
fn components<T: Compactable>(compactables: &[T], shard_bits: ShardBits) -> Vec<Vec<usize>> {
let mut spans = compactables
.iter() .iter()
.map(|(range, info)| { .enumerate()
info.values() .map(|(index, c)| {
.map(|info| info.duplication(&range)) let range = c.range();
.sum::<u64>() let shard_start = shard_bits.shard_of(*range.start());
let shard_end = shard_bits.shard_of(*range.end());
(shard_start, shard_end, index)
}) })
.sum() .collect::<Vec<_>>();
spans.sort_unstable();
let mut result: Vec<(u32, Vec<usize>)> = Vec::new();
for (shard_start, shard_end, index) in spans {
match result.last_mut() {
Some((component_end, members)) if shard_start <= *component_end => {
// Grow overlapping compactables by adding a new member and possibly expanding the
// component
*component_end = (*component_end).max(shard_end);
members.push(index);
}
_ => result.push((shard_end, vec![index])),
}
}
result
.into_iter()
.map(|(_, mut members)| {
members.sort_unstable();
members
})
.collect()
} }
type MergeSegments = Vec<SmallVec<[usize; 1]>>; /// Produces a [`Candidate`] for an intermediate merge of the files `above` the bottom run of a
/// shard. Intermediate merges are ranked by how far the number of files above the bottom run
/// exceeds `max_files_above_bottom`.
fn intermediate_candidate(above: Vec<usize>, config: &CompactConfig) -> Candidate {
Candidate {
priority: above.len() as f32 / config.max_files_above_bottom.max(1) as f32,
job: MergeJob {
members: above,
bottom: false,
},
}
}
/// Computes the set of merge segments that should be run to compact the given compactables. /// Plans the merge jobs of one family, bottom merges first, each kind most urgent first.
/// fn plan_family<T: Compactable>(
/// Returns both the mergeable segments and the actual number of merge segments that were created.
pub fn get_merge_segments<T: Compactable>(
compactables: &[T], compactables: &[T],
shard_bits: ShardBits,
config: &CompactConfig, config: &CompactConfig,
) -> (MergeSegments, usize) { ) -> Vec<Candidate> {
// Process all compactables in reverse order. let fresh_bytes = compactables
// For each compactable, find the smallest set of compactables that overlaps with it and matches .iter()
// the conditions. .filter(|c| c.is_fresh())
// To find the set: .map(|c| c.size())
// - Set the current range to the range of the first unused compactable. .sum::<u64>();
// - When the set matches the conditions, add the set as merge job, mark all used compactables
// and continue. let mut bottom_candidates = Vec::new();
// - Find the next unused compactable that overlaps with the current range. let mut intermediate_candidates = Vec::new();
// - If the range need to be extended, restart the search with the new range. for members in components(compactables, shard_bits) {
// - If the compactable is within the range, add it to the current set. let (bottom, above): (Vec<usize>, Vec<usize>) =
// - If the set is too large, mark the starting compactable as used and continue with the next members.iter().partition(|&&i| compactables[i].is_bottom());
if above.is_empty() {
let mut unused_compactables = compactables.iter().collect::<Vec<_>>();
let mut used_compactables = vec![false; compactables.len()];
let mut merge_segments: MergeSegments = Vec::new();
let mut real_merge_segments = 0;
// Iterate in reverse order to process the compactables from the end.
// That's the order in which compactables are read, so we need to keep that order.
'outer: while let Some(start_compactable) = unused_compactables.pop() {
let start_index = unused_compactables.len();
if used_compactables[start_index] {
continue; continue;
} }
if real_merge_segments >= config.max_merge_segment_count { // A bottom file is older than the files above it that overlap it. After the shard count
// We have reached the maximum number of merge jobs, so we stop here. // shrank, a component can also hold a newer bottom file of another former shard, which
break; // covers different keys.
} debug_assert!(
let start_compactable_range = start_compactable.range(); bottom.iter().all(|&b| above.iter().all(|&a| {
let start_compactable_size = start_compactable.size(); let (b_range, a_range) = (compactables[b].range(), compactables[a].range());
let start_compactable_category = start_compactable.category(); b < a || b_range.end() < a_range.start() || a_range.end() < b_range.start()
let mut current_range = start_compactable_range.clone(); })),
"bottom files must be older than the files above them that they overlap"
// We might need to restart the search if we need to extend the range. );
'search: loop { // The bottom run consists of multiple files when the bottom merge output exceeds the size
let mut current_set = smallvec![start_index]; // of a file, or when the component spans multiple shards after the shard count grew.
let mut current_size = start_compactable_size; let bottom_bytes = bottom.iter().map(|&i| compactables[i].size()).sum::<u64>();
let mut duplication = IntervalMap::<FxHashMap<u8, DuplicationInfo>>::new(); let above_bytes = above.iter().map(|&i| compactables[i].size()).sum::<u64>();
duplication.update(start_compactable_range.clone(), |dup_info| { // A bottom merge drops the entries deleted by tombstones above the bottom run, which are
dup_info // much larger than the tombstones. Estimate them with the average entry size of the bottom
.entry(start_compactable_category) // run, which has no tombstones. This overestimates, as tombstones can delete entries above
.or_default() // the bottom run, or nothing, and entries above the bottom run shadow each other, but it
.add(start_compactable_size, &start_compactable_range); // makes a shard with many deletes merge, which it wouldn't by size alone.
}); let bottom_entries = bottom
let mut current_skip = 0; .iter()
.map(|&i| compactables[i].entry_count())
// We will capture compactables in the current_range until we find a optimal merge .sum::<u64>();
// segment or are limited by size or count. let above_tombstones = above
loop { .iter()
// Early exit if we have found an optimal merge segment. .map(|&i| compactables[i].tombstone_count())
let duplication_size = total_duplication_size(&duplication); .sum::<u64>();
let optimal_merge_job = current_set.len() >= config.optimal_merge_count let deleted_bytes = bottom_bytes
&& duplication_size >= config.optimal_merge_duplication_bytes; .checked_div(bottom_entries)
if optimal_merge_job { .unwrap_or(0)
for &i in current_set.iter() { .saturating_mul(above_tombstones);
used_compactables[i] = true; // Both the files above the bottom run and the entries they delete are garbage that a
} // bottom merge reclaims.
current_set.reverse(); let reclaimable_bytes = above_bytes.saturating_add(deleted_bytes);
merge_segments.push(current_set); let limit = f64::from(config.max_space_amplification_percent) / 100.0;
real_merge_segments += 1; let amplification = if bottom_bytes == 0 {
continue 'outer; f64::INFINITY
} } else {
reclaimable_bytes as f64 / bottom_bytes as f64
// If we are limited by size or count, we might also create a merge segment if it's };
// within the limits. if amplification > limit && reclaimable_bytes >= config.min_bottom_merge_bytes {
let valid_merge_job = current_set.len() >= config.min_merge_count let candidate = Candidate {
&& duplication_size >= config.min_merge_duplication_bytes; job: MergeJob {
let mut end_job = members,
|mut current_set: SmallVec<[usize; 1]>, used_compactables: &mut Vec<bool>| { bottom: true,
if valid_merge_job { },
for &i in current_set.iter() { priority: if limit > 0.0 {
used_compactables[i] = true; (amplification / limit) as f32
} } else {
current_set.reverse(); f32::INFINITY
merge_segments.push(current_set); },
real_merge_segments += 1; };
} else { // Far behind: bottom merged even when the rewrite quota is reached. A trigger of 0
merge_segments.push(smallvec![start_index]); // merges every shard anyway, and then only the quota limits the rewrites.
} let overdue = limit > 0.0
}; && (amplification > 2.0 * limit || above.len() > 2 * config.max_files_above_bottom);
bottom_candidates.push((candidate, bottom_bytes + above_bytes, above, overdue));
// Check if we run into the count or size limit. } else if above.len() > config.max_files_above_bottom.max(1) {
if current_set.len() >= config.max_merge_count intermediate_candidates.push(intermediate_candidate(above, config));
|| current_size >= config.max_merge_bytes
{
// The set is so large so we can't add more compactables to it.
end_job(current_set, &mut used_compactables);
continue 'outer;
}
// Find the next compactable that overlaps with the current range.
let Some((next_index, compactable)) = unused_compactables
.iter()
.enumerate()
.rev()
.skip(current_skip)
.find(|(i, compactable)| {
if used_compactables[*i] {
return false;
}
let range = compactable.range();
is_overlapping(&current_range, &range)
})
else {
// There are no more compactables that overlap with the current range.
end_job(current_set, &mut used_compactables);
continue 'outer;
};
current_skip = unused_compactables.len() - next_index;
// Check if we run into the size limit.
let size = compactable.size();
if current_size + size > config.max_merge_bytes {
// The next compactable is too large to be added to the current set.
end_job(current_set, &mut used_compactables);
continue 'outer;
}
// Check if the next compactable is larger than the current range. We need to
// restart from beginning here as there could be previously skipped compactables
// that are within the larger range.
let range = compactable.range();
if extend_range(&mut current_range, &range) {
// The range was extended, so we need to restart the search.
continue 'search;
}
// The next compactable is within the current range, so we can add it to the current
// set.
current_set.push(next_index);
current_size += size;
let category = compactable.category();
duplication.update(range.clone(), |dup_info| {
dup_info.entry(category).or_default().add(size, &range);
});
}
} }
} }
while merge_segments.last().is_some_and(|s| s.len() == 1) { // Schedule the most amplified shards until the rewrite quota is reached. Shards past it still
// Remove segments that only contain a single compactable. // get an intermediate merge if they have too many files.
merge_segments.pop(); bottom_candidates.sort_by(|a, b| b.0.priority.total_cmp(&a.0.priority));
let mut rewrite_target = if config.rewrite_per_fresh_byte.is_finite() {
// Float to int casts saturate.
(f64::from(config.rewrite_per_fresh_byte) * fresh_bytes as f64) as u64
} else {
// Not `INFINITY * fresh_bytes`, which is NaN (a quota of 0) without fresh bytes.
u64::MAX
};
let mut result = Vec::new();
for (candidate, cost, above, overdue) in bottom_candidates {
// The first job always runs, even when the quota is 0, and we keep scheduling jobs while
// the quota isn't reached, so that we don't pathologically rewrite too little.
if result.is_empty() || rewrite_target > 0 || overdue {
rewrite_target = rewrite_target.saturating_sub(cost);
result.push(candidate);
} else if above.len() > config.max_files_above_bottom.max(1) {
// The quota is reached, but an intermediate merge of the same shard is cheap and
// still bounds the number of files a lookup consults.
intermediate_candidates.push(intermediate_candidate(above, config));
}
} }
intermediate_candidates.sort_by(|a, b| b.priority.total_cmp(&a.priority));
result.extend(intermediate_candidates);
result
}
// Reverse it since we processed in reverse order. /// Plans the merge jobs for all families, limited to `max_merge_jobs` jobs in total. Each family is
merge_segments.reverse(); /// given as its compactables, in the order they are read (oldest first), and its shards.
///
// Remove single compectable segments that don't overlap with previous segments. We don't need /// Returns the merge jobs of each family. The jobs of a family don't overlap each other, and each
// to touch them. /// includes all files overlapping it, except that an intermediate merge leaves out the bottom run,
let mut used_ranges = IntervalMap::<bool>::new(); /// which is older. So the outputs can be placed after all existing files without moving any file.
merge_segments.retain(|segment| { pub fn plan_compaction<T: Compactable>(
// Remove a single element segments which doesn't overlap with previous used ranges. families: &[(&[T], ShardBits)],
if segment.len() == 1 { config: &CompactConfig,
let range = compactables[segment[0]].range(); ) -> Vec<Vec<MergeJob>> {
if !used_ranges.iter_intersecting(range).any(|(_, v)| *v) { let mut candidates = families
return false; .iter()
} .enumerate()
} .flat_map(|(family, (compactables, shard_bits))| {
// Mark the ranges of the segment as used. plan_family(compactables, *shard_bits, config)
for i in segment { .into_iter()
let range = compactables[*i].range(); .enumerate()
used_ranges.replace(range, true); .map(move |(order, candidate)| (family, order, candidate))
} })
true .collect::<Vec<_>>();
// Most over its limit first, so that intermediate merges, which bound the files a lookup
// consults, are not starved by bottom merges. Ties prefer bottom merges, then keep each
// family's order, then family order.
candidates.sort_by(|a, b| {
b.2.priority
.total_cmp(&a.2.priority)
.then(b.2.job.bottom.cmp(&a.2.job.bottom))
.then(a.1.cmp(&b.1))
.then(a.0.cmp(&b.0))
}); });
let mut result = vec![Vec::new(); families.len()];
(merge_segments, real_merge_segments) for (family, _, candidate) in candidates.into_iter().take(config.max_merge_jobs) {
result[family].push(candidate.job);
}
for jobs in &mut result {
jobs.sort_by_key(|job| job.members[0]);
}
result
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::{ use std::collections::{BTreeMap, BTreeSet};
fmt::Debug,
mem::{replace, swap},
};
use rand::{RngExt, SeedableRng, seq::SliceRandom}; use rand::{RngExt, SeedableRng, seq::SliceRandom};
use super::*; use super::*;
struct TestCompactable { #[derive(Clone, Debug)]
struct File {
range: RangeInclusive<u64>, range: RangeInclusive<u64>,
size: u64, size: u64,
bottom: bool,
fresh: bool,
} }
impl Compactable for TestCompactable { impl Compactable for File {
fn range(&self) -> RangeInclusive<u64> { fn range(&self) -> RangeInclusive<u64> {
self.range.clone() self.range.clone()
} }
...@@ -414,343 +351,477 @@ mod tests { ...@@ -414,343 +351,477 @@ mod tests {
fn size(&self) -> u64 { fn size(&self) -> u64 {
self.size self.size
} }
fn is_bottom(&self) -> bool {
self.bottom
}
fn is_fresh(&self) -> bool {
self.fresh
}
fn entry_count(&self) -> u64 {
0
}
fn tombstone_count(&self) -> u64 {
0
}
} }
fn compact<const N: usize>( fn file(shard: u32, shard_bits: u8, size: u64, bottom: bool, fresh: bool) -> File {
ranges: [RangeInclusive<u64>; N], File {
config: &CompactConfig, range: ShardBits::new(shard_bits).range(shard),
) -> Vec<Vec<usize>> { size,
let compactables = ranges bottom,
fresh,
}
}
/// The default config without the byte floor, since test files are tiny, and with the file
/// count limit the tests are written for, so they don't depend on the default.
fn test_config() -> CompactConfig {
CompactConfig {
min_bottom_merge_bytes: 0,
max_files_above_bottom: 4,
..Default::default()
}
}
fn plan(files: &[File], shard_bits: u8, config: &CompactConfig) -> Vec<(Vec<usize>, bool)> {
plan_compaction(&[(files, ShardBits::new(shard_bits))], config)
.remove(0)
.into_iter() .into_iter()
.map(|range| TestCompactable { range, size: 100 }) .map(|job| (job.members, job.bottom))
.collect::<Vec<_>>();
let (jobs, _) = get_merge_segments(&compactables, config);
jobs.into_iter()
.map(|job| job.into_iter().collect())
.collect() .collect()
} }
#[test] #[test]
fn test_compaction_jobs_by_count() { fn test_shard_without_bottom_run_gets_one() {
let merge_jobs = compact( let files = [file(0, 0, 100, false, true), file(0, 0, 100, false, true)];
[ assert_eq!(plan(&files, 0, &test_config()), vec![(vec![0, 1], true)]);
0..=10,
10..=30,
9..=13,
0..=30,
40..=44,
41..=42,
41..=47,
90..=100,
30..=40,
],
&CompactConfig {
min_merge_count: 2,
optimal_merge_count: 3,
max_merge_count: 4,
max_merge_bytes: u64::MAX,
min_merge_duplication_bytes: 0,
optimal_merge_duplication_bytes: 0,
max_merge_segment_count: usize::MAX,
},
);
assert_eq!(merge_jobs, vec![vec![1, 2, 3], vec![5, 6, 8]]);
} }
#[test] #[test]
fn test_compaction_jobs_by_size() { fn test_bottom_merge_by_space_amplification() {
let merge_jobs = compact( let config = test_config();
[ // 40% above the bottom run: nothing to do.
0..=10, let files = [file(0, 0, 1000, true, false), file(0, 0, 400, false, true)];
10..=30, assert_eq!(plan(&files, 0, &config), vec![]);
9..=13, // 60%: merge the shard into a new bottom run.
0..=30, let files = [file(0, 0, 1000, true, false), file(0, 0, 600, false, true)];
40..=44, assert_eq!(plan(&files, 0, &config), vec![(vec![0, 1], true)]);
41..=42,
41..=47,
90..=100,
30..=40,
],
&CompactConfig {
min_merge_count: 2,
optimal_merge_count: 2,
max_merge_count: usize::MAX,
max_merge_bytes: 300,
min_merge_duplication_bytes: 0,
optimal_merge_duplication_bytes: u64::MAX,
max_merge_segment_count: usize::MAX,
},
);
assert_eq!(merge_jobs, vec![vec![1, 2, 3], vec![5, 6, 8]]);
} }
#[test] #[test]
fn test_compaction_jobs_full() { fn test_intermediate_merge_by_file_count() {
let merge_jobs = compact( let mut files = vec![file(0, 0, 1000, true, false)];
[ files.extend((0..5).map(|_| file(0, 0, 10, false, true)));
0..=10, assert_eq!(
10..=30, plan(&files, 0, &test_config()),
9..=13, vec![(vec![1, 2, 3, 4, 5], false)]
0..=30,
40..=44,
41..=42,
41..=47,
90..=100,
30..=40,
],
&CompactConfig {
min_merge_count: 2,
optimal_merge_count: usize::MAX,
max_merge_count: usize::MAX,
max_merge_bytes: u64::MAX,
min_merge_duplication_bytes: 0,
optimal_merge_duplication_bytes: u64::MAX,
max_merge_segment_count: usize::MAX,
},
); );
assert_eq!(merge_jobs, vec![vec![0, 1, 2, 3, 4, 5, 6, 8]]); files.pop();
assert_eq!(plan(&files, 0, &test_config()), vec![]);
} }
#[test] #[test]
fn test_compaction_jobs_big() { fn test_budget_spreads_bottom_merges() {
let merge_jobs = compact( // All four shards are above the threshold, but the fresh data only pays for one bottom
[ // merge. The most amplified shard goes first.
0..=10, let mut files = (0..4)
10..=30, .map(|shard| file(shard, 2, 1000, true, false))
9..=13, .collect::<Vec<_>>();
0..=30, files.extend((0..4).map(|shard| file(shard, 2, 600 + u64::from(shard), false, true)));
40..=44, let config = CompactConfig {
41..=42, rewrite_per_fresh_byte: 0.1,
41..=47, ..test_config()
90..=100, };
30..=40, assert_eq!(plan(&files, 2, &config), vec![(vec![3, 7], true)]);
], // With a large enough quota, all of them are merged.
&CompactConfig { assert_eq!(
min_merge_count: 2, plan(&files, 2, &test_config()),
optimal_merge_count: 7, vec![
max_merge_count: usize::MAX, (vec![0, 4], true),
max_merge_bytes: u64::MAX, (vec![1, 5], true),
min_merge_duplication_bytes: 0, (vec![2, 6], true),
optimal_merge_duplication_bytes: 0, (vec![3, 7], true)
max_merge_segment_count: usize::MAX, ]
},
); );
assert_eq!(merge_jobs, vec![vec![1, 2, 3, 4, 5, 6, 8]]);
} }
#[test] #[test]
fn test_compaction_jobs_small() { fn test_full_config_merges_every_shard_without_fresh_bytes() {
let merge_jobs = compact( // Nothing is fresh (everything was compacted before), so the quota is 0 for a finite
[ // factor, but the full config has no quota.
0..=10, let mut files = (0..4)
10..=30, .map(|shard| file(shard, 2, 1000, true, false))
9..=13, .collect::<Vec<_>>();
0..=30, files.extend((0..4).map(|shard| file(shard, 2, 10, false, false)));
40..=44, assert_eq!(plan(&files, 2, &CompactConfig::full()).len(), 4);
41..=42, // With a finite factor, only the first job runs (the full config's trigger is 0, so no
41..=47, // shard counts as far behind).
90..=100, let config = CompactConfig {
30..=40, rewrite_per_fresh_byte: 3.0,
], ..CompactConfig::full()
&CompactConfig { };
min_merge_count: 2, assert_eq!(plan(&files, 2, &config).len(), 1);
optimal_merge_count: 2, }
max_merge_count: usize::MAX,
max_merge_bytes: u64::MAX, #[test]
min_merge_duplication_bytes: 0, fn test_quota_stops_when_exactly_reached() {
optimal_merge_duplication_bytes: 0, // Four shards, each a 360 byte bottom file with 140 compacted and 100 fresh bytes above it
max_merge_segment_count: usize::MAX, // (67%, over the trigger but under twice it), so each job rewrites 600 bytes. The quota is
}, // 3 * 400 fresh bytes = 1200, which two jobs reach exactly: a third one doesn't run.
); let mut files = (0..4)
assert_eq!( .map(|shard| file(shard, 2, 360, true, false))
merge_jobs, .collect::<Vec<_>>();
vec![vec![0, 1], vec![2, 3], vec![4, 5], vec![6, 8]] files.extend((0..4).map(|shard| file(shard, 2, 140, false, false)));
files.extend((0..4).map(|shard| file(shard, 2, 100, false, true)));
assert_eq!(plan(&files, 2, &test_config()).len(), 2);
}
#[test]
fn test_shards_far_behind_are_merged_over_the_quota() {
// Four shards over the trigger with nothing fresh, so the quota allows only the first
// bottom merge: at 60% and 70% (under twice the trigger), 110% (over twice the trigger),
// and 60% with 9 files above the bottom run (over twice `max_files_above_bottom`).
let mut files = (0..4)
.map(|shard| file(shard, 2, 1000, true, false))
.collect::<Vec<_>>();
files.extend(
[(0, 600), (1, 700), (2, 1100)].map(|(shard, size)| file(shard, 2, size, false, false)),
); );
files.extend((0..9).map(|_| file(3, 2, 600 / 9 + 1, false, false)));
let config = CompactConfig {
rewrite_per_fresh_byte: 0.0,
..test_config()
};
let bottom_merged = plan(&files, 2, &config)
.into_iter()
.filter(|(_, bottom)| *bottom)
.map(|(members, _)| members[0])
.collect::<Vec<_>>();
// Shard 2 (most amplified, and over twice the trigger) runs first and shard 3 is over twice
// the file count; shards 0 and 1 wait for quota.
assert_eq!(bottom_merged, vec![2, 3]);
} }
pub fn debug_print_compactables<T: Compactable>(compactables: &[T], max_key: u64) { #[test]
const WIDTH: usize = 128; fn test_byte_floor_skips_bottom_merges_of_tiny_shards() {
let char_width: u64 = max_key / WIDTH as u64; // Every commit rewrites the whole (tiny) family: always amplified, but not worth a bottom
for (i, c) in compactables.iter().enumerate() { // merge. It only gets an intermediate merge once there are enough files.
let range = c.range(); let mut files = vec![file(0, 0, 50, true, false)];
let size = c.size(); files.push(file(0, 0, 50, false, true));
let start = usize::try_from(range.start() / char_width).unwrap(); let config = CompactConfig {
let end = usize::try_from(range.end() / char_width).unwrap(); min_bottom_merge_bytes: 1000,
let mut line = format!("{i:>3} | "); ..test_config()
for j in 0..WIDTH { };
if j >= start && j <= end { assert_eq!(plan(&files, 0, &config), vec![]);
line.push('█'); files.extend((0..4).map(|_| file(0, 0, 50, false, true)));
} else { assert_eq!(plan(&files, 0, &config), vec![(vec![1, 2, 3, 4, 5], false)]);
line.push(' ');
}
}
println!("{line} | {size:>6}");
}
} }
#[cfg(not(miri))]
#[test] #[test]
fn simulate_compactions() { fn test_intermediate_merges_are_not_starved() {
const KEY_RANGE: u64 = 10000; // One job slot: a family with far too many files above its bottom run wins over a family
const WARM_KEY_COUNT: usize = 100; // that is only slightly over the space amplification threshold.
const INITIAL_CHUNK_SIZE: usize = 100; let mut many_files = vec![file(0, 0, 1000, true, false)];
const ITERATIONS: usize = 100; many_files.extend((0..8).map(|_| file(0, 0, 1, false, true)));
let amplified = [file(0, 0, 1000, true, false), file(0, 0, 600, false, true)];
let config = CompactConfig {
max_merge_jobs: 1,
..test_config()
};
let jobs = plan_compaction(
&[
(&many_files[..], ShardBits::new(0)),
(&amplified[..], ShardBits::new(0)),
],
&config,
);
assert_eq!(jobs[0].len(), 1);
assert!(!jobs[0][0].bottom);
assert!(jobs[1].is_empty());
}
let mut rnd = rand::rngs::SmallRng::from_seed([0; 32]); #[test]
let mut keys = (0..KEY_RANGE).collect::<Vec<_>>(); fn test_coarse_files_merge_the_shards_they_span() {
keys.shuffle(&mut rnd); // A bottom run written with 2 shards, and fresh files written with 4 shards.
let files = [
file(0, 1, 1000, true, false),
file(1, 1, 1000, true, false),
file(0, 2, 600, false, true),
file(1, 2, 10, false, true),
file(3, 2, 10, false, true),
];
assert_eq!(plan(&files, 2, &test_config()), vec![(vec![0, 2, 3], true)]);
}
let mut batch_index = 0; #[test]
let mut containers = keys fn test_merge_job_limit_across_families() {
.chunks(INITIAL_CHUNK_SIZE) let a = [file(0, 0, 100, false, true), file(0, 0, 100, false, true)];
.map(|keys| Container::new(batch_index, keys.to_vec())) let b = [file(0, 0, 100, false, true), file(0, 0, 100, false, true)];
.collect::<Vec<_>>(); let config = CompactConfig {
max_merge_jobs: 1,
..test_config()
};
let jobs = plan_compaction(
&[(&a[..], ShardBits::new(0)), (&b[..], ShardBits::new(0))],
&config,
);
assert_eq!(jobs.iter().map(Vec::len).sum::<usize>(), 1);
}
let mut warm_keys = (0..WARM_KEY_COUNT) /// A simulated SST file.
.map(|_| { struct Container {
let i = rnd.random_range(0..keys.len()); /// Sorted keys, and whether the entry is a tombstone.
keys.swap_remove(i) keys: Vec<(u64, bool)>,
}) bottom: bool,
.collect::<Vec<_>>(); fresh: bool,
}
let mut number_of_compactions = 0; impl Compactable for Container {
fn range(&self) -> RangeInclusive<u64> {
for _ in 0..ITERATIONS { self.keys[0].0..=self.keys.last().unwrap().0
let total_size = containers.iter().map(|c| c.keys.len()).sum::<usize>(); }
let metrics = compute_metrics(&containers, 0..=KEY_RANGE);
debug_print_compactables(&containers, KEY_RANGE);
println!(
"size: {}, coverage: {}, overlap: {}, duplication: {}, items: {}",
total_size,
metrics.coverage,
metrics.overlap,
metrics.duplication,
containers.len()
);
assert!(containers.len() < 400);
// assert!(metrics.duplication < 4.0);
let config = CompactConfig {
max_merge_count: 16,
min_merge_count: 2,
optimal_merge_count: 4,
max_merge_bytes: 5000,
min_merge_duplication_bytes: 500,
optimal_merge_duplication_bytes: 1000,
max_merge_segment_count: 4,
};
let (jobs, _) = get_merge_segments(&containers, &config);
if !jobs.is_empty() {
println!("{jobs:?}");
batch_index += 1; fn size(&self) -> u64 {
do_compact(&mut containers, jobs, batch_index); self.keys.len() as u64
number_of_compactions += 1; }
let new_metrics = compute_metrics(&containers, 0..=KEY_RANGE); fn is_bottom(&self) -> bool {
println!( self.bottom
"Compaction done: coverage: {} ({}), overlap: {} ({}), duplication: {} ({}), \ }
duplicated_size: {} ({})",
new_metrics.coverage,
new_metrics.coverage - metrics.coverage,
new_metrics.overlap,
new_metrics.overlap - metrics.overlap,
new_metrics.duplication,
new_metrics.duplication - metrics.duplication,
new_metrics.duplicated_size,
(new_metrics.duplicated_size as f32) - metrics.duplicated_size as f32,
);
} else {
println!("No compaction needed");
}
// Modify warm keys fn is_fresh(&self) -> bool {
batch_index += 1; self.fresh
let pieces = rnd.random_range(1..4); }
for chunk in warm_keys.chunks(warm_keys.len().div_ceil(pieces)) {
containers.push(Container::new(batch_index, chunk.to_vec()));
}
// Change some warm keys fn entry_count(&self) -> u64 {
let changes = rnd.random_range(0..100); self.keys.len() as u64
for _ in 0..changes {
let i = rnd.random_range(0..warm_keys.len());
let j = rnd.random_range(0..keys.len());
swap(&mut warm_keys[i], &mut keys[j]);
}
} }
println!("Number of compactions: {number_of_compactions}");
let metrics = compute_metrics(&containers, 0..=KEY_RANGE); fn tombstone_count(&self) -> u64 {
assert!(number_of_compactions < 30); self.keys.iter().filter(|(_, tombstone)| *tombstone).count() as u64
assert!(containers.len() < 30); }
assert!(metrics.duplication < 0.5);
} }
struct Container { /// Splits sorted entries at shard boundaries, like commits and merges do.
batch_index: usize, fn split_by_shard(
keys: Vec<u64>, entries: Vec<(u64, bool)>,
shard_bits: ShardBits,
bottom: bool,
fresh: bool,
) -> Vec<Container> {
let mut by_shard = BTreeMap::<u32, Vec<(u64, bool)>>::new();
for entry in entries {
by_shard
.entry(shard_bits.shard_of(entry.0))
.or_default()
.push(entry);
}
by_shard
.into_values()
.map(|keys| Container {
keys,
bottom,
fresh,
})
.collect()
} }
impl Container { /// Runs the merge jobs like the database does. Returns the number of entries written.
fn new(batch_index: usize, mut keys: Vec<u64>) -> Self { fn run_jobs(
keys.sort_unstable(); containers: &mut Vec<Container>,
Self { batch_index, keys } jobs: Vec<MergeJob>,
shard_bits: ShardBits,
) -> u64 {
let mut written = 0;
let mut outputs = Vec::new();
let mut merged = BTreeSet::new();
for job in jobs {
let oldest = job.members[0];
// Newer entries win.
let mut entries = job
.members
.iter()
.rev()
.flat_map(|&i| containers[i].keys.iter().copied())
.collect::<Vec<_>>();
entries.sort_by_key(|(key, _)| *key);
entries.dedup_by_key(|(key, _)| *key);
// Tombstones are dropped when no older file holds the key.
entries.retain(|&(key, tombstone)| {
!tombstone
|| containers[..oldest]
.iter()
.any(|c| c.keys.binary_search_by_key(&key, |(k, _)| *k).is_ok())
});
written += entries.len() as u64;
outputs.extend(split_by_shard(entries, shard_bits, job.bottom, false));
merged.extend(job.members);
} }
let mut i = 0;
containers.retain(|_| {
i += 1;
!merged.contains(&(i - 1))
});
containers.extend(outputs);
written
} }
impl Compactable for Container { const KEY_COUNT: u64 = 20_000;
fn range(&self) -> RangeInclusive<u64> { /// Spreads keys over the hash space like real key hashes.
(self.keys[0])..=(*self.keys.last().unwrap()) const KEY_SCALE: u64 = u64::MAX / KEY_COUNT;
}
struct SimulationResult {
compactions_with_bottom_merges: usize,
/// Entries written by commits and by compactions.
written: u64,
rewritten: u64,
/// The highest space amplification (stored / live entries) after a compaction, once
/// everything was compacted once.
max_space_amplification: f64,
/// The most files a lookup has to consult, after a compaction.
max_files_per_shard: usize,
}
fn size(&self) -> u64 { /// A commit rewrites a churning set of hot keys and deletes some cold keys, like a build with
self.keys.len() as u64 /// garbage collection. The database is compacted after every commit.
fn simulate(
config: &CompactConfig,
shard_bits: ShardBits,
iterations: usize,
) -> SimulationResult {
let mut rnd = rand::rngs::SmallRng::from_seed([0; 32]);
let mut live = (0..KEY_COUNT).map(|k| k * KEY_SCALE).collect::<Vec<_>>();
live.shuffle(&mut rnd);
let mut containers = split_by_shard(
{
let mut all = live.iter().map(|&k| (k, false)).collect::<Vec<_>>();
all.sort_unstable();
all
},
shard_bits,
false,
true,
);
let mut written = KEY_COUNT;
let mut rewritten = 0;
let mut result = SimulationResult {
compactions_with_bottom_merges: 0,
written: 0,
rewritten: 0,
max_space_amplification: 0.0,
max_files_per_shard: 0,
};
let hot_count = KEY_COUNT as usize / 20;
for iteration in 0..iterations {
let jobs = plan_compaction(&[(&containers[..], shard_bits)], config).remove(0);
if jobs.iter().any(|job| job.bottom) {
result.compactions_with_bottom_merges += 1;
}
rewritten += run_jobs(&mut containers, jobs, shard_bits);
if iteration >= iterations / 4 {
let stored = containers.iter().map(|c| c.keys.len()).sum::<usize>();
result.max_space_amplification = result
.max_space_amplification
.max(stored as f64 / live.len() as f64);
for shard in 0..shard_bits.count() {
let range = shard_bits.range(shard);
let files = containers
.iter()
.filter(|c| {
let r = c.range();
r.start() <= range.end() && range.start() <= r.end()
})
.count();
result.max_files_per_shard = result.max_files_per_shard.max(files);
}
}
// Rewrite the hot keys (the first part of `live`) and churn the hot set a bit.
let mut commit = live[..hot_count]
.iter()
.map(|&k| (k, false))
.collect::<Vec<_>>();
for _ in 0..hot_count / 10 {
let i = rnd.random_range(0..hot_count);
let j = rnd.random_range(hot_count..live.len());
live.swap(i, j);
}
// Delete some cold keys and add as many new keys, like tasks collected and created by
// a build, so the live data stays about the same size.
for _ in 0..rnd.random_range(0..KEY_COUNT as usize / 200) {
let i = rnd.random_range(hot_count..live.len());
commit.push((live[i], true));
let new_key = rnd.random::<u64>();
live[i] = new_key;
commit.push((new_key, false));
}
commit.sort_unstable();
written += commit.len() as u64;
containers.extend(split_by_shard(commit, shard_bits, false, true));
} }
result.written = written;
result.rewritten = rewritten;
result
} }
impl Debug for Container { fn simulation_config(
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { max_space_amplification_percent: u16,
let (l, r) = self.range().into_inner(); rewrite_per_fresh_byte: f32,
write!( ) -> CompactConfig {
f, CompactConfig {
"#{} {}b {l} - {r} ({})", max_space_amplification_percent,
self.batch_index, rewrite_per_fresh_byte,
self.keys.len(), max_merge_jobs: usize::MAX,
r - l ..test_config()
)
} }
} }
fn do_compact(containers: &mut Vec<Container>, segments: MergeSegments, batch_index: usize) { // This 200-commit simulation didn't finish in 28 minutes under Miri. It has no unsafe code.
let total_size = containers.iter().map(|c| c.keys.len()).sum::<usize>(); #[cfg(not(miri))]
for merge_job in segments { #[test]
if merge_job.len() < 2 { fn simulate_compactions() {
let container = replace( let config = simulation_config(50, 2.0);
&mut containers[merge_job[0]], let result = simulate(&config, ShardBits::new(3), 200);
Container { let write_amplification = result.rewritten as f64 / result.written as f64;
batch_index: 0, println!(
keys: Default::default(), "space amp {:.2}, write amp {write_amplification:.2}, files per shard {}, compactions \
}, with bottom merges {}",
result.max_space_amplification,
result.max_files_per_shard,
result.compactions_with_bottom_merges
);
// The bottom run of a shard lags its data by at most the threshold, plus one commit and the
// shards waiting for quota.
assert!(result.max_space_amplification < 1.6);
assert!(result.max_files_per_shard <= config.max_files_above_bottom + 1);
assert!(write_amplification < 2.0);
}
/// Prints the trade-off between space and write amplification.
/// Run with `cargo test -p turbo-persistence -- --ignored --nocapture sweep`.
#[test]
#[ignore]
fn sweep_space_amplification() {
println!("space amp threshold % | rewrite factor | space amp | write amp | files/shard");
for threshold in [25, 50, 100, 200] {
for factor in [1.0, 2.0, 4.0, f32::INFINITY] {
let result = simulate(
&simulation_config(threshold, factor),
ShardBits::new(3),
300,
);
println!(
"{threshold:>21} | {factor:>14} | {:>9.2} | {:>9.2} | {:>11}",
result.max_space_amplification,
result.rewritten as f64 / result.written as f64,
result.max_files_per_shard
); );
containers.push(container);
} else {
let mut keys = Vec::new();
for i in merge_job {
keys.append(&mut containers[i].keys);
}
keys.sort_unstable();
keys.dedup();
containers.extend(keys.chunks(1000).map(|keys| Container {
batch_index,
keys: keys.to_vec(),
}));
} }
} }
containers.retain(|c| !c.keys.is_empty());
let total_size2 = containers.iter().map(|c| c.keys.len()).sum::<usize>();
println!("Compaction done: {total_size} -> {total_size2}",);
} }
} }
...@@ -25,7 +25,7 @@ use jiff::Timestamp; ...@@ -25,7 +25,7 @@ use jiff::Timestamp;
use memmap2::Mmap; use memmap2::Mmap;
use nohash_hasher::BuildNoHashHasher; use nohash_hasher::BuildNoHashHasher;
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use rustc_hash::FxHasher; use rustc_hash::{FxHashSet, FxHasher};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use smallvec::SmallVec; use smallvec::SmallVec;
use tracing::span::EnteredSpan; use tracing::span::EnteredSpan;
...@@ -36,7 +36,7 @@ use crate::{AccessMode, mmap_helper::advise_mmap_for_persistence}; ...@@ -36,7 +36,7 @@ use crate::{AccessMode, mmap_helper::advise_mmap_for_persistence};
use crate::{ use crate::{
DbConfig, FamilyKind, QueryKey, DbConfig, FamilyKind, QueryKey,
arc_bytes::ArcBytes, arc_bytes::ArcBytes,
compaction::selector::{Compactable, get_merge_segments}, compaction::selector::{Compactable, MergeJob, plan_compaction},
compression::{Compression, checksum_block, decompress_into_arc}, compression::{Compression, checksum_block, decompress_into_arc},
constants::{ constants::{
DATA_THRESHOLD_PER_COMPACTED_FILE, KEY_BLOCK_AVG_SIZE, KEY_BLOCK_CACHE_SIZE, DATA_THRESHOLD_PER_COMPACTED_FILE, KEY_BLOCK_AVG_SIZE, KEY_BLOCK_CACHE_SIZE,
...@@ -49,6 +49,7 @@ use crate::{ ...@@ -49,6 +49,7 @@ use crate::{
meta_file_builder::MetaFileBuilder, meta_file_builder::MetaFileBuilder,
parallel_scheduler::ParallelScheduler, parallel_scheduler::ParallelScheduler,
rc_bytes::RcBytes, rc_bytes::RcBytes,
shard::{MetaEntryIndex, ShardBits, ShardIndex},
sst_filter::SstFilter, sst_filter::SstFilter,
static_sorted_file::{BlockCache, SstLookupResult, StaticSortedFileIter}, static_sorted_file::{BlockCache, SstLookupResult, StaticSortedFileIter},
static_sorted_file_builder::{StaticSortedFileBuilderMeta, StreamingSstWriter}, static_sorted_file_builder::{StaticSortedFileBuilderMeta, StreamingSstWriter},
...@@ -99,7 +100,6 @@ pub struct Statistics { ...@@ -99,7 +100,6 @@ pub struct Statistics {
pub value_block_cache: CacheStatistics, pub value_block_cache: CacheStatistics,
pub hits: u64, pub hits: u64,
pub misses: u64, pub misses: u64,
pub miss_family: u64,
pub miss_range: u64, pub miss_range: u64,
pub miss_amqf: u64, pub miss_amqf: u64,
pub miss_key: u64, pub miss_key: u64,
...@@ -111,7 +111,6 @@ struct TrackedStats { ...@@ -111,7 +111,6 @@ struct TrackedStats {
hits_deleted: std::sync::atomic::AtomicU64, hits_deleted: std::sync::atomic::AtomicU64,
hits_small: std::sync::atomic::AtomicU64, hits_small: std::sync::atomic::AtomicU64,
hits_blob: std::sync::atomic::AtomicU64, hits_blob: std::sync::atomic::AtomicU64,
miss_family: std::sync::atomic::AtomicU64,
miss_range: std::sync::atomic::AtomicU64, miss_range: std::sync::atomic::AtomicU64,
miss_amqf: std::sync::atomic::AtomicU64, miss_amqf: std::sync::atomic::AtomicU64,
miss_key: std::sync::atomic::AtomicU64, miss_key: std::sync::atomic::AtomicU64,
...@@ -341,12 +340,15 @@ struct Inner<const FAMILIES: usize> { ...@@ -341,12 +340,15 @@ struct Inner<const FAMILIES: usize> {
/// files. Each family's files are in ascending sequence order; there are no ordering /// files. Each family's files are in ascending sequence order; there are no ordering
/// constraints across families. /// constraints across families.
meta_files_by_family: [Vec<MetaFile>; FAMILIES], meta_files_by_family: [Vec<MetaFile>; FAMILIES],
/// The current sequence number for the database. /// For each family, the SST files that can contain the keys of each shard. Must be rebuilt
current_sequence_number: u32, /// whenever `meta_files_by_family` changes.
shard_indices: [ShardIndex; FAMILIES],
/// The in progress set of hashes of keys that have been accessed. /// The in progress set of hashes of keys that have been accessed.
/// It will be flushed onto disk (into a meta file) on next commit. /// It will be flushed onto disk (into a meta file) on next commit.
/// It's a dashset to allow modification while only tracking a read lock on Inner. /// It's a dashset to allow modification while only tracking a read lock on Inner.
accessed_key_hashes: [DashSet<u64, BuildNoHashHasher<u64>>; FAMILIES], accessed_key_hashes: [DashSet<u64, BuildNoHashHasher<u64>>; FAMILIES],
/// The current sequence number for the database.
current_sequence_number: u32,
} }
impl<const FAMILIES: usize> Inner<FAMILIES> { impl<const FAMILIES: usize> Inner<FAMILIES> {
...@@ -485,9 +487,10 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -485,9 +487,10 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
read_only, read_only,
inner: RwLock::new(Inner { inner: RwLock::new(Inner {
meta_files_by_family: [(); FAMILIES].map(|_| Vec::new()), meta_files_by_family: [(); FAMILIES].map(|_| Vec::new()),
current_sequence_number: 0, shard_indices: [(); FAMILIES].map(|_| ShardIndex::default()),
accessed_key_hashes: [(); FAMILIES] accessed_key_hashes: [(); FAMILIES]
.map(|_| DashSet::with_hasher(BuildNoHashHasher::default())), .map(|_| DashSet::with_hasher(BuildNoHashHasher::default())),
current_sequence_number: 0,
}), }),
is_empty: AtomicBool::new(true), is_empty: AtomicBool::new(true),
active_write_operation: Mutex::new(None), active_write_operation: Mutex::new(None),
...@@ -697,6 +700,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -697,6 +700,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
} }
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
inner.debug_assert_meta_invariants(); inner.debug_assert_meta_invariants();
rebuild_shard_index(&self.config, inner);
inner.current_sequence_number = current; inner.current_sequence_number = current;
self.is_empty.store(inner.is_empty(), Ordering::Relaxed); self.is_empty.store(inner.is_empty(), Ordering::Relaxed);
Ok(true) Ok(true)
...@@ -814,12 +818,14 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -814,12 +818,14 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
let guard = self.acquire_write_operation("write batch")?; let guard = self.acquire_write_operation("write batch")?;
// seq_before is already the current sequence number, no second read needed. // seq_before is already the current sequence number, no second read needed.
let current = guard.seq_before; let current = guard.seq_before;
let shard_bits = shard_bits(&self.config, &self.inner.read().meta_files_by_family);
Ok(WriteBatch::new( Ok(WriteBatch::new(
guard, guard,
self.path.clone(), self.path.clone(),
current, current,
self.parallel_scheduler.clone(), self.parallel_scheduler.clone(),
self.config.family_configs, self.config.family_configs,
shard_bits,
)) ))
} }
...@@ -902,6 +908,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -902,6 +908,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
new_blob_files, new_blob_files,
keys_written, keys_written,
} = write_batch.finish(|family| { } = write_batch.finish(|family| {
// Only called for families this commit writes to: like before, reads of a family are
// not recorded by a commit without writes to it, and stay in the set for the next one.
let inner = self.inner.read(); let inner = self.inner.read();
let set = &inner.accessed_key_hashes[family as usize]; let set = &inner.accessed_key_hashes[family as usize];
// len is only a snapshot at that time and it can change while we create the filter. // len is only a snapshot at that time and it can change while we create the filter.
...@@ -1044,7 +1052,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1044,7 +1052,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
let seq = entry.sequence_number(); let seq = entry.sequence_number();
let size = entry.size(); let size = entry.size();
let flags = entry.flags(); let flags = entry.flags();
(seq, range.min_hash, range.max_hash, size, flags) let counts = (entry.entry_count(), entry.tombstone_count());
(seq, range.min_hash, range.max_hash, size, flags, counts)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
( (
...@@ -1202,10 +1211,11 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1202,10 +1211,11 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
writeln!(log, "Commit {seq:08} {keys_written} keys in {span:#}")?; writeln!(log, "Commit {seq:08} {keys_written} keys in {span:#}")?;
writeln!(log, "FAM | META SEQ | SST SEQ | RANGE")?; writeln!(log, "FAM | META SEQ | SST SEQ | RANGE")?;
for (meta_seq, family, ssts, obsolete) in new_meta_info { for (meta_seq, family, ssts, obsolete) in new_meta_info {
for (seq, min, max, size, flags) in ssts { for (seq, min, max, size, flags, (entries, tombstones)) in ssts {
writeln!( writeln!(
log, log,
"{family:3} | {meta_seq:08} | {seq:08} SST | {} ({} MiB, {})", "{family:3} | {meta_seq:08} | {seq:08} SST | {} ({} MiB, {}, \
{size} bytes, {entries} entries, {tombstones} tombstones)",
range_to_str(min, max), range_to_str(min, max),
size / 1024 / 1024, size / 1024 / 1024,
flags flags
...@@ -1297,6 +1307,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1297,6 +1307,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
} }
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
inner.debug_assert_meta_invariants(); inner.debug_assert_meta_invariants();
rebuild_shard_index(&self.config, &mut inner);
inner.current_sequence_number = seq; inner.current_sequence_number = seq;
self.is_empty.store(inner.is_empty(), Ordering::Relaxed); self.is_empty.store(inner.is_empty(), Ordering::Relaxed);
// The write guard must be released after publishing the matching empty state. // The write guard must be released after publishing the matching empty state.
...@@ -1357,15 +1368,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1357,15 +1368,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
/// Runs a full compaction on the database. This will rewrite all SST files, removing all /// Runs a full compaction on the database. This will rewrite all SST files, removing all
/// duplicate keys and separating all key ranges into unique files. /// duplicate keys and separating all key ranges into unique files.
pub fn full_compact(&self) -> Result<()> { pub fn full_compact(&self) -> Result<()> {
self.compact(&CompactConfig { self.compact(&CompactConfig::full())?;
min_merge_count: 2,
optimal_merge_count: usize::MAX,
max_merge_count: usize::MAX,
max_merge_bytes: u64::MAX,
min_merge_duplication_bytes: 0,
optimal_merge_duplication_bytes: u64::MAX,
max_merge_segment_count: usize::MAX,
})?;
Ok(()) Ok(())
} }
...@@ -1454,6 +1457,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1454,6 +1457,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
range: StaticSortedFileRange, range: StaticSortedFileRange,
size: u64, size: u64,
flags: MetaEntryFlags, flags: MetaEntryFlags,
entry_count: u32,
tombstone_count: u32,
} }
impl Compactable for SstWithRange { impl Compactable for SstWithRange {
...@@ -1465,10 +1470,20 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1465,10 +1470,20 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
self.size self.size
} }
fn category(&self) -> u8 { fn is_bottom(&self) -> bool {
// Cold and non-cold files are placed separately so we pass different category self.flags.bottom()
// values to ensure they are not merged together. }
if self.flags.cold() { 1 } else { 0 }
fn is_fresh(&self) -> bool {
self.flags.fresh()
}
fn entry_count(&self) -> u64 {
self.entry_count.into()
}
fn tombstone_count(&self) -> u64 {
self.tombstone_count.into()
} }
} }
...@@ -1495,6 +1510,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1495,6 +1510,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
range: meta.range(index_in_meta as u32), range: meta.range(index_in_meta as u32),
size: entry.size(), size: entry.size(),
flags: entry.flags(), flags: entry.flags(),
entry_count: entry.entry_count(),
tombstone_count: entry.tombstone_count(),
}) })
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
...@@ -1513,18 +1530,22 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1513,18 +1530,22 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
keys_written: u64, keys_written: u64,
} }
let mut compact_config = compact_config.clone(); let shard_bits = shard_bits(&self.config, meta_files_by_family);
let planned = plan_compaction(
&sst_by_family
.iter()
.zip(shard_bits)
.map(|(ssts, shard_bits)| (&ssts[..], shard_bits))
.collect::<Vec<_>>(),
compact_config,
);
let merge_jobs = sst_by_family let merge_jobs = sst_by_family
.into_iter() .into_iter()
.zip(planned)
.zip(shard_bits)
.enumerate() .enumerate()
.filter_map(|(family, ssts_with_ranges)| { .map(|(family, ((ssts_with_ranges, merge_jobs), shard_bits))| {
if compact_config.max_merge_segment_count == 0 { (family, ssts_with_ranges, merge_jobs, shard_bits)
return None;
}
let (merge_jobs, real_merge_job_size) =
get_merge_segments(&ssts_with_ranges, &compact_config);
compact_config.max_merge_segment_count -= real_merge_job_size;
Some((family, ssts_with_ranges, merge_jobs))
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
...@@ -1532,7 +1553,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1532,7 +1553,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
.parallel_scheduler .parallel_scheduler
.parallel_map_collect_owned::<_, _, Result<Vec<_>>>( .parallel_map_collect_owned::<_, _, Result<Vec<_>>>(
merge_jobs, merge_jobs,
|(family, ssts_with_ranges, merge_jobs)| { |(family, ssts_with_ranges, merge_jobs, shard_bits)| {
let meta_files = &meta_files_by_family[family]; let meta_files = &meta_files_by_family[family];
let family = family as u32; let family = family as u32;
debug_assert!( debug_assert!(
...@@ -1549,49 +1570,30 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1549,49 +1570,30 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
keys_written: 0, keys_written: 0,
}); });
} }
let sst_strictly_in_shard = |index: usize| {
let sst = &ssts_with_ranges[index];
let range = meta_files[sst.meta_index].hash_range(sst.index_in_meta);
shard_bits.shard_of(range.min_hash) == shard_bits.shard_of(range.max_hash)
};
// Deserialize and merge used key hash filters per-family into // The keys read recently: the used keys of the meta files written by commits
// a single filter. This avoids O(entries × N) filter probes // that are still alive, i.e. whose SST files were not all merged yet. We only
// during the merge loop. Empty filters (from commits with no // capture this for bottom compactions.
// reads) are discarded. let used_key_hashes = if merge_jobs.iter().any(|job| {
let used_key_hashes: Option<qfilter::Filter> = { job.bottom
let filters: Vec<qfilter::FilterRef<'_>> = meta_files && (job.members.len() > 1 || !sst_strictly_in_shard(job.members[0]))
.iter() }) {
.filter_map(|meta_file| { union_used_key_hashes(meta_files)?
meta_file.deserialize_used_key_hashes_amqf().transpose() } else {
}) None
.collect::<Result<Vec<_>>>()?
.into_iter()
.filter(|amqf| !amqf.is_empty())
.collect();
if filters.is_empty() {
None
} else if filters.len() == 1 {
// Just directly use the single item
Some(filters[0].to_owned())
} else {
let total_len: u64 = filters.iter().map(|f| f.len()).sum();
// Fingerprint size must match the source filters to
// enable the efficient sorted merge path in qfilter.
let mut merged =
qfilter::Filter::with_fingerprint_size(total_len, u64::BITS as u8)
.expect("Failed to create merged AMQF filter");
for filter in &filters {
merged
.merge(false, filter)
.expect("Failed to merge AMQF filters");
}
merged.shrink_to_fit();
Some(merged)
}
}; };
// Later we will remove the merged files. Capture each one's size now (we know // Later we will remove the merged files. Capture each one's size now (we know
// exactly which SST it is) so `commit` can report deleted bytes without a scan. // exactly which SST it is) so `commit` can report deleted bytes without a scan.
let sst_files_to_delete = merge_jobs let sst_files_to_delete = merge_jobs
.iter() .iter()
.filter(|l| l.len() > 1) .filter(|job| job.members.len() > 1)
.flat_map(|l| l.iter().copied()) .flat_map(|job| job.members.iter().copied())
.map(|index| DeletedFile { .map(|index| DeletedFile {
seq: ssts_with_ranges[index].seq, seq: ssts_with_ranges[index].seq,
size: ssts_with_ranges[index].size, size: ssts_with_ranges[index].size,
...@@ -1608,7 +1610,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1608,7 +1610,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
new_sst_files: Vec<(u32, File, StaticSortedFileBuilderMeta<'static>)>, new_sst_files: Vec<(u32, File, StaticSortedFileBuilderMeta<'static>)>,
blob_seq_numbers_to_delete: Vec<u32>, blob_seq_numbers_to_delete: Vec<u32>,
keys_written: u64, keys_written: u64,
indices: SmallVec<[usize; 1]>, indices: Vec<usize>,
}, },
Move { Move {
seq: u32, seq: u32,
...@@ -1617,11 +1619,24 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1617,11 +1619,24 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
} }
let merge_result = self let merge_result = self
.parallel_scheduler .parallel_scheduler
.parallel_map_collect_owned::<_, _, Result<Vec<_>>>(merge_jobs, |indices| { .parallel_map_collect_owned::<_, _, Result<Vec<_>>>(merge_jobs, |job| {
let _span = span.clone().entered(); let _span = span.clone().entered();
let MergeJob {
members: indices,
bottom,
} = job;
let output_flags = if bottom {
MetaEntryFlags::COLD_BOTTOM
} else {
MetaEntryFlags::COMPACTED
};
if indices.len() == 1 { // Only a shard's first bottom merge has a single file (an intermediate
// If we only have one file, we can just move it // merge takes at least two). If the file doesn't span a shard boundary,
// it can become the bottom run as is. One that does (written before
// the shard count grew) is rewritten, which splits it.
if indices.len() == 1 && sst_strictly_in_shard(indices[0]) {
debug_assert!(bottom, "a single file merge must be a bottom merge");
let index = indices[0]; let index = indices[0];
let meta_index = ssts_with_ranges[index].meta_index; let meta_index = ssts_with_ranges[index].meta_index;
let index_in_meta = ssts_with_ranges[index].index_in_meta; let index_in_meta = ssts_with_ranges[index].index_in_meta;
...@@ -1635,8 +1650,9 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1635,8 +1650,9 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
amqf, amqf,
block_count: entry.block_count(), block_count: entry.block_count(),
size: entry.size(), size: entry.size(),
flags: entry.flags(), flags: output_flags,
entries: 0, entries: entry.entry_count().into(),
tombstones: entry.tombstone_count().into(),
}; };
return Ok(PartialMergeResult::Move { return Ok(PartialMergeResult::Move {
seq: entry.sequence_number(), seq: entry.sequence_number(),
...@@ -1704,10 +1720,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1704,10 +1720,8 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
struct Collector { struct Collector {
/// The active writer and its sequence number. `None` if no /// The active writer and its sequence number. `None` if no
/// entries have been added since the last flush. We defer /// entries have been added since the last flush. We defer
/// allocation to avoid creating empty SST files for collectors /// allocation to avoid creating empty SST files when a merge
/// that receive no entries (e.g., the unused_collector when /// produces no entries (e.g. when everything was deleted).
/// all keys are in the
/// used set).
writer: Option<(u32, StreamingSstWriter<LookupEntry>)>, writer: Option<(u32, StreamingSstWriter<LookupEntry>)>,
flags: MetaEntryFlags, flags: MetaEntryFlags,
compression: Compression, compression: Compression,
...@@ -1716,15 +1730,23 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1716,15 +1730,23 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
/// Hash of the last key added. Used to ensure we only split /// Hash of the last key added. Used to ensure we only split
/// SST files at key boundaries (not mid-key-group for MultiValue). /// SST files at key boundaries (not mid-key-group for MultiValue).
last_hash: Option<u64>, last_hash: Option<u64>,
/// The shards of the family. SST files are split at shard
/// boundaries.
shard_bits: ShardBits,
} }
impl Collector { impl Collector {
fn new(flags: MetaEntryFlags, compression: Compression) -> Self { fn new(
flags: MetaEntryFlags,
compression: Compression,
shard_bits: ShardBits,
) -> Self {
Self { Self {
writer: None, writer: None,
flags, flags,
compression, compression,
new_sst_files: Vec::new(), new_sst_files: Vec::new(),
last_hash: None, last_hash: None,
shard_bits,
} }
} }
...@@ -1781,15 +1803,30 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1781,15 +1803,30 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
sequence_number: &AtomicU32, sequence_number: &AtomicU32,
keys_written: &mut u64, keys_written: &mut u64,
) -> Result<()> { ) -> Result<()> {
let key_changed = self.last_hash != Some(entry.hash); let (key_changed, shard_changed) =
if let Some(last) = self.last_hash {
if last == entry.hash {
(false, false)
} else {
(
true,
self.shard_bits.shard_of(last)
!= self.shard_bits.shard_of(entry.hash),
)
}
} else {
(false, false)
};
// Only check fullness at key boundaries to avoid splitting // Only check fullness at key boundaries to avoid splitting
// a key group across two SST files. // a key group across two SST files.
if key_changed if key_changed
&& let Some((_, ref writer)) = self.writer && let Some((_, ref writer)) = self.writer
&& writer.is_full( && (shard_changed
MAX_ENTRIES_PER_COMPACTED_FILE, || writer.is_full(
DATA_THRESHOLD_PER_COMPACTED_FILE, MAX_ENTRIES_PER_COMPACTED_FILE,
) DATA_THRESHOLD_PER_COMPACTED_FILE,
))
{ {
self.close_sst_file(keys_written)?; self.close_sst_file(keys_written)?;
} }
...@@ -1815,10 +1852,18 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1815,10 +1852,18 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
} }
let compression = let compression =
self.config.family_configs[family as usize].compression; self.config.family_configs[family as usize].compression;
let mut used_collector = let mut collector =
Collector::new(MetaEntryFlags::WARM, compression); Collector::new(output_flags, compression, shard_bits);
let mut unused_collector = // A bottom merge writes the entries of recently read keys into separate
Collector::new(MetaEntryFlags::COLD, compression); // hot files, so that reading them again touches fewer blocks.
let mut hot_collector =
(bottom && used_key_hashes.is_some()).then(|| {
Collector::new(
MetaEntryFlags::HOT_BOTTOM,
compression,
shard_bits,
)
});
let mut current_key: Option<RcBytes> = None; let mut current_key: Option<RcBytes> = None;
let mut keys_written = 0; let mut keys_written = 0;
...@@ -1868,15 +1913,6 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1868,15 +1913,6 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
continue; continue;
} }
if !skip_remaining_for_this_key { if !skip_remaining_for_this_key {
let is_used =
used_key_hashes.as_ref().is_some_and(|amqf| {
amqf.contains_fingerprint(entry.hash)
});
let collector = if is_used {
&mut used_collector
} else {
&mut unused_collector
};
match family_config.kind { match family_config.kind {
FamilyKind::MultiValue => { FamilyKind::MultiValue => {
// For MultiValue families we only skip remaining // For MultiValue families we only skip remaining
...@@ -1899,6 +1935,20 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1899,6 +1935,20 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
{ {
continue; continue;
} }
let collector = if let Some(hot_collector) =
&mut hot_collector
&& used_key_hashes
.as_ref()
.expect(
"if we have a hot collector used key hashes \
must be computed",
)
.contains_fingerprint(entry.hash)
{
hot_collector
} else {
&mut collector
};
collector.add_entry( collector.add_entry(
entry, entry,
path, path,
...@@ -1915,12 +1965,13 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1915,12 +1965,13 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
} }
} }
// Close remaining writers // Close the remaining writers
used_collector.close_sst_file(&mut keys_written)?; collector.close_sst_file(&mut keys_written)?;
unused_collector.close_sst_file(&mut keys_written)?; let mut new_sst_files = take(&mut collector.new_sst_files);
if let Some(hot_collector) = &mut hot_collector {
let mut new_sst_files = take(&mut unused_collector.new_sst_files); hot_collector.close_sst_file(&mut keys_written)?;
new_sst_files.append(&mut used_collector.new_sst_files); new_sst_files.append(&mut hot_collector.new_sst_files);
}
Ok(PartialMergeResult::Merged { Ok(PartialMergeResult::Merged {
new_sst_files, new_sst_files,
blob_seq_numbers_to_delete, blob_seq_numbers_to_delete,
...@@ -1929,8 +1980,10 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1929,8 +1980,10 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
}) })
})(); })();
if result.is_err() { if result.is_err() {
used_collector.cancel(); collector.cancel();
unused_collector.cancel(); if let Some(hot_collector) = &mut hot_collector {
hot_collector.cancel();
}
} }
result result
}) })
...@@ -1965,6 +2018,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -1965,6 +2018,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
let mut meta_file_builder = MetaFileBuilder::new( let mut meta_file_builder = MetaFileBuilder::new(
family, family,
self.config.family_configs[family as usize].compression, self.config.family_configs[family as usize].compression,
shard_bits,
); );
let mut keys_written = 0; let mut keys_written = 0;
...@@ -2036,9 +2090,6 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -2036,9 +2090,6 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
for f in sst_files_to_delete.iter() { for f in sst_files_to_delete.iter() {
meta_file_builder.add_obsolete_sst_file(f.seq); meta_file_builder.add_obsolete_sst_file(f.seq);
} }
// Do not copy `used_key_hashes` into the new meta file. Those marks must expire
// as their source meta files are retired; persisting the merged filter here
// would make keys that were used once stay marked as used forever.
let new_meta_file = { let new_meta_file = {
let _span = tracing::trace_span!("write meta file").entered(); let _span = tracing::trace_span!("write meta file").entered();
...@@ -2165,18 +2216,29 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -2165,18 +2216,29 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
.all(|meta| meta.family() as usize == family), .all(|meta| meta.family() as usize == family),
"meta file stored in the wrong family shard while querying family {family}" "meta file stored in the wrong family shard while querying family {family}"
); );
for meta in inner.meta_files_by_family[family].iter().rev() { // Only the SST files of the key's shard can contain it, newest first.
match meta.lookup::<K, FIND_ALL>( let meta_files = &inner.meta_files_by_family[family];
family as u32, let shard_files = inner.shard_indices[family].candidates(hash);
hash, for (
key, range,
key_block_cache, &MetaEntryIndex {
value_block_cache, meta_index,
)? { entry_index,
MetaLookupResult::FamilyMiss => { },
#[cfg(feature = "stats")] ) in shard_files.ranges.iter().zip(&shard_files.locations)
self.stats.miss_family.fetch_add(1, Ordering::Relaxed); {
} let result = if range.contains(hash) {
meta_files[meta_index as usize].lookup_entry::<K, FIND_ALL>(
entry_index,
hash,
key,
key_block_cache,
value_block_cache,
)?
} else {
MetaLookupResult::RangeMiss
};
match result {
MetaLookupResult::RangeMiss => { MetaLookupResult::RangeMiss => {
#[cfg(feature = "stats")] #[cfg(feature = "stats")]
self.stats.miss_range.fetch_add(1, Ordering::Relaxed); self.stats.miss_range.fetch_add(1, Ordering::Relaxed);
...@@ -2295,7 +2357,6 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -2295,7 +2357,6 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
) )
.entered(); .entered();
let mut cells: Vec<(u64, usize, Option<LookupValue>)> = Vec::with_capacity(keys.len()); let mut cells: Vec<(u64, usize, Option<LookupValue>)> = Vec::with_capacity(keys.len());
let mut empty_cells = keys.len();
for (index, key) in keys.iter().enumerate() { for (index, key) in keys.iter().enumerate() {
let hash = hash_key(key); let hash = hash_key(key);
cells.push((hash, index, None)); cells.push((hash, index, None));
...@@ -2310,48 +2371,42 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -2310,48 +2371,42 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
.all(|meta| meta.family() as usize == family), .all(|meta| meta.family() as usize == family),
"meta file stored in the wrong family shard while querying family {family}" "meta file stored in the wrong family shard while querying family {family}"
); );
for meta in inner.meta_files_by_family[family].iter().rev() { // Cells are sorted by hash, so the keys of each shard are contiguous. Each run of cells is
let _result = meta.batch_lookup( // only looked up in the SST files of its shard.
family as u32, let shard_index = &inner.shard_indices[family];
keys, let mut run_start = 0;
&mut cells, while run_start < cells.len() {
&mut empty_cells, let shard = shard_index.bits().shard_of(cells[run_start].0);
key_block_cache, let run_len = cells[run_start..]
value_block_cache, .partition_point(|(hash, _, _)| shard_index.bits().shard_of(*hash) == shard);
)?; let run = &mut cells[run_start..run_start + run_len];
run_start += run_len;
#[cfg(feature = "stats")] let mut empty_run_cells = run_len;
let shard_files = shard_index.shard(shard);
for (
range,
&MetaEntryIndex {
meta_index,
entry_index,
},
) in shard_files.ranges.iter().zip(&shard_files.locations)
{ {
let crate::meta_file::MetaBatchLookupResult { let _result = inner.meta_files_by_family[family][meta_index as usize]
family_miss, .batch_lookup_entry(
range_misses, entry_index,
quick_filter_misses, range,
sst_misses, keys,
hits: _, run,
} = _result; &mut empty_run_cells,
if family_miss { key_block_cache,
self.stats.miss_family.fetch_add(1, Ordering::Relaxed); value_block_cache,
} )?;
if range_misses > 0 { #[cfg(feature = "stats")]
self.stats self.record_batch_lookup_stats(_result);
.miss_range if empty_run_cells == 0 {
.fetch_add(range_misses as u64, Ordering::Relaxed); break;
}
if quick_filter_misses > 0 {
self.stats
.miss_amqf
.fetch_add(quick_filter_misses as u64, Ordering::Relaxed);
}
if sst_misses > 0 {
self.stats
.miss_key
.fetch_add(sst_misses as u64, Ordering::Relaxed);
} }
} }
if empty_cells == 0 {
break;
}
} }
let mut deleted = 0; let mut deleted = 0;
let mut not_found = 0; let mut not_found = 0;
...@@ -2405,6 +2460,31 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -2405,6 +2460,31 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
Ok(results) Ok(results)
} }
#[cfg(feature = "stats")]
fn record_batch_lookup_stats(&self, result: crate::meta_file::MetaBatchLookupResult) {
let crate::meta_file::MetaBatchLookupResult {
range_misses,
quick_filter_misses,
sst_misses,
hits: _,
} = result;
if range_misses > 0 {
self.stats
.miss_range
.fetch_add(range_misses as u64, Ordering::Relaxed);
}
if quick_filter_misses > 0 {
self.stats
.miss_amqf
.fetch_add(quick_filter_misses as u64, Ordering::Relaxed);
}
if sst_misses > 0 {
self.stats
.miss_key
.fetch_add(sst_misses as u64, Ordering::Relaxed);
}
}
/// Returns database statistics. /// Returns database statistics.
#[cfg(feature = "stats")] #[cfg(feature = "stats")]
pub fn statistics(&self) -> Statistics { pub fn statistics(&self) -> Statistics {
...@@ -2423,7 +2503,6 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -2423,7 +2503,6 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
+ self.stats.hits_small.load(Ordering::Relaxed) + self.stats.hits_small.load(Ordering::Relaxed)
+ self.stats.hits_blob.load(Ordering::Relaxed), + self.stats.hits_blob.load(Ordering::Relaxed),
misses: self.stats.miss_global.load(Ordering::Relaxed), misses: self.stats.miss_global.load(Ordering::Relaxed),
miss_family: self.stats.miss_family.load(Ordering::Relaxed),
miss_range: self.stats.miss_range.load(Ordering::Relaxed), miss_range: self.stats.miss_range.load(Ordering::Relaxed),
miss_amqf: self.stats.miss_amqf.load(Ordering::Relaxed), miss_amqf: self.stats.miss_amqf.load(Ordering::Relaxed),
miss_key: self.stats.miss_key.load(Ordering::Relaxed), miss_key: self.stats.miss_key.load(Ordering::Relaxed),
...@@ -2453,11 +2532,13 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -2453,11 +2532,13 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
amqf_size: entry.amqf_size(), amqf_size: entry.amqf_size(),
amqf_entries: amqf.len(), amqf_entries: amqf.len(),
block_count: entry.block_count(), block_count: entry.block_count(),
entry_count: entry.entry_count(),
} }
}) })
.collect(); .collect();
MetaFileInfo { MetaFileInfo {
sequence_number: meta_file.sequence_number(), sequence_number: meta_file.sequence_number(),
shard_bits: meta_file.shard_bits().get(),
family: meta_file.family(), family: meta_file.family(),
obsolete_sst_files: meta_file.obsolete_sst_files().to_vec(), obsolete_sst_files: meta_file.obsolete_sst_files().to_vec(),
entries, entries,
...@@ -2505,6 +2586,93 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> ...@@ -2505,6 +2586,93 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
} }
} }
/// The union of the used keys recorded in the meta files, or `None` if there are none.
fn union_used_key_hashes(meta_files: &[MetaFile]) -> Result<Option<qfilter::Filter>> {
let filters = meta_files
.iter()
.filter_map(|meta_file| meta_file.deserialize_used_key_hashes_amqf().transpose())
.collect::<Result<Vec<_>>>()?
.into_iter()
.filter(|amqf| !amqf.is_empty())
.collect::<Vec<_>>();
Ok(match &filters[..] {
[] => None,
[single] => Some(single.to_owned()),
_ => {
let total_len = filters.iter().map(|f| f.len()).sum::<u64>();
// The fingerprint size must match the source filters to use qfilter's sorted merge.
let mut merged = qfilter::Filter::with_fingerprint_size(total_len, u64::BITS as u8)
.context("Failed to create the merged used keys AMQF")?;
for filter in &filters {
merged
.merge(false, filter)
.context("Failed to merge used keys AMQFs")?;
}
merged.shrink_to_fit();
Some(merged)
}
})
}
/// Rebuilds the shard index of every family after the meta files changed.
fn rebuild_shard_index<const FAMILIES: usize>(
config: &DbConfig<FAMILIES>,
inner: &mut Inner<FAMILIES>,
) {
let shard_bits = shard_bits(config, &inner.meta_files_by_family);
for ((index, meta_files), shard_bits) in inner
.shard_indices
.iter_mut()
.zip(&inner.meta_files_by_family)
.zip(shard_bits)
{
*index = ShardIndex::build(shard_bits, meta_files.iter().map(MetaFile::hash_ranges));
}
}
/// The number of key hash shards of each family (see [`crate::shard`]). It starts at
/// `FamilyConfig::initial_shard_bits`, is recorded in every meta file, and follows the size of the
/// bottom runs, which is about the size of the live data after compaction (see
/// [`ShardBits::maybe_reshard`]). Before the first bottom merge, it follows the size of all files,
/// so that the first bottom merges already split at a fitting shard count.
fn shard_bits<const FAMILIES: usize>(
config: &DbConfig<FAMILIES>,
meta_files_by_family: &[Vec<MetaFile>; FAMILIES],
) -> [ShardBits; FAMILIES] {
std::array::from_fn(|family| {
let meta_files = &meta_files_by_family[family];
let Some(newest) = meta_files.last() else {
return config.family_configs[family].initial_shard_bits;
};
let current = newest.shard_bits();
// Estimate the size of the family from the shards that have a bottom run: while the rewrite
// quota spreads the bottom merges over multiple compactions, other shards don't have one
// yet.
let mut bottom_bytes = 0u64;
let mut all_bytes = 0u64;
let mut covered_shards = FxHashSet::default();
for (entry, range) in meta_files
.iter()
.flat_map(|meta| meta.entries().iter().zip(meta.hash_ranges()))
{
all_bytes = all_bytes.saturating_add(entry.size());
if entry.flags().bottom() {
bottom_bytes = bottom_bytes.saturating_add(entry.size());
covered_shards
.extend(current.shard_of(range.min_hash)..=current.shard_of(range.max_hash));
}
}
// Before the first bottom merge there is no bottom run, so use the size of all files. They
// are only the first commits, so they hold little garbage.
let estimated_bytes = if covered_shards.is_empty() {
all_bytes
} else {
bottom_bytes.saturating_mul(u64::from(current.count())) / covered_shards.len() as u64
};
current.maybe_reshard(estimated_bytes, config.target_shard_size)
})
}
fn range_to_str(min: u64, max: u64) -> String { fn range_to_str(min: u64, max: u64) -> String {
use std::fmt::Write; use std::fmt::Write;
const DISPLAY_SIZE: usize = 100; const DISPLAY_SIZE: usize = 100;
...@@ -2531,6 +2699,8 @@ fn range_to_str(min: u64, max: u64) -> String { ...@@ -2531,6 +2699,8 @@ fn range_to_str(min: u64, max: u64) -> String {
pub struct MetaFileInfo { pub struct MetaFileInfo {
pub sequence_number: u32, pub sequence_number: u32,
/// The shard bits the SST files of this meta file were split with.
pub shard_bits: u8,
pub family: u32, pub family: u32,
pub obsolete_sst_files: Vec<u32>, pub obsolete_sst_files: Vec<u32>,
pub entries: Vec<MetaFileEntryInfo>, pub entries: Vec<MetaFileEntryInfo>,
...@@ -2545,4 +2715,6 @@ pub struct MetaFileEntryInfo { ...@@ -2545,4 +2715,6 @@ pub struct MetaFileEntryInfo {
pub sst_size: u64, pub sst_size: u64,
pub flags: MetaEntryFlags, pub flags: MetaEntryFlags,
pub block_count: u16, pub block_count: u16,
/// The number of entries in the SST file.
pub entry_count: u32,
} }
...@@ -21,6 +21,7 @@ mod meta_file_builder; ...@@ -21,6 +21,7 @@ mod meta_file_builder;
pub mod mmap_helper; pub mod mmap_helper;
mod parallel_scheduler; mod parallel_scheduler;
mod rc_bytes; mod rc_bytes;
pub mod shard;
mod shared_bytes; mod shared_bytes;
pub mod sst_filter; pub mod sst_filter;
pub mod static_sorted_file; pub mod static_sorted_file;
...@@ -69,6 +70,13 @@ pub struct FamilyConfig { ...@@ -69,6 +70,13 @@ pub struct FamilyConfig {
pub name: &'static str, pub name: &'static str,
pub kind: FamilyKind, pub kind: FamilyKind,
pub compression: Compression, pub compression: Compression,
/// Initial sharding factor for the family. There will be 2^ShardBits shards of each family.
///
/// The shard count follows the size of the family, see [`DbConfig::target_shard_size`].
/// This is just a hint to bootstrap the family. `0` would always work, but families with lots
/// of data would benefit from starting with many shards since this influences how initial
/// commits shard outputs.
pub initial_shard_bits: shard::ShardBits,
} }
/// Database-wide configuration with per-family storage settings. /// Database-wide configuration with per-family storage settings.
...@@ -80,6 +88,10 @@ pub struct DbConfig<const FAMILIES: usize> { ...@@ -80,6 +88,10 @@ pub struct DbConfig<const FAMILIES: usize> {
pub family_configs: [FamilyConfig; FAMILIES], pub family_configs: [FamilyConfig; FAMILIES],
/// How SST and meta files are read from disk. /// How SST and meta files are read from disk.
pub access_mode: AccessMode, pub access_mode: AccessMode,
/// The size a shard of a family should have after compaction.
///
/// This is a rough bound to avoid frequent resharding, See [`shard`] for sizing semantics.
pub target_shard_size: u64,
} }
/// Returns the default access mode for this execution environment. /// Returns the default access mode for this execution environment.
...@@ -130,8 +142,10 @@ impl<const FAMILIES: usize> DbConfig<FAMILIES> { ...@@ -130,8 +142,10 @@ impl<const FAMILIES: usize> DbConfig<FAMILIES> {
name: "unknown", name: "unknown",
kind: FamilyKind::SingleValue, kind: FamilyKind::SingleValue,
compression: Compression::Lz4, compression: Compression::Lz4,
initial_shard_bits: shard::ShardBits::new(0),
}; FAMILIES], }; FAMILIES],
access_mode: default_access_mode(), access_mode: default_access_mode(),
target_shard_size: 256 * 1024 * 1024,
} }
} }
} }
......
...@@ -14,7 +14,6 @@ use byteorder::{BE, ReadBytesExt}; ...@@ -14,7 +14,6 @@ use byteorder::{BE, ReadBytesExt};
use fs_err::File; use fs_err::File;
#[cfg(feature = "mmap")] #[cfg(feature = "mmap")]
use memmap2::{Mmap, MmapOptions}; use memmap2::{Mmap, MmapOptions};
use smallvec::SmallVec;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Ref, big_endian as be}; use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Ref, big_endian as be};
#[cfg(feature = "mmap")] #[cfg(feature = "mmap")]
...@@ -22,6 +21,7 @@ use crate::mmap_helper::advise_mmap_for_persistence; ...@@ -22,6 +21,7 @@ use crate::mmap_helper::advise_mmap_for_persistence;
use crate::{ use crate::{
AccessMode, Compression, FamilyConfig, QueryKey, AccessMode, Compression, FamilyConfig, QueryKey,
lookup_entry::LookupValue, lookup_entry::LookupValue,
shard::ShardBits,
static_sorted_file::{BlockCache, SstLookupResult, StaticSortedFile, StaticSortedFileMetaData}, static_sorted_file::{BlockCache, SstLookupResult, StaticSortedFile, StaticSortedFileMetaData},
}; };
...@@ -31,25 +31,31 @@ bitfield! { ...@@ -31,25 +31,31 @@ bitfield! {
impl Debug; impl Debug;
impl From<u32>; impl From<u32>;
/// The SST file was compacted and none of the entries have been accessed recently. /// The SST file was compacted and none of the entries have been accessed recently.
/// Only relevant for bottom files
pub cold, set_cold: 0; pub cold, set_cold: 0;
/// The SST file was freshly written and has not been compacted yet. /// The SST file was freshly written and has not been compacted yet.
pub fresh, set_fresh: 1; pub fresh, set_fresh: 1;
/// The SST file is part of the bottom run of its shard.
pub bottom, set_bottom: 2;
} }
impl MetaEntryFlags { impl MetaEntryFlags {
pub const FRESH: MetaEntryFlags = MetaEntryFlags(0b10); pub const FRESH: MetaEntryFlags = MetaEntryFlags(0b010);
pub const COLD: MetaEntryFlags = MetaEntryFlags(0b01); pub const COMPACTED: MetaEntryFlags = MetaEntryFlags(0b000);
pub const WARM: MetaEntryFlags = MetaEntryFlags(0b00); pub const COLD_BOTTOM: MetaEntryFlags = MetaEntryFlags(0b101);
pub const HOT_BOTTOM: MetaEntryFlags = MetaEntryFlags(0b100);
} }
impl Display for MetaEntryFlags { impl Display for MetaEntryFlags {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.fresh() { if self.fresh() {
f.pad_integral(true, "", "fresh") f.pad_integral(true, "", "fresh")
} else if self.cold() { } else if self.bottom() && self.cold() {
f.pad_integral(true, "", "cold") f.pad_integral(true, "", "cold bottom")
} else if self.bottom() {
f.pad_integral(true, "", "hot bottom")
} else { } else {
f.pad_integral(true, "", "warm") f.pad_integral(true, "", "compacted")
} }
} }
} }
...@@ -69,6 +75,8 @@ pub(crate) struct EntryHeader { ...@@ -69,6 +75,8 @@ pub(crate) struct EntryHeader {
max_hash: be::U64, max_hash: be::U64,
size: be::U64, size: be::U64,
flags: be::U32, flags: be::U32,
entry_count: be::U32,
tombstone_count: be::U32,
amqf_end_offset: be::U32, amqf_end_offset: be::U32,
} }
...@@ -80,6 +88,8 @@ impl EntryHeader { ...@@ -80,6 +88,8 @@ impl EntryHeader {
max_hash: u64, max_hash: u64,
size: u64, size: u64,
flags: MetaEntryFlags, flags: MetaEntryFlags,
entry_count: u32,
tombstone_count: u32,
amqf_end_offset: u32, amqf_end_offset: u32,
) -> Self { ) -> Self {
Self { Self {
...@@ -89,6 +99,8 @@ impl EntryHeader { ...@@ -89,6 +99,8 @@ impl EntryHeader {
max_hash: be::U64::new(max_hash), max_hash: be::U64::new(max_hash),
size: be::U64::new(size), size: be::U64::new(size),
flags: be::U32::new(flags.0), flags: be::U32::new(flags.0),
entry_count: be::U32::new(entry_count),
tombstone_count: be::U32::new(tombstone_count),
amqf_end_offset: be::U32::new(amqf_end_offset), amqf_end_offset: be::U32::new(amqf_end_offset),
} }
} }
...@@ -110,6 +122,10 @@ pub struct MetaEntry { ...@@ -110,6 +122,10 @@ pub struct MetaEntry {
size: u64, size: u64,
/// The status flags for this entry. /// The status flags for this entry.
flags: MetaEntryFlags, flags: MetaEntryFlags,
/// The number of entries in the SST file.
entry_count: u32,
/// The number of tombstone entries in the SST file.
tombstone_count: u32,
/// Byte offset range of the raw AMQF data within the backing, used for carrying forward /// Byte offset range of the raw AMQF data within the backing, used for carrying forward
/// serialized bytes during compaction without re-serializing. /// serialized bytes during compaction without re-serializing.
amqf_data_offset: std::ops::Range<u32>, amqf_data_offset: std::ops::Range<u32>,
...@@ -141,6 +157,16 @@ impl MetaEntry { ...@@ -141,6 +157,16 @@ impl MetaEntry {
self.flags self.flags
} }
/// The number of entries in the SST file.
pub fn entry_count(&self) -> u32 {
self.entry_count
}
/// The number of tombstone entries (`KeyDeleted` and `KeyValueDeleted`) in the SST file.
pub fn tombstone_count(&self) -> u32 {
self.tombstone_count
}
pub fn amqf_size(&self) -> u32 { pub fn amqf_size(&self) -> u32 {
self.amqf_data_offset.end - self.amqf_data_offset.start self.amqf_data_offset.end - self.amqf_data_offset.start
} }
...@@ -184,8 +210,6 @@ impl MetaEntry { ...@@ -184,8 +210,6 @@ impl MetaEntry {
/// The result of a lookup operation. /// The result of a lookup operation.
pub enum MetaLookupResult { pub enum MetaLookupResult {
/// The key was not found because it is from a different key family.
FamilyMiss,
/// The key was not found because it is out of the range of this SST file. But it was the /// The key was not found because it is out of the range of this SST file. But it was the
/// correct key family. /// correct key family.
RangeMiss, RangeMiss,
...@@ -198,9 +222,6 @@ pub enum MetaLookupResult { ...@@ -198,9 +222,6 @@ pub enum MetaLookupResult {
/// The result of a batch lookup operation. /// The result of a batch lookup operation.
#[derive(Default)] #[derive(Default)]
pub struct MetaBatchLookupResult { pub struct MetaBatchLookupResult {
/// The key was not found because it is from a different key family.
#[cfg(feature = "stats")]
pub family_miss: bool,
/// The key was not found because it is out of the range of this SST file. But it was the /// The key was not found because it is out of the range of this SST file. But it was the
/// correct key family. /// correct key family.
#[cfg(feature = "stats")] #[cfg(feature = "stats")]
...@@ -280,6 +301,8 @@ pub struct MetaFile { ...@@ -280,6 +301,8 @@ pub struct MetaFile {
/// Byte offset within the backing where the AMQF data region starts. /// Byte offset within the backing where the AMQF data region starts.
/// Entry AMQF offsets and used-keys offsets are relative to this position. /// Entry AMQF offsets and used-keys offsets are relative to this position.
amqf_data_start: u32, amqf_data_start: u32,
/// The shards the SST files of this meta file were split with.
shard_bits: ShardBits,
/// The offset of the start of the "used keys" AMQF data relative to the AMQF data region. /// The offset of the start of the "used keys" AMQF data relative to the AMQF data region.
start_of_used_keys_amqf_data_offset: u32, start_of_used_keys_amqf_data_offset: u32,
/// The offset of the end of the "used keys" AMQF data relative to the AMQF data region. /// The offset of the end of the "used keys" AMQF data relative to the AMQF data region.
...@@ -343,6 +366,9 @@ impl MetaFile { ...@@ -343,6 +366,9 @@ impl MetaFile {
value if value == Compression::Zstd3 as u8 => Compression::Zstd3, value if value == Compression::Zstd3 as u8 => Compression::Zstd3,
value => bail!("Invalid compression algorithm {value}"), value => bail!("Invalid compression algorithm {value}"),
}; };
let shard_bits = reader.read_u8()?;
let shard_bits = ShardBits::try_new(shard_bits)
.with_context(|| format!("Invalid shard bits {shard_bits}"))?;
if let Some(configs) = family_configs { if let Some(configs) = family_configs {
let configured = configs let configured = configs
.get(family as usize) .get(family as usize)
...@@ -386,6 +412,8 @@ impl MetaFile { ...@@ -386,6 +412,8 @@ impl MetaFile {
let max_hash = header.max_hash.get(); let max_hash = header.max_hash.get();
let size = header.size.get(); let size = header.size.get();
let flags = MetaEntryFlags(header.flags.get()); let flags = MetaEntryFlags(header.flags.get());
let entry_count = header.entry_count.get();
let tombstone_count = header.tombstone_count.get();
let end_of_amqf_data_offset = header.amqf_end_offset.get(); let end_of_amqf_data_offset = header.amqf_end_offset.get();
let amqf_bytes = amqf_data let amqf_bytes = amqf_data
...@@ -408,6 +436,8 @@ impl MetaFile { ...@@ -408,6 +436,8 @@ impl MetaFile {
sst_data, sst_data,
size, size,
flags, flags,
entry_count,
tombstone_count,
amqf_data_offset: start_of_amqf_data_offset..end_of_amqf_data_offset, amqf_data_offset: start_of_amqf_data_offset..end_of_amqf_data_offset,
amqf, amqf,
compression, compression,
...@@ -429,6 +459,7 @@ impl MetaFile { ...@@ -429,6 +459,7 @@ impl MetaFile {
obsolete_entries: Vec::new(), obsolete_entries: Vec::new(),
obsolete_sst_files, obsolete_sst_files,
amqf_data_start, amqf_data_start,
shard_bits,
start_of_used_keys_amqf_data_offset, start_of_used_keys_amqf_data_offset,
end_of_used_keys_amqf_data_offset, end_of_used_keys_amqf_data_offset,
access_mode, access_mode,
...@@ -452,6 +483,11 @@ impl MetaFile { ...@@ -452,6 +483,11 @@ impl MetaFile {
self.sequence_number self.sequence_number
} }
/// The shards the SST files of this meta file were split with.
pub fn shard_bits(&self) -> ShardBits {
self.shard_bits
}
pub fn family(&self) -> u32 { pub fn family(&self) -> u32 {
self.family self.family
} }
...@@ -493,6 +529,8 @@ impl MetaFile { ...@@ -493,6 +529,8 @@ impl MetaFile {
&self.backing[self.amqf_data_start as usize..] &self.backing[self.amqf_data_start as usize..]
} }
/// The hashes of the keys that were read in the session that wrote this meta file, if it was
/// written by a commit.
pub fn deserialize_used_key_hashes_amqf(&self) -> Result<Option<qfilter::FilterRef<'_>>> { pub fn deserialize_used_key_hashes_amqf(&self) -> Result<Option<qfilter::FilterRef<'_>>> {
if self.start_of_used_keys_amqf_data_offset == self.end_of_used_keys_amqf_data_offset { if self.start_of_used_keys_amqf_data_offset == self.end_of_used_keys_amqf_data_offset {
return Ok(None); return Ok(None);
...@@ -547,170 +585,113 @@ impl MetaFile { ...@@ -547,170 +585,113 @@ impl MetaFile {
&self.obsolete_sst_files &self.obsolete_sst_files
} }
/// Looks up a key in this meta file. /// Looks up a key in the SST file of the entry `entry_index`. The caller checks the hash range,
/// e.g. with [`crate::shard::ShardIndex`].
/// ///
/// If `FIND_ALL` is false, returns after finding the first match. /// If `FIND_ALL` is false, returns after finding the first match.
/// If `FIND_ALL` is true, returns all entries with the same key from all SST files /// If `FIND_ALL` is true, returns all entries with the same key in the SST file
/// (useful for keyspaces where keys are hashes and collisions are possible). /// (useful for keyspaces where keys are hashes and collisions are possible).
pub fn lookup<K: QueryKey, const FIND_ALL: bool>( pub(crate) fn lookup_entry<K: QueryKey, const FIND_ALL: bool>(
&self, &self,
key_family: u32, entry_index: u32,
key_hash: u64, key_hash: u64,
key: &K, key: &K,
key_block_cache: &BlockCache, key_block_cache: &BlockCache,
value_block_cache: &BlockCache, value_block_cache: &BlockCache,
) -> Result<MetaLookupResult> { ) -> Result<MetaLookupResult> {
if key_family != self.family { let entry = &self.entries[entry_index as usize];
return Ok(MetaLookupResult::FamilyMiss); if !entry.amqf.contains_fingerprint(key_hash) {
return Ok(MetaLookupResult::QuickFilterMiss);
} }
let mut miss_result = MetaLookupResult::RangeMiss; Ok(MetaLookupResult::SstLookup(
let mut all_results: SmallVec<[LookupValue; 1]> = SmallVec::new(); entry.sst(self)?.lookup::<K, FIND_ALL>(
for (index, range) in self.hash_ranges.iter().enumerate().rev() {
if !range.contains(key_hash) {
continue;
}
let entry = &self.entries[index];
if !entry.amqf.contains_fingerprint(key_hash) {
miss_result = MetaLookupResult::QuickFilterMiss;
continue;
}
let result = entry.sst(self)?.lookup::<K, FIND_ALL>(
key_hash, key_hash,
key, key,
key_block_cache, key_block_cache,
value_block_cache, value_block_cache,
)?; )?,
))
match result {
SstLookupResult::NotFound => {
// continue searching other sst files
}
SstLookupResult::Found(values) => {
if !FIND_ALL {
// Return immediately with the first result
return Ok(MetaLookupResult::SstLookup(SstLookupResult::Found(values)));
}
// A key tombstone stops the search across older SSTs within this meta file.
// It sorts last within a key group, so it is the last value if present.
// Key-value tombstones do not stop the search: they delete a single value,
// and older SSTs may hold others for this key.
let has_tombstone =
values.last().is_some_and(|v| *v == LookupValue::KeyDeleted);
all_results.extend(values);
if has_tombstone {
return Ok(MetaLookupResult::SstLookup(SstLookupResult::Found(
all_results,
)));
}
}
}
}
if FIND_ALL && !all_results.is_empty() {
return Ok(MetaLookupResult::SstLookup(SstLookupResult::Found(
all_results,
)));
}
Ok(miss_result)
} }
pub fn batch_lookup<K: QueryKey>( /// Looks up the keys of `cells` in the SST file of the entry `entry_index`, whose hash range is
/// `range`. Only cells without a result are looked up. `cells` must be sorted by key hash.
#[allow(clippy::too_many_arguments)]
pub(crate) fn batch_lookup_entry<K: QueryKey>(
&self, &self,
key_family: u32, entry_index: u32,
range: &StaticSortedFileRange,
keys: &[K], keys: &[K],
cells: &mut [(u64, usize, Option<LookupValue>)], cells: &mut [(u64, usize, Option<LookupValue>)],
empty_cells: &mut usize, empty_cells: &mut usize,
key_block_cache: &BlockCache, key_block_cache: &BlockCache,
value_block_cache: &BlockCache, value_block_cache: &BlockCache,
) -> Result<MetaBatchLookupResult> { ) -> Result<MetaBatchLookupResult> {
if key_family != self.family {
#[cfg(feature = "stats")]
return Ok(MetaBatchLookupResult {
family_miss: true,
..Default::default()
});
#[cfg(not(feature = "stats"))]
return Ok(MetaBatchLookupResult {});
}
debug_assert!( debug_assert!(
cells.is_sorted_by_key(|(hash, _, _)| *hash), cells.is_sorted_by_key(|(hash, _, _)| *hash),
"Cells must be sorted by key hash" "Cells must be sorted by key hash"
); );
#[allow(unused_mut, reason = "It's used when stats are enabled")] #[allow(unused_mut, reason = "It's used when stats are enabled")]
let mut lookup_result = MetaBatchLookupResult::default(); let mut lookup_result = MetaBatchLookupResult::default();
for (entry_index, range) in self.hash_ranges.iter().enumerate().rev() { let start_index = cells
let start_index = cells .binary_search_by(|(hash, _, _)| hash.cmp(&range.min_hash).then(Ordering::Greater))
.binary_search_by(|(hash, _, _)| hash.cmp(&range.min_hash).then(Ordering::Greater)) .err()
.err() .unwrap();
.unwrap(); if start_index >= cells.len() {
if start_index >= cells.len() { #[cfg(feature = "stats")]
#[cfg(feature = "stats")] {
{ lookup_result.range_misses += 1;
lookup_result.range_misses += 1; }
} return Ok(lookup_result);
}
let end_index = cells
.binary_search_by(|(hash, _, _)| hash.cmp(&range.max_hash).then(Ordering::Less))
.err()
.unwrap();
if start_index >= end_index {
#[cfg(feature = "stats")]
{
lookup_result.range_misses += 1;
}
return Ok(lookup_result);
}
let entry = &self.entries[entry_index as usize];
for (hash, index, result) in &mut cells[start_index..end_index] {
debug_assert!(range.contains(*hash), "Key hash out of range");
if result.is_some() {
continue; continue;
} }
let end_index = cells if !entry.amqf.contains_fingerprint(*hash) {
.binary_search_by(|(hash, _, _)| hash.cmp(&range.max_hash).then(Ordering::Less))
.err()
.unwrap()
.checked_sub(1);
let Some(end_index) = end_index else {
#[cfg(feature = "stats")] #[cfg(feature = "stats")]
{ {
lookup_result.range_misses += 1; lookup_result.quick_filter_misses += 1;
} }
continue; continue;
}; }
if start_index > end_index { let sst_result = entry.sst(self)?.lookup::<_, false>(
*hash,
&keys[*index],
key_block_cache,
value_block_cache,
)?;
if let SstLookupResult::Found(mut values) = sst_result {
// find_all=false guarantees exactly one result
debug_assert!(values.len() == 1);
let Some(value) = values.pop() else {
unreachable!()
};
*result = Some(value);
*empty_cells -= 1;
#[cfg(feature = "stats")] #[cfg(feature = "stats")]
{ {
lookup_result.range_misses += 1; lookup_result.hits += 1;
} }
continue; if *empty_cells == 0 {
} return Ok(lookup_result);
let entry = &self.entries[entry_index];
for (hash, index, result) in &mut cells[start_index..=end_index] {
debug_assert!(range.contains(*hash), "Key hash out of range");
if result.is_some() {
continue;
}
if !entry.amqf.contains_fingerprint(*hash) {
#[cfg(feature = "stats")]
{
lookup_result.quick_filter_misses += 1;
}
continue;
} }
let sst_result = entry.sst(self)?.lookup::<_, false>( } else {
*hash, #[cfg(feature = "stats")]
&keys[*index], {
key_block_cache, lookup_result.sst_misses += 1;
value_block_cache,
)?;
if let SstLookupResult::Found(mut values) = sst_result {
// find_all=false guarantees exactly one result
debug_assert!(values.len() == 1);
let Some(value) = values.pop() else {
unreachable!()
};
*result = Some(value);
*empty_cells -= 1;
#[cfg(feature = "stats")]
{
lookup_result.hits += 1;
}
if *empty_cells == 0 {
return Ok(lookup_result);
}
} else {
#[cfg(feature = "stats")]
{
lookup_result.sst_misses += 1;
}
} }
} }
} }
......
...@@ -12,12 +12,15 @@ use zerocopy::IntoBytes; ...@@ -12,12 +12,15 @@ use zerocopy::IntoBytes;
use crate::{ use crate::{
Compression, Compression,
meta_file::{EntryHeader, META_FILE_MAGIC}, meta_file::{EntryHeader, META_FILE_MAGIC},
shard::ShardBits,
static_sorted_file_builder::StaticSortedFileBuilderMeta, static_sorted_file_builder::StaticSortedFileBuilderMeta,
}; };
pub struct MetaFileBuilder<'a> { pub struct MetaFileBuilder<'a> {
family: u32, family: u32,
compression: Compression, compression: Compression,
/// The shards the SST files of this meta file were split with.
shard_bits: ShardBits,
/// Entries in the meta file, tuples of (sequence_number, StaticSortedFileBuilderMetaResult) /// Entries in the meta file, tuples of (sequence_number, StaticSortedFileBuilderMetaResult)
entries: Vec<(u32, StaticSortedFileBuilderMeta<'a>)>, entries: Vec<(u32, StaticSortedFileBuilderMeta<'a>)>,
/// Obsolete SST files, represented by their sequence numbers /// Obsolete SST files, represented by their sequence numbers
...@@ -27,10 +30,11 @@ pub struct MetaFileBuilder<'a> { ...@@ -27,10 +30,11 @@ pub struct MetaFileBuilder<'a> {
} }
impl<'a> MetaFileBuilder<'a> { impl<'a> MetaFileBuilder<'a> {
pub fn new(family: u32, compression: Compression) -> Self { pub fn new(family: u32, compression: Compression, shard_bits: ShardBits) -> Self {
Self { Self {
family, family,
compression, compression,
shard_bits,
entries: Vec::new(), entries: Vec::new(),
obsolete_sst_files: Vec::new(), obsolete_sst_files: Vec::new(),
used_key_hashes_amqf: None, used_key_hashes_amqf: None,
...@@ -63,6 +67,7 @@ impl<'a> MetaFileBuilder<'a> { ...@@ -63,6 +67,7 @@ impl<'a> MetaFileBuilder<'a> {
file.write_u32::<BE>(META_FILE_MAGIC)?; // Magic number file.write_u32::<BE>(META_FILE_MAGIC)?; // Magic number
file.write_u32::<BE>(self.family)?; file.write_u32::<BE>(self.family)?;
file.write_u8(self.compression as u8)?; file.write_u8(self.compression as u8)?;
file.write_u8(self.shard_bits.get())?;
self.obsolete_sst_files.sort(); self.obsolete_sst_files.sort();
file.write_u32::<BE>(self.obsolete_sst_files.len() as u32)?; file.write_u32::<BE>(self.obsolete_sst_files.len() as u32)?;
...@@ -82,6 +87,8 @@ impl<'a> MetaFileBuilder<'a> { ...@@ -82,6 +87,8 @@ impl<'a> MetaFileBuilder<'a> {
sst.max_hash, sst.max_hash,
sst.size, sst.size,
sst.flags, sst.flags,
u32::try_from(sst.entries).unwrap_or(u32::MAX),
u32::try_from(sst.tombstones).unwrap_or(u32::MAX),
amqf_offset as u32, amqf_offset as u32,
); );
file.write_all(header.as_bytes())?; file.write_all(header.as_bytes())?;
......
//! Key hash shards.
//!
//! The key space of a family is split into `2^bits` shards by the leading bits of the key hash.
//! Commits split their SST files at shard boundaries and compaction merges each shard on its own,
//! so SST files never span a shard boundary. Since shards are hash prefixes, doubling
//! the shard count splits every shard exactly in half.
use std::ops::RangeInclusive;
use crate::meta_file::StaticSortedFileRange;
/// The number of leading key hash bits that select the shard, i.e. a family has `2^bits` shards.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct ShardBits(u8);
impl ShardBits {
/// The largest supported value, i.e. 4096 shards.
pub const MAX: ShardBits = ShardBits(12);
/// Panics if `bits` exceeds [`ShardBits::MAX`].
pub const fn new(bits: u8) -> Self {
assert!(bits <= Self::MAX.0, "too many shard bits");
Self(bits)
}
/// Returns `None` if `bits` exceeds [`ShardBits::MAX`].
pub fn try_new(bits: u8) -> Option<Self> {
(bits <= Self::MAX.0).then_some(Self(bits))
}
/// The number of leading key hash bits.
pub fn get(self) -> u8 {
self.0
}
/// The number of shards.
pub fn count(self) -> u32 {
1 << self.0
}
/// Returns the shard that contains `hash`.
pub fn shard_of(self, hash: u64) -> u32 {
if self.0 == 0 {
0
} else {
(hash >> (u64::BITS - u32::from(self.0))) as u32
}
}
/// Returns the range of key hashes in the shard `index`.
pub fn range(self, index: u32) -> RangeInclusive<u64> {
debug_assert!(index < self.count());
if self.0 == 0 {
return 0..=u64::MAX;
}
let shift = u64::BITS - u32::from(self.0);
let start = u64::from(index) << shift;
let end = start | (u64::MAX >> u32::from(self.0));
start..=end
}
/// Computes the shard bits for a family with size [`bytes`], targeting a shard size and using
/// `[self]` bits already.
///
/// The shard count only doubles once shards hold more than 1.5 times `target_shard_size`, and
/// only halves once they hold less than half of it to prevent resharding around a threshold.
pub fn maybe_reshard(self, bytes: u64, target_shard_size: u64) -> Self {
let target = target_shard_size.max(1);
let shard_size = |bits: Self| bytes >> bits.0;
let mut bits = self;
// Grow while a shard would be over 1.5 * target.
while bits < Self::MAX && shard_size(bits) > target.saturating_add(target / 2) {
bits.0 += 1;
}
// Shrink while a shard would be under 0.5 * target.
while bits.0 > 0 && shard_size(bits) < target / 2 {
bits.0 -= 1;
}
bits
}
}
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub(crate) struct MetaEntryIndex {
pub meta_index: u32,
pub entry_index: u32,
}
/// The SST files that can contain the keys of a shard, newest first, which is the order lookups
/// consult them in. The hash ranges are stored densely so that a lookup scans them sequentially.
#[derive(Default)]
pub(crate) struct ShardFiles {
pub ranges: Box<[StaticSortedFileRange]>,
/// For each range, the index of the meta file and of the entry in the meta file.
pub locations: Box<[MetaEntryIndex]>,
}
/// The SST files of each shard of a family, so lookups only consult the files of the key's shard
/// instead of every file of the family.
pub(crate) struct ShardIndex {
bits: ShardBits,
shards: Box<[ShardFiles]>,
}
impl Default for ShardIndex {
fn default() -> Self {
Self {
bits: ShardBits::default(),
shards: Box::new([ShardFiles::default()]),
}
}
}
impl ShardIndex {
/// Builds the index of a family, given the hash ranges of the entries of each meta file,
/// oldest meta file first. Files that span multiple shards (written with a smaller shard
/// count) are listed in every shard they overlap.
pub(crate) fn build<'l>(
bits: ShardBits,
meta_files: impl DoubleEndedIterator<Item = &'l [StaticSortedFileRange]> + ExactSizeIterator,
) -> Self {
let mut shards = (0..bits.count())
.map(|_| (Vec::new(), Vec::new()))
.collect::<Vec<_>>();
for (meta_index, ranges) in meta_files.enumerate().rev() {
for (entry_index, range) in ranges.iter().enumerate().rev() {
let first = bits.shard_of(range.min_hash);
let last = bits.shard_of(range.max_hash);
for (ranges, locations) in &mut shards[first as usize..=last as usize] {
ranges.push(*range);
locations.push(MetaEntryIndex {
meta_index: meta_index as u32,
entry_index: entry_index as u32,
});
}
}
}
Self {
bits,
shards: shards
.into_iter()
.map(|(ranges, locations)| ShardFiles {
ranges: ranges.into_boxed_slice(),
locations: locations.into_boxed_slice(),
})
.collect(),
}
}
pub(crate) fn bits(&self) -> ShardBits {
self.bits
}
/// The SST files that can contain `hash`.
pub(crate) fn candidates(&self, hash: u64) -> &ShardFiles {
&self.shards[self.bits.shard_of(hash) as usize]
}
/// The SST files that can contain the keys of `shard`.
pub(crate) fn shard(&self, shard: u32) -> &ShardFiles {
&self.shards[shard as usize]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_shard_ranges_cover_the_key_space() {
for bits in [0, 1, 2, 3, 10] {
let bits = ShardBits::new(bits);
let mut next = 0u64;
for index in 0..bits.count() {
let range = bits.range(index);
assert_eq!(*range.start(), next);
assert_eq!(bits.shard_of(*range.start()), index);
assert_eq!(bits.shard_of(*range.end()), index);
next = range.end().wrapping_add(1);
}
assert_eq!(next, 0, "the last shard ends at u64::MAX");
}
}
#[test]
fn test_one_more_bit_splits_shards() {
let coarse = ShardBits::new(2).range(3);
let fine = [ShardBits::new(3).range(6), ShardBits::new(3).range(7)];
assert_eq!(coarse.start(), fine[0].start());
assert_eq!(fine[0].end() + 1, *fine[1].start());
assert_eq!(coarse.end(), fine[1].end());
}
#[test]
fn test_shard_index() {
let range = |shard, bits| {
let r = ShardBits::new(bits).range(shard);
StaticSortedFileRange {
min_hash: *r.start(),
max_hash: *r.end(),
}
};
// An old meta file written with 2 shards, a newer one with 4.
let old = [range(0, 1), range(1, 1)];
let new = [range(1, 2), range(2, 2), range(3, 2)];
let index = ShardIndex::build(ShardBits::new(2), [&old[..], &new[..]].into_iter());
let locations = |shard| index.shard(shard).locations.to_vec();
assert_eq!(
locations(0),
vec![MetaEntryIndex {
meta_index: 0,
entry_index: 0
}]
);
assert_eq!(
locations(1),
vec![
MetaEntryIndex {
meta_index: 1,
entry_index: 0
},
MetaEntryIndex {
meta_index: 0,
entry_index: 0
}
]
);
assert_eq!(
locations(2),
vec![
MetaEntryIndex {
meta_index: 1,
entry_index: 1
},
MetaEntryIndex {
meta_index: 0,
entry_index: 1
}
]
);
assert_eq!(
locations(3),
vec![
MetaEntryIndex {
meta_index: 1,
entry_index: 2
},
MetaEntryIndex {
meta_index: 0,
entry_index: 1
}
]
);
assert_eq!(
index.candidates(u64::MAX).locations,
index.shard(3).locations
);
for shard in 0..4 {
let files = index.shard(shard);
assert_eq!(files.ranges.len(), files.locations.len());
for (
range,
&MetaEntryIndex {
meta_index: meta,
entry_index: entry,
},
) in files.ranges.iter().zip(&files.locations)
{
let expected = [&old[..], &new[..]][meta as usize][entry as usize];
assert_eq!(range.min_hash, expected.min_hash);
}
}
}
#[test]
fn test_maybe_reshard_has_hysteresis() {
const T: u64 = 100;
let bits = |b| ShardBits::new(b);
// 2 shards of 140 each (1.4x the target) stay 2 shards, 2 of 160 become 4 of 80.
assert_eq!(bits(1).maybe_reshard(280, T), bits(1));
assert_eq!(bits(1).maybe_reshard(320, T), bits(2));
// 4 shards of 60 stay 4 shards, 4 of 40 become 2 of 80.
assert_eq!(bits(2).maybe_reshard(240, T), bits(2));
assert_eq!(bits(2).maybe_reshard(160, T), bits(1));
// Large changes take multiple steps at once.
assert_eq!(bits(0).maybe_reshard(1000, T), bits(3));
assert_eq!(bits(4).maybe_reshard(10, T), bits(0));
assert_eq!(bits(0).maybe_reshard(u64::MAX, 1), ShardBits::MAX);
// A change lands inside the band, so adjusting again is stable.
for bytes in [0, 50, 149, 151, 499, 1000, 12345] {
for start in 0..6 {
let once = bits(start).maybe_reshard(bytes, T);
assert_eq!(once.maybe_reshard(bytes, T), once, "{bytes} {start}");
}
}
}
}
...@@ -330,6 +330,8 @@ pub struct StaticSortedFileBuilderMeta<'a> { ...@@ -330,6 +330,8 @@ pub struct StaticSortedFileBuilderMeta<'a> {
pub flags: MetaEntryFlags, pub flags: MetaEntryFlags,
/// The number of entries in the SST file /// The number of entries in the SST file
pub entries: u64, pub entries: u64,
/// The number of tombstone entries (`KeyDeleted` and `KeyValueDeleted`) in the SST file.
pub tombstones: u64,
} }
/// Writes an SST file from a pre-sorted slice of entries. /// Writes an SST file from a pre-sorted slice of entries.
...@@ -609,6 +611,7 @@ pub struct StreamingSstWriter<E: Entry> { ...@@ -609,6 +611,7 @@ pub struct StreamingSstWriter<E: Entry> {
min_hash: u64, min_hash: u64,
max_hash: u64, max_hash: u64,
entry_count: u64, entry_count: u64,
tombstone_count: u64,
flags: MetaEntryFlags, flags: MetaEntryFlags,
// Fullness tracking (for compaction callers) // Fullness tracking (for compaction callers)
...@@ -678,6 +681,7 @@ impl<E: Entry> StreamingSstWriter<E> { ...@@ -678,6 +681,7 @@ impl<E: Entry> StreamingSstWriter<E> {
min_hash: u64::MAX, min_hash: u64::MAX,
max_hash: 0, max_hash: 0,
entry_count: 0, entry_count: 0,
tombstone_count: 0,
flags, flags,
total_key_size: 0, total_key_size: 0,
total_value_size: 0, total_value_size: 0,
...@@ -811,8 +815,12 @@ impl<E: Entry> StreamingSstWriter<E> { ...@@ -811,8 +815,12 @@ impl<E: Entry> StreamingSstWriter<E> {
} }
} }
EntryValue::Large { blob } => ValueRef::Blob { blob_id: blob }, EntryValue::Large { blob } => ValueRef::Blob { blob_id: blob },
EntryValue::KeyDeleted => ValueRef::KeyDeleted, EntryValue::KeyDeleted => {
self.tombstone_count += 1;
ValueRef::KeyDeleted
}
EntryValue::KeyValueDeleted { value } => { EntryValue::KeyValueDeleted { value } => {
self.tombstone_count += 1;
// Enforced by `WriteBatch::delete_value`, which rejects oversized values. // Enforced by `WriteBatch::delete_value`, which rejects oversized values.
debug_assert!(value.len() <= MAX_INLINE_VALUE_SIZE); debug_assert!(value.len() <= MAX_INLINE_VALUE_SIZE);
let mut data = [0u8; MAX_INLINE_VALUE_SIZE]; let mut data = [0u8; MAX_INLINE_VALUE_SIZE];
...@@ -1150,6 +1158,7 @@ impl<E: Entry> StreamingSstWriter<E> { ...@@ -1150,6 +1158,7 @@ impl<E: Entry> StreamingSstWriter<E> {
size: file_size, size: file_size,
flags: self.flags, flags: self.flags,
entries: self.entry_count, entries: self.entry_count,
tombstones: self.tombstone_count,
}; };
let file = file.into_inner()?; let file = file.into_inner()?;
......
...@@ -21,7 +21,6 @@ use crate::{ ...@@ -21,7 +21,6 @@ use crate::{
#[cfg(not(miri))] #[cfg(not(miri))]
use crate::{ use crate::{
constants::{MAX_MEDIUM_VALUE_SIZE, MAX_SMALL_VALUE_SIZE}, constants::{MAX_MEDIUM_VALUE_SIZE, MAX_SMALL_VALUE_SIZE},
meta_file::MetaFile,
parallel_scheduler::ParallelScheduler, parallel_scheduler::ParallelScheduler,
write_batch::WriteBatch, write_batch::WriteBatch,
}; };
...@@ -164,12 +163,14 @@ fn multi_value_config_with_mmap(mmap: bool) -> DbConfig<1> { ...@@ -164,12 +163,14 @@ fn multi_value_config_with_mmap(mmap: bool) -> DbConfig<1> {
name: "test", name: "test",
kind: FamilyKind::MultiValue, kind: FamilyKind::MultiValue,
compression: Compression::Lz4, compression: Compression::Lz4,
initial_shard_bits: crate::shard::ShardBits::new(0),
}], }],
access_mode: if mmap { access_mode: if mmap {
crate::mmap_access_mode() crate::mmap_access_mode()
} else { } else {
AccessMode::File AccessMode::File
}, },
..DbConfig::new()
} }
} }
...@@ -656,12 +657,7 @@ fn persist_changes(#[case] mmap: bool) -> Result<()> { ...@@ -656,12 +657,7 @@ fn persist_changes(#[case] mmap: bool) -> Result<()> {
{ {
let db = open_db::<1>(path, mmap)?; let db = open_db::<1>(path, mmap)?;
db.compact(&CompactConfig { db.compact(&CompactConfig::full())?;
optimal_merge_count: 4,
min_merge_duplication_bytes: 1,
optimal_merge_duplication_bytes: 1,
..Default::default()
})?;
check(&db, 1, 13)?; check(&db, 1, 13)?;
check(&db, 2, 22)?; check(&db, 2, 22)?;
...@@ -738,12 +734,7 @@ fn partial_compaction(#[case] mmap: bool) -> Result<()> { ...@@ -738,12 +734,7 @@ fn partial_compaction(#[case] mmap: bool) -> Result<()> {
{ {
let db = open_db::<1>(path, mmap)?; let db = open_db::<1>(path, mmap)?;
db.compact(&CompactConfig { db.compact(&CompactConfig::full())?;
optimal_merge_count: 4,
min_merge_duplication_bytes: 1,
optimal_merge_duplication_bytes: 1,
..Default::default()
})?;
for j in 0..i { for j in 0..i {
check(&db, j, j)?; check(&db, j, j)?;
...@@ -853,12 +844,7 @@ fn merge_file_removal(#[case] mmap: bool) -> Result<()> { ...@@ -853,12 +844,7 @@ fn merge_file_removal(#[case] mmap: bool) -> Result<()> {
{ {
let db = open_db::<1>(path, mmap)?; let db = open_db::<1>(path, mmap)?;
db.compact(&CompactConfig { db.compact(&CompactConfig::full())?;
optimal_merge_count: 4,
min_merge_duplication_bytes: 1,
optimal_merge_duplication_bytes: 1,
..Default::default()
})?;
for j in 0..32 { for j in 0..32 {
check(&db, j, expected_values[j as usize])?; check(&db, j, expected_values[j as usize])?;
...@@ -1595,10 +1581,21 @@ fn multi_value_config() -> DbConfig<1> { ...@@ -1595,10 +1581,21 @@ fn multi_value_config() -> DbConfig<1> {
name: "test", name: "test",
kind: FamilyKind::MultiValue, kind: FamilyKind::MultiValue,
compression: Compression::Lz4, compression: Compression::Lz4,
initial_shard_bits: crate::shard::ShardBits::new(0),
}; };
config config
} }
/// Only merges files above the bottom run, so a merge never includes the oldest files once a
/// bottom run exists. Tombstones then have to survive while the bottom run holds their keys.
fn intermediate_compaction_config() -> CompactConfig {
CompactConfig {
min_bottom_merge_bytes: u64::MAX,
max_files_above_bottom: 1,
..Default::default()
}
}
#[rstest] #[rstest]
#[case(true)] #[case(true)]
#[case(false)] #[case(false)]
...@@ -2368,6 +2365,8 @@ fn valued_tombstone_survives_partial_compaction() -> Result<()> { ...@@ -2368,6 +2365,8 @@ fn valued_tombstone_survives_partial_compaction() -> Result<()> {
)?; )?;
} }
db.commit_write_batch(batch)?; db.commit_write_batch(batch)?;
// Make the oldest layer the bottom run, so later merges don't include it.
db.compact(&CompactConfig::full())?;
// Newer layers so compaction has overlapping candidates to merge partially. // Newer layers so compaction has overlapping candidates to merge partially.
for v in [1u32, 2, 3] { for v in [1u32, 2, 3] {
...@@ -2390,13 +2389,7 @@ fn valued_tombstone_survives_partial_compaction() -> Result<()> { ...@@ -2390,13 +2389,7 @@ fn valued_tombstone_survives_partial_compaction() -> Result<()> {
// Compact repeatedly; whatever coverage the selector chooses, 42 must stay deleted. // Compact repeatedly; whatever coverage the selector chooses, 42 must stay deleted.
for round in 0..3 { for round in 0..3 {
db.compact(&CompactConfig { db.compact(&intermediate_compaction_config())?;
min_merge_count: 2,
optimal_merge_count: 2,
min_merge_duplication_bytes: 1,
optimal_merge_duplication_bytes: 1,
..Default::default()
})?;
for k in [0u32, KEYS / 2, KEYS - 1] { for k in [0u32, KEYS / 2, KEYS - 1] {
let results = db let results = db
.get_multiple(0, &k.to_be_bytes().to_vec().as_slice())? .get_multiple(0, &k.to_be_bytes().to_vec().as_slice())?
...@@ -2569,13 +2562,7 @@ fn compaction_reclaims_tombstones_when_no_older_sst_has_the_key() -> Result<()> ...@@ -2569,13 +2562,7 @@ fn compaction_reclaims_tombstones_when_no_older_sst_has_the_key() -> Result<()>
"tombstones should be on disk before compaction" "tombstones should be on disk before compaction"
); );
db.compact(&CompactConfig { db.compact(&CompactConfig::full())?;
min_merge_count: 2,
optimal_merge_count: 2,
min_merge_duplication_bytes: 1,
optimal_merge_duplication_bytes: 1,
..Default::default()
})?;
// No older SST holds these keys, so every tombstone is dead weight and must be gone. Assert // No older SST holds these keys, so every tombstone is dead weight and must be gone. Assert
// on the tombstone entries themselves: total file size would shrink from dropping the deleted // on the tombstone entries themselves: total file size would shrink from dropping the deleted
...@@ -2625,6 +2612,8 @@ fn compaction_keeps_tombstone_when_older_sst_has_the_key() -> Result<()> { ...@@ -2625,6 +2612,8 @@ fn compaction_keeps_tombstone_when_older_sst_has_the_key() -> Result<()> {
)?; )?;
} }
db.commit_write_batch(batch)?; db.commit_write_batch(batch)?;
// Make the oldest layer the bottom run, so later merges don't include it.
db.compact(&CompactConfig::full())?;
// Newer layers: an unrelated value per key, then a tombstone for the old one. // Newer layers: an unrelated value per key, then a tombstone for the old one.
let batch = db.write_batch()?; let batch = db.write_batch()?;
...@@ -2650,13 +2639,7 @@ fn compaction_keeps_tombstone_when_older_sst_has_the_key() -> Result<()> { ...@@ -2650,13 +2639,7 @@ fn compaction_keeps_tombstone_when_older_sst_has_the_key() -> Result<()> {
// Compact repeatedly. Whatever subset each job picks, value 1 must never come back: while an // Compact repeatedly. Whatever subset each job picks, value 1 must never come back: while an
// older SST still holds it, the probe has to keep the tombstone alive. // older SST still holds it, the probe has to keep the tombstone alive.
for round in 0..4 { for round in 0..4 {
db.compact(&CompactConfig { db.compact(&intermediate_compaction_config())?;
min_merge_count: 2,
optimal_merge_count: 2,
min_merge_duplication_bytes: 1,
optimal_merge_duplication_bytes: 1,
..Default::default()
})?;
for k in [0u32, KEYS / 2, KEYS - 1] { for k in [0u32, KEYS / 2, KEYS - 1] {
let mut results = db let mut results = db
...@@ -2714,6 +2697,8 @@ fn compaction_keeps_tombstone_when_skipped_sst_has_the_key() -> Result<()> { ...@@ -2714,6 +2697,8 @@ fn compaction_keeps_tombstone_when_skipped_sst_has_the_key() -> Result<()> {
batch.put(0, key_for(0, i), 1u32.to_be_bytes().to_vec().into())?; batch.put(0, key_for(0, i), 1u32.to_be_bytes().to_vec().into())?;
} }
db.commit_write_batch(batch)?; db.commit_write_batch(batch)?;
// Make the oldest layer the bottom run, so later merges don't include it.
db.compact(&CompactConfig::full())?;
// Several more layers touching the same keys, so the selector has many overlapping candidates. // Several more layers touching the same keys, so the selector has many overlapping candidates.
for round in 1..7u32 { for round in 1..7u32 {
...@@ -2745,14 +2730,7 @@ fn compaction_keeps_tombstone_when_skipped_sst_has_the_key() -> Result<()> { ...@@ -2745,14 +2730,7 @@ fn compaction_keeps_tombstone_when_skipped_sst_has_the_key() -> Result<()> {
} }
for round in 0..6 { for round in 0..6 {
db.compact(&CompactConfig { db.compact(&intermediate_compaction_config())?;
min_merge_count: 2,
max_merge_count: 3,
optimal_merge_count: 2,
min_merge_duplication_bytes: 1,
optimal_merge_duplication_bytes: 1,
..Default::default()
})?;
for i in [0u32, KEYS / 2, KEYS - 1] { for i in [0u32, KEYS / 2, KEYS - 1] {
let results = db let results = db
...@@ -2873,14 +2851,11 @@ fn valued_tombstone_rejects_single_value_families() -> Result<()> { ...@@ -2873,14 +2851,11 @@ fn valued_tombstone_rejects_single_value_families() -> Result<()> {
fn partial_compaction_retires_fully_consumed_meta_files(#[case] mmap: bool) -> Result<()> { fn partial_compaction_retires_fully_consumed_meta_files(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?; let tempdir = tempfile::tempdir()?;
let path = tempdir.path(); let path = tempdir.path();
let access_mode = if mmap { // Two shards, so every commit writes one SST per shard into its meta file.
crate::mmap_access_mode() let config = || two_shard_config(mmap);
} else { let db = open_db_with_config::<1>(path, config()?)?;
AccessMode::File
};
let db = open_db::<1>(path, mmap)?;
const KEYS: u32 = 2_000; const KEYS: u32 = TWO_SHARD_KEYS;
for generation in 0..4u32 { for generation in 0..4u32 {
let batch = db.write_batch()?; let batch = db.write_batch()?;
for key in 0..KEYS { for key in 0..KEYS {
...@@ -2891,10 +2866,6 @@ fn partial_compaction_retires_fully_consumed_meta_files(#[case] mmap: bool) -> R ...@@ -2891,10 +2866,6 @@ fn partial_compaction_retires_fully_consumed_meta_files(#[case] mmap: bool) -> R
)?; )?;
} }
db.commit_write_batch(batch)?; db.commit_write_batch(batch)?;
if generation == 0 {
// Flush this access into the following commit's used-key-hash AMQF.
assert!(db.get(0, &0u32.to_be_bytes())?.is_some());
}
} }
let before_meta_sequences = db let before_meta_sequences = db
.meta_info()? .meta_info()?
...@@ -2902,37 +2873,18 @@ fn partial_compaction_retires_fully_consumed_meta_files(#[case] mmap: bool) -> R ...@@ -2902,37 +2873,18 @@ fn partial_compaction_retires_fully_consumed_meta_files(#[case] mmap: bool) -> R
.map(|meta| meta.sequence_number) .map(|meta| meta.sequence_number)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
assert_eq!(before_meta_sequences.len(), 4); assert_eq!(before_meta_sequences.len(), 4);
assert!(before_meta_sequences.iter().any(|&seq| {
MetaFile::open(path, seq, None, access_mode)
.unwrap()
.deserialize_used_key_hashes_amqf()
.unwrap()
.is_some()
}));
// A single merge job merges one shard, which leaves an SST in every meta file.
let partial = CompactConfig { let partial = CompactConfig {
min_merge_count: 2, max_merge_jobs: 1,
optimal_merge_count: 2, ..CompactConfig::full()
max_merge_count: 2,
max_merge_bytes: u64::MAX,
min_merge_duplication_bytes: 0,
optimal_merge_duplication_bytes: 0,
max_merge_segment_count: 1,
}; };
assert!(db.compact(&partial)?.is_some()); assert!(db.compact(&partial)?.is_some());
let after_partial = db.meta_info()?; let after_partial = db.meta_info()?;
assert_eq!( assert_eq!(
after_partial.len(), after_partial.len(),
3, 5,
"two fully consumed meta files should retire while two untouched metas remain" "no meta file is fully consumed by merging one of two shards"
);
assert_eq!(
after_partial
.iter()
.filter(|meta| before_meta_sequences.contains(&meta.sequence_number))
.count(),
2,
"untouched SST metadata should stay in its two existing meta files"
); );
for key in 0..KEYS { for key in 0..KEYS {
assert_eq!( assert_eq!(
...@@ -2941,19 +2893,21 @@ fn partial_compaction_retires_fully_consumed_meta_files(#[case] mmap: bool) -> R ...@@ -2941,19 +2893,21 @@ fn partial_compaction_retires_fully_consumed_meta_files(#[case] mmap: bool) -> R
); );
} }
// Merging the other shard consumes the original meta files, but not the bottom run written by
// the partial compaction.
db.full_compact()?; db.full_compact()?;
let fully_compacted = db.meta_info()?; let fully_compacted = db.meta_info()?;
assert_eq!(fully_compacted.len(), 1); assert_eq!(fully_compacted.len(), 2);
let compacted_meta =
MetaFile::open(path, fully_compacted[0].sequence_number, None, access_mode)?;
assert!( assert!(
compacted_meta.deserialize_used_key_hashes_amqf()?.is_none(), fully_compacted
"used-key marks should expire instead of being copied into compaction output" .iter()
.all(|meta| !before_meta_sequences.contains(&meta.sequence_number)),
"fully consumed meta files should retire"
); );
drop(db); drop(db);
let reopened = open_db::<1>(path, mmap)?; let reopened = open_db_with_config::<1>(path, config()?)?;
assert_eq!(reopened.meta_info()?.len(), 1); assert_eq!(reopened.meta_info()?.len(), 2);
for key in 0..KEYS { for key in 0..KEYS {
assert_eq!( assert_eq!(
&*reopened.get(0, &key.to_be_bytes())?.unwrap(), &*reopened.get(0, &key.to_be_bytes())?.unwrap(),
...@@ -2962,3 +2916,369 @@ fn partial_compaction_retires_fully_consumed_meta_files(#[case] mmap: bool) -> R ...@@ -2962,3 +2916,369 @@ fn partial_compaction_retires_fully_consumed_meta_files(#[case] mmap: bool) -> R
} }
Ok(()) Ok(())
} }
/// The number of keys the tests using [`two_shard_config`] write per commit.
#[cfg(not(miri))]
const TWO_SHARD_KEYS: u32 = 2_000;
/// A config that starts with 2 shards, and a target shard size that keeps 2 shards for
/// [`TWO_SHARD_KEYS`] keys with 4 byte values: the size of one shard of them after compaction.
#[cfg(not(miri))]
fn two_shard_config(mmap: bool) -> Result<DbConfig<1>> {
let mut config = config_with_mmap::<1>(mmap);
config.family_configs[0].initial_shard_bits = crate::shard::ShardBits::new(1);
let tempdir = tempfile::tempdir()?;
let db = open_db_with_config::<1>(tempdir.path(), config.clone())?;
let batch = db.write_batch()?;
for key in 0..TWO_SHARD_KEYS {
batch.put(
0,
key.to_be_bytes().to_vec(),
0u32.to_be_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
db.full_compact()?;
let bottom_bytes = db
.meta_info()?
.into_iter()
.flat_map(|meta| meta.entries)
.filter(|entry| entry.flags.bottom())
.map(|entry| entry.sst_size)
.sum::<u64>();
config.target_shard_size = bottom_bytes / 2;
Ok(config)
}
/// Counts the entries of the family's hot and other bottom SST files.
#[cfg(not(miri))]
fn bottom_entry_counts(db: &TurboPersistence<RayonParallelScheduler, 1>) -> Result<(usize, usize)> {
let mut hot = 0;
let mut cold = 0;
for entry in db.meta_info()?.into_iter().flat_map(|meta| meta.entries) {
if !entry.flags.bottom() {
continue;
}
if entry.flags.cold() {
cold += entry.entry_count as usize;
} else {
hot += entry.entry_count as usize;
}
}
Ok((hot, cold))
}
// The compaction tests below write thousands of keys and took 4 to over 28 minutes under Miri.
// They exercise the compaction policy, not unsafe code.
#[cfg(not(miri))]
#[rstest]
#[case(true)]
#[case(false)]
fn bottom_merge_writes_read_keys_into_hot_files(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let config = || {
let mut config = config_with_mmap::<1>(mmap);
config.family_configs[0].initial_shard_bits = crate::shard::ShardBits::new(1);
config
};
const KEYS: u32 = 2_000;
const HOT: u32 = 300;
let put_all =
|db: &TurboPersistence<RayonParallelScheduler, 1>, generation: u32| -> Result<()> {
let batch = db.write_batch()?;
for key in 0..KEYS {
batch.put(
0,
key.to_be_bytes().to_vec(),
generation.to_be_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
Ok(())
};
let db = open_db_with_config::<1>(path, config())?;
put_all(&db, 0)?;
// No keys were read yet, so the first bottom merge has no hot files.
db.full_compact()?;
assert_eq!(bottom_entry_counts(&db)?, (0, KEYS as usize));
// Read some keys; the next commit records them.
for key in 0..HOT {
db.get(0, &key.to_be_bytes())?.unwrap();
}
put_all(&db, 1)?;
db.full_compact()?;
assert_eq!(
bottom_entry_counts(&db)?,
(HOT as usize, (KEYS - HOT) as usize)
);
for key in 0..KEYS {
assert_eq!(
&*db.get(0, &key.to_be_bytes())?.unwrap(),
&1u32.to_be_bytes()
);
}
db.shutdown()?;
// The full compaction merged every SST file of the commit that recorded the reads, which
// retired its meta file and the used keys with it. The reads of the keys checked above were
// never committed, so the next bottom merge writes no hot files.
let db = open_db_with_config::<1>(path, config())?;
put_all(&db, 2)?;
db.full_compact()?;
assert_eq!(bottom_entry_counts(&db)?, (0, KEYS as usize));
for key in 0..KEYS {
assert_eq!(
&*db.get(0, &key.to_be_bytes())?.unwrap(),
&2u32.to_be_bytes()
);
}
Ok(())
}
#[cfg(not(miri))]
#[rstest]
#[case(true)]
#[case(false)]
fn used_keys_live_as_long_as_the_meta_file_that_recorded_them(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let db = open_db_with_config::<1>(path, two_shard_config(mmap)?)?;
const KEYS: u32 = TWO_SHARD_KEYS;
let put_all = |generation: u32| -> Result<()> {
let batch = db.write_batch()?;
for key in 0..KEYS {
batch.put(
0,
key.to_be_bytes().to_vec(),
generation.to_be_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
Ok(())
};
put_all(0)?;
db.full_compact()?;
for key in 0..KEYS {
db.get(0, &key.to_be_bytes())?.unwrap();
}
put_all(1)?;
// Bottom merge only one of the two shards. The commit that recorded the used keys still has an
// SST file in the other shard, so its meta file and the used keys stay alive for that shard.
db.compact(&CompactConfig {
max_merge_jobs: 1,
..CompactConfig::full()
})?;
let (hot_after_first, _) = bottom_entry_counts(&db)?;
assert!(hot_after_first > 0 && hot_after_first < KEYS as usize);
db.full_compact()?;
assert_eq!(bottom_entry_counts(&db)?, (KEYS as usize, 0));
// Now every SST file of that commit was merged, so its meta file and the used keys are gone.
// Compaction didn't copy them, so the next bottom merges write no hot files.
put_all(2)?;
db.full_compact()?;
assert_eq!(bottom_entry_counts(&db)?, (0, KEYS as usize));
Ok(())
}
#[cfg(not(miri))]
#[rstest]
#[case(true)]
#[case(false)]
fn shard_count_changes_with_hysteresis(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
const KEYS: u32 = 20_000;
let commit = |db: &TurboPersistence<RayonParallelScheduler, 1>| -> Result<()> {
let batch = db.write_batch()?;
for key in 0..100u32 {
batch.put(0, key.to_be_bytes().to_vec(), vec![1; 64].into())?;
}
db.commit_write_batch(batch)?;
Ok(())
};
let newest_shard_bits = |db: &TurboPersistence<RayonParallelScheduler, 1>| -> Result<u8> {
// `meta_info` lists the newest meta file first.
Ok(db.meta_info()?.first().unwrap().shard_bits)
};
let bottom_bytes = {
let db = open_db::<1>(path, mmap)?;
let batch = db.write_batch()?;
for key in 0..KEYS {
batch.put(
0,
key.to_be_bytes().to_vec(),
key.to_le_bytes().repeat(8).into(),
)?;
}
db.commit_write_batch(batch)?;
db.full_compact()?;
db.shutdown()?;
db.meta_info()?
.into_iter()
.flat_map(|meta| meta.entries)
.filter(|entry| entry.flags.bottom())
.map(|entry| entry.sst_size)
.sum::<u64>()
};
let open_with_target = |target: f64| {
let mut config = config_with_mmap::<1>(mmap);
config.target_shard_size = (bottom_bytes as f64 / target) as u64;
open_db_with_config::<1>(path, config)
};
// The bottom run is 1.2 times the target: a plain size-based count would double, but it's
// within the band.
let db = open_with_target(1.2)?;
commit(&db)?;
assert_eq!(newest_shard_bits(&db)?, 0);
drop(db);
// 1.6 times the target doubles the shard count.
let db = open_with_target(1.6)?;
commit(&db)?;
assert_eq!(newest_shard_bits(&db)?, 1);
drop(db);
// Back at 1.2 times the target, the count is read from the meta file and stays: shards hold 0.6
// times the target.
let db = open_with_target(1.2)?;
commit(&db)?;
assert_eq!(newest_shard_bits(&db)?, 1);
drop(db);
// At 0.9 times the target, shards hold 0.45 times the target, so the count halves again.
let db = open_with_target(0.9)?;
commit(&db)?;
assert_eq!(newest_shard_bits(&db)?, 0);
for key in 0..KEYS {
assert!(db.get(0, &key.to_be_bytes())?.is_some());
}
Ok(())
}
#[cfg(not(miri))]
#[rstest]
#[case(true)]
#[case(false)]
fn initial_shard_bits_are_a_starting_value(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let mut config = config_with_mmap::<1>(mmap);
config.family_configs[0].initial_shard_bits = crate::shard::ShardBits::new(2);
let db = open_db_with_config::<1>(tempdir.path(), config)?;
let commit = || -> Result<()> {
let batch = db.write_batch()?;
for key in 0..1000u32 {
batch.put(0, key.to_be_bytes().to_vec(), vec![1; 8].into())?;
}
db.commit_write_batch(batch)?;
Ok(())
};
// `meta_info` lists the newest meta file first.
let newest_shard_bits = || -> Result<u8> { Ok(db.meta_info()?.first().unwrap().shard_bits) };
// The first commit has nothing to size the shards by, so it uses the initial count.
commit()?;
assert_eq!(newest_shard_bits()?, 2);
// Without a bottom run yet, the next commit sizes the shards by all files: the tiny family
// shrinks to a single shard, far below the initial count.
commit()?;
assert_eq!(newest_shard_bits()?, 0);
// Once compacted, the bottom run is as tiny, so the count stays.
db.full_compact()?;
commit()?;
assert_eq!(newest_shard_bits()?, 0);
for key in 0..1000u32 {
assert!(db.get(0, &key.to_be_bytes())?.is_some());
}
Ok(())
}
#[cfg(not(miri))]
#[rstest]
#[case(true)]
#[case(false)]
fn first_bottom_merges_split_at_the_size_of_all_files(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let mut config = config_with_mmap::<1>(mmap);
// Far less than the data, so the family needs several shards.
config.target_shard_size = 64 * 1024;
let db = open_db_with_config::<1>(tempdir.path(), config)?;
const KEYS: u32 = 20_000;
let batch = db.write_batch()?;
for key in 0..KEYS {
batch.put(0, key.to_be_bytes().to_vec(), vec![key as u8; 64].into())?;
}
db.commit_write_batch(batch)?;
// The commit used the initial single shard. There is no bottom run yet, so the compaction
// sizes the shards by all files and its bottom merges already split at the grown count.
db.full_compact()?;
let metas = db.meta_info()?;
// `meta_info` lists the newest meta file first.
let shard_bits = crate::shard::ShardBits::new(metas.first().unwrap().shard_bits);
assert!(shard_bits.count() > 1, "{} shards", shard_bits.count());
let bottom = metas
.iter()
.flat_map(|meta| &meta.entries)
.filter(|entry| entry.flags.bottom())
.collect::<Vec<_>>();
assert_eq!(bottom.len(), shard_bits.count() as usize);
for entry in bottom {
assert_eq!(
shard_bits.shard_of(entry.min_hash),
shard_bits.shard_of(entry.max_hash),
"a bottom file spans shards"
);
}
for key in 0..KEYS {
assert!(db.get(0, &key.to_be_bytes())?.is_some());
}
Ok(())
}
// Writes 2M keys to fill the collectors several times, which is too slow under Miri.
#[cfg(not(miri))]
#[rstest]
#[case(true)]
#[case(false)]
fn commits_with_more_shards_than_collectors_split_files_at_shard_boundaries(
#[case] mmap: bool,
) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let mut config = config_with_mmap::<1>(mmap);
// 16 shards, but at most 4 collectors in memory.
let shard_bits = crate::shard::ShardBits::new(4);
config.family_configs[0].initial_shard_bits = shard_bits;
let db = open_db_with_config::<1>(tempdir.path(), config)?;
// After the first collector fills (256K entries) and splits into 4, each fills again after
// another ~200K entries.
const KEYS: u32 = 2_000_000;
let batch = db.write_batch()?;
for key in 0..KEYS {
batch.put(
0,
key.to_be_bytes().to_vec(),
key.to_le_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
let entries = db
.meta_info()?
.into_iter()
.flat_map(|meta| meta.entries)
.collect::<Vec<_>>();
for entry in &entries {
assert_eq!(
shard_bits.shard_of(entry.min_hash),
shard_bits.shard_of(entry.max_hash),
"an SST file spans a shard boundary"
);
}
// Every shard got files, from multiple collector flushes.
assert!(entries.len() > 16, "{} files", entries.len());
for key in (0..KEYS).step_by(997) {
assert_eq!(
&*db.get(0, &key.to_be_bytes())?.unwrap(),
&key.to_le_bytes()
);
}
Ok(())
}
...@@ -25,6 +25,7 @@ use crate::{ ...@@ -25,6 +25,7 @@ use crate::{
meta_file::MetaEntryFlags, meta_file::MetaEntryFlags,
meta_file_builder::MetaFileBuilder, meta_file_builder::MetaFileBuilder,
parallel_scheduler::ParallelScheduler, parallel_scheduler::ParallelScheduler,
shard::ShardBits,
static_sorted_file_builder::{StaticSortedFileBuilderMeta, write_static_stored_file}, static_sorted_file_builder::{StaticSortedFileBuilderMeta, write_static_stored_file},
}; };
...@@ -49,10 +50,6 @@ struct ThreadLocalState<K: StoreKey + Send, const FAMILIES: usize> { ...@@ -49,10 +50,6 @@ struct ThreadLocalState<K: StoreKey + Send, const FAMILIES: usize> {
new_blob_files: Vec<NewFile>, new_blob_files: Vec<NewFile>,
} }
const COLLECTOR_SHARDS: usize = 4;
const COLLECTOR_SHARD_SHIFT: usize =
u64::BITS as usize - COLLECTOR_SHARDS.trailing_zeros() as usize;
/// The result of a `WriteBatch::finish` operation. /// The result of a `WriteBatch::finish` operation.
pub(crate) struct FinishResult { pub(crate) struct FinishResult {
pub(crate) sequence_number: u32, pub(crate) sequence_number: u32,
...@@ -63,12 +60,17 @@ pub(crate) struct FinishResult { ...@@ -63,12 +60,17 @@ pub(crate) struct FinishResult {
pub(crate) keys_written: u64, pub(crate) keys_written: u64,
} }
/// The most leading key hash bits that split a family's entries into collectors in memory as part
/// of a commit.
const MAX_COLLECTOR_SHARD_BITS: ShardBits = ShardBits::new(2);
enum GlobalCollectorState<K: StoreKey + Send> { enum GlobalCollectorState<K: StoreKey + Send> {
/// Initial state. Single collector. Once the collector is full, we switch to sharded mode. /// Initial state. Single collector. Once the collector is full, we switch to sharded mode. When
/// written, its entries are split into one SST file per shard.
Unsharded(Collector<K>), Unsharded(Collector<K>),
/// Sharded mode. /// Sharded mode. One collector per key hash prefix of the given bits (see
/// We use multiple collectors, and select one based on the first bits of the key hash. /// [`WriteBatch::collector_bits`]).
Sharded([Collector<K>; COLLECTOR_SHARDS]), Sharded(ShardBits, Box<[Collector<K>]>),
} }
/// A write batch. /// A write batch.
...@@ -82,6 +84,8 @@ pub struct WriteBatch<'db, K: StoreKey + Send, S: ParallelScheduler, const FAMIL ...@@ -82,6 +84,8 @@ pub struct WriteBatch<'db, K: StoreKey + Send, S: ParallelScheduler, const FAMIL
/// Per-family storage configuration. /// Per-family storage configuration.
#[cfg_attr(not(feature = "verify_sst_content"), allow(dead_code))] #[cfg_attr(not(feature = "verify_sst_content"), allow(dead_code))]
family_configs: [FamilyConfig; FAMILIES], family_configs: [FamilyConfig; FAMILIES],
/// The shards of each family. SST files are split at shard boundaries.
shard_bits: [ShardBits; FAMILIES],
/// The current sequence number counter. Increased for every new SST file or blob file. /// The current sequence number counter. Increased for every new SST file or blob file.
current_sequence_number: AtomicU32, current_sequence_number: AtomicU32,
/// The thread local state. /// The thread local state.
...@@ -104,6 +108,7 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize ...@@ -104,6 +108,7 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize
current: u32, current: u32,
parallel_scheduler: S, parallel_scheduler: S,
family_configs: [FamilyConfig; FAMILIES], family_configs: [FamilyConfig; FAMILIES],
shard_bits: [ShardBits; FAMILIES],
) -> Self { ) -> Self {
const { const {
assert!(FAMILIES <= usize_from_u32(u32::MAX)); assert!(FAMILIES <= usize_from_u32(u32::MAX));
...@@ -113,6 +118,7 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize ...@@ -113,6 +118,7 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize
parallel_scheduler, parallel_scheduler,
db_path: path, db_path: path,
family_configs, family_configs,
shard_bits,
current_sequence_number: AtomicU32::new(current), current_sequence_number: AtomicU32::new(current),
thread_locals: ThreadLocal::new(), thread_locals: ThreadLocal::new(),
collectors: [(); FAMILIES] collectors: [(); FAMILIES]
...@@ -172,26 +178,34 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize ...@@ -172,26 +178,34 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize
GlobalCollectorState::Unsharded(collector) => { GlobalCollectorState::Unsharded(collector) => {
collector.add_entry(entry); collector.add_entry(entry);
if collector.is_full() { if collector.is_full() {
// When full, split the entries into shards. let collector_bits = self.collector_bits(family);
let mut shards: [Collector<K>; 4] = if collector_bits.count() == 1 {
[(); COLLECTOR_SHARDS].map(|_| Collector::new()); full_collectors.push(replace(collector, Collector::new()));
for entry in collector.drain() { } else {
let shard = (entry.key.hash >> COLLECTOR_SHARD_SHIFT) as usize; // When full, split the entries by key hash prefix.
shards[shard].add_entry(entry); let mut shards = (0..collector_bits.count())
} .map(|_| Collector::new())
// There is a rare edge case where all entries are in the same shard, .collect::<Box<[_]>>();
// and the collector is full after the split. for entry in collector.drain() {
for collector in shards.iter_mut() { let shard = collector_bits.shard_of(entry.key.hash) as usize;
if collector.is_full() { shards[shard].add_entry(entry);
full_collectors
.push(replace(&mut *collector, Collector::new()));
} }
// There is a rare edge case where all entries are in the same
// shard, and the collector is full
// after the split.
for collector in shards.iter_mut() {
if collector.is_full() {
full_collectors
.push(replace(&mut *collector, Collector::new()));
}
}
*global_collector_state =
GlobalCollectorState::Sharded(collector_bits, shards);
} }
*global_collector_state = GlobalCollectorState::Sharded(shards);
} }
} }
GlobalCollectorState::Sharded(shards) => { GlobalCollectorState::Sharded(collector_bits, shards) => {
let shard = (entry.key.hash >> COLLECTOR_SHARD_SHIFT) as usize; let shard = collector_bits.shard_of(entry.key.hash) as usize;
let collector = &mut shards[shard]; let collector = &mut shards[shard];
collector.add_entry(entry); collector.add_entry(entry);
if collector.is_full() { if collector.is_full() {
...@@ -220,12 +234,12 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize ...@@ -220,12 +234,12 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize
// these operations async, or we could integrate with the parallel::map operation that is // these operations async, or we could integrate with the parallel::map operation that is
// driving the work to slow down task submission in this case. // driving the work to slow down task submission in this case.
for mut global_collector in full_collectors { for mut global_collector in full_collectors {
// When the global collector is full, we create a new SST file. // When the global collector is full, we create new SST files, one per shard.
let sst = self.create_sst_file( let ssts = self.create_sst_files(
family, family,
global_collector.sorted(self.family_configs[usize_from_u32(family)].kind), global_collector.sorted(self.family_configs[usize_from_u32(family)].kind),
)?; )?;
self.new_sst_files.lock().push(sst); self.new_sst_files.lock().extend(ssts);
drop(global_collector); drop(global_collector);
} }
Ok(()) Ok(())
...@@ -324,13 +338,16 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize ...@@ -324,13 +338,16 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize
match &mut *collector_state { match &mut *collector_state {
GlobalCollectorState::Unsharded(collector) => { GlobalCollectorState::Unsharded(collector) => {
if !collector.is_empty() { if !collector.is_empty() {
let sst = self.create_sst_file(family, collector.sorted(family_config.kind))?; // A collector that never filled up was never split into shards, so its
// entries can span all shards.
let ssts =
self.create_sst_files(family, collector.sorted(family_config.kind))?;
collector.clear(); collector.clear();
self.new_sst_files.lock().push(sst); self.new_sst_files.lock().extend(ssts);
} }
} }
GlobalCollectorState::Sharded(_) => { GlobalCollectorState::Sharded(..) => {
let GlobalCollectorState::Sharded(mut shards) = replace( let GlobalCollectorState::Sharded(_, mut shards) = replace(
&mut *collector_state, &mut *collector_state,
GlobalCollectorState::Unsharded(Collector::new()), GlobalCollectorState::Unsharded(Collector::new()),
) else { ) else {
...@@ -339,11 +356,10 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize ...@@ -339,11 +356,10 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize
self.parallel_scheduler self.parallel_scheduler
.try_parallel_for_each_mut(&mut shards, |collector| { .try_parallel_for_each_mut(&mut shards, |collector| {
if !collector.is_empty() { if !collector.is_empty() {
let sst = let ssts = self
self.create_sst_file(family, collector.sorted(family_config.kind))?; .create_sst_files(family, collector.sorted(family_config.kind))?;
collector.clear(); collector.clear_and_drop_capacity();
self.new_sst_files.lock().push(sst); self.new_sst_files.lock().extend(ssts);
collector.drop_contents();
} }
anyhow::Ok(()) anyhow::Ok(())
})?; })?;
...@@ -414,7 +430,7 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize ...@@ -414,7 +430,7 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize
GlobalCollectorState::Unsharded(collector) => { GlobalCollectorState::Unsharded(collector) => {
Either::Left([(family, collector)].into_iter()) Either::Left([(family, collector)].into_iter())
} }
GlobalCollectorState::Sharded(shards) => { GlobalCollectorState::Sharded(_, shards) => {
Either::Right(shards.into_iter().map(move |collector| (family, collector))) Either::Right(shards.into_iter().map(move |collector| (family, collector)))
} }
} }
...@@ -425,13 +441,13 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize ...@@ -425,13 +441,13 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize
|(family, mut collector)| { |(family, mut collector)| {
let family = family as u32; let family = family as u32;
if !collector.is_empty() { if !collector.is_empty() {
let sst = self.create_sst_file( let ssts = self.create_sst_files(
family, family,
collector.sorted(self.family_configs[usize_from_u32(family)].kind), collector.sorted(self.family_configs[usize_from_u32(family)].kind),
)?; )?;
collector.clear(); collector.clear();
drop(collector); drop(collector);
shared_new_sst_files.lock().push(sst); shared_new_sst_files.lock().extend(ssts);
} }
anyhow::Ok(()) anyhow::Ok(())
}, },
...@@ -457,6 +473,7 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize ...@@ -457,6 +473,7 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize
let mut builder = MetaFileBuilder::new( let mut builder = MetaFileBuilder::new(
family, family,
self.family_configs[usize_from_u32(family)].compression, self.family_configs[usize_from_u32(family)].compression,
self.shard_bits[usize_from_u32(family)],
); );
for (seq, sst) in sst_files { for (seq, sst) in sst_files {
entries += sst.entries; entries += sst.entries;
...@@ -505,14 +522,35 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize ...@@ -505,14 +522,35 @@ impl<'db, K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize
Ok(NewFile { seq, file, size }) Ok(NewFile { seq, file, size })
} }
/// Creates a new SST file with the given collector data. /// The key hash bits that split the entries of `family` into collectors in memory: the shard
#[tracing::instrument(level = "trace", skip(self, collector_data), fields(family_name = self.family_configs[usize_from_u32(family)].name))] /// bits of the family, but at most [`MAX_COLLECTOR_SHARD_BITS`].
fn create_sst_file( fn collector_bits(&self, family: u32) -> ShardBits {
self.shard_bits[usize_from_u32(family)].min(MAX_COLLECTOR_SHARD_BITS)
}
#[tracing::instrument(level = "trace", skip(self, entries), fields(family_name = self.family_configs[usize_from_u32(family)].name))]
/// Writes sorted entries that can span multiple shards into one SST file per shard.
fn create_sst_files(
&self, &self,
family: u32, family: u32,
collector_data: (&[CollectorEntry<K>], usize), entries: &[CollectorEntry<K>],
) -> Result<NewFile> { ) -> Result<SmallVec<[NewFile; 1]>> {
let (entries, _total_key_size) = collector_data; let shard_bits = self.shard_bits[usize_from_u32(family)];
let mut files = SmallVec::new();
let mut rest = entries;
while let Some(first) = rest.first() {
// Entries are sorted by key hash, so each shard is a contiguous range.
let shard = shard_bits.shard_of(first.key.hash);
let len = rest.partition_point(|e| shard_bits.shard_of(e.key.hash) == shard);
let (chunk, remaining) = rest.split_at(len);
files.push(self.create_sst_file(family, chunk)?);
rest = remaining;
}
Ok(files)
}
/// Creates a new SST file with the given collector data.
fn create_sst_file(&self, family: u32, entries: &[CollectorEntry<K>]) -> Result<NewFile> {
let seq = self.current_sequence_number.fetch_add(1, Ordering::SeqCst) + 1; let seq = self.current_sequence_number.fetch_add(1, Ordering::SeqCst) + 1;
let path = self.db_path.join(format!("{seq:08}.sst")); let path = self.db_path.join(format!("{seq:08}.sst"));
......
use turbo_persistence::{Compression, FamilyConfig, FamilyKind}; use turbo_persistence::{Compression, FamilyConfig, FamilyKind, shard::ShardBits};
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub enum KeySpace { pub enum KeySpace {
...@@ -39,17 +39,23 @@ impl KeySpace { ...@@ -39,17 +39,23 @@ impl KeySpace {
name: self.name(), name: self.name(),
kind: FamilyKind::SingleValue, kind: FamilyKind::SingleValue,
compression: Compression::Lz4, compression: Compression::Lz4,
initial_shard_bits: ShardBits::new(match self {
KeySpace::Infra => 0,
_ => 2,
}),
}, },
KeySpace::TaskData => FamilyConfig { KeySpace::TaskData => FamilyConfig {
name: self.name(), name: self.name(),
kind: FamilyKind::SingleValue, kind: FamilyKind::SingleValue,
compression: Compression::Zstd3, compression: Compression::Zstd3,
initial_shard_bits: ShardBits::new(3),
}, },
KeySpace::TaskCache => FamilyConfig { KeySpace::TaskCache => FamilyConfig {
name: self.name(), name: self.name(),
// TaskCache uses hash-based lookups with potential collisions. // TaskCache uses hash-based lookups with potential collisions.
kind: FamilyKind::MultiValue, kind: FamilyKind::MultiValue,
compression: Compression::Lz4, compression: Compression::Lz4,
initial_shard_bits: ShardBits::new(0),
}, },
} }
} }
......
...@@ -14,7 +14,7 @@ use turbo_persistence::{ ...@@ -14,7 +14,7 @@ use turbo_persistence::{
use turbo_tasks::{ use turbo_tasks::{
message_queue::{TimingEvent, TraceEvent}, message_queue::{TimingEvent, TraceEvent},
parallel::available_parallelism, parallel::available_parallelism,
turbo_tasks, try_turbo_tasks,
}; };
use crate::{ use crate::{
...@@ -30,8 +30,6 @@ pub const FAMILIES: usize = 4; ...@@ -30,8 +30,6 @@ pub const FAMILIES: usize = 4;
const COMPACTION_MESSAGE: &str = "Finished filesystem cache database compaction"; const COMPACTION_MESSAGE: &str = "Finished filesystem cache database compaction";
const MB: u64 = 1024 * 1024;
/// Returns the database configuration for the Turbopack persistent cache, mapping each /// Returns the database configuration for the Turbopack persistent cache, mapping each
/// [`KeySpace`] to its persistence family config. /// [`KeySpace`] to its persistence family config.
pub fn db_config() -> DbConfig<FAMILIES> { pub fn db_config() -> DbConfig<FAMILIES> {
...@@ -42,13 +40,11 @@ pub fn db_config() -> DbConfig<FAMILIES> { ...@@ -42,13 +40,11 @@ pub fn db_config() -> DbConfig<FAMILIES> {
} }
pub const COMPACT_CONFIG: CompactConfig = CompactConfig { pub const COMPACT_CONFIG: CompactConfig = CompactConfig {
min_merge_count: 3, max_space_amplification_percent: 50,
optimal_merge_count: 8, min_bottom_merge_bytes: 1024 * 1024,
max_merge_count: 64, max_files_above_bottom: 6,
max_merge_bytes: 512 * MB, rewrite_per_fresh_byte: 3.0,
min_merge_duplication_bytes: 50 * MB, max_merge_jobs: 16,
optimal_merge_duplication_bytes: 100 * MB,
max_merge_segment_count: 16,
}; };
pub struct TurboKeyValueDatabase { pub struct TurboKeyValueDatabase {
...@@ -166,24 +162,27 @@ impl TurboKeyValueDatabase { ...@@ -166,24 +162,27 @@ impl TurboKeyValueDatabase {
fn do_compact( fn do_compact(
db: &TurboPersistence<TurboTasksParallelScheduler, FAMILIES>, db: &TurboPersistence<TurboTasksParallelScheduler, FAMILIES>,
message: &'static str, message: &'static str,
max_merge_segment_count: usize, max_merge_jobs: usize,
) -> Result<Option<CommitStats>> { ) -> Result<Option<CommitStats>> {
let start = Instant::now(); let start = Instant::now();
// SystemTime for wall-clock timestamps in trace events (Instant has no // SystemTime for wall-clock timestamps in trace events (Instant has no
// defined epoch so it can't be used for cross-process trace correlation). // defined epoch so it can't be used for cross-process trace correlation).
let wall_start = SystemTime::now(); let wall_start = SystemTime::now();
let stats = db.compact(&CompactConfig { let stats = db.compact(&CompactConfig {
max_merge_segment_count, max_merge_jobs,
..COMPACT_CONFIG ..COMPACT_CONFIG
})?; })?;
if let Some(stats) = stats { // Compaction can run outside of turbo-tasks (e.g. in tests), then there is nobody to report to.
if let Some(stats) = stats
&& let Some(turbo_tasks) = try_turbo_tasks()
{
let elapsed = start.elapsed(); let elapsed = start.elapsed();
// avoid spamming the event queue with information about fast operations // avoid spamming the event queue with information about fast operations
if elapsed > Duration::from_secs(10) { if elapsed > Duration::from_secs(10) {
turbo_tasks() turbo_tasks
.send_compilation_event(Arc::new(TimingEvent::new(message.to_string(), elapsed))); .send_compilation_event(Arc::new(TimingEvent::new(message.to_string(), elapsed)));
} }
turbo_tasks().send_compilation_event(Arc::new(TraceEvent::new_with_duration( turbo_tasks.send_compilation_event(Arc::new(TraceEvent::new_with_duration(
"turbopack-compaction", "turbopack-compaction",
wall_start, wall_start,
elapsed, elapsed,
......
...@@ -98,7 +98,7 @@ pub fn compact_database( ...@@ -98,7 +98,7 @@ pub fn compact_database(
// Fully compact with no segment count limit (unlike the runtime shutdown path // Fully compact with no segment count limit (unlike the runtime shutdown path
// which caps segments based on available parallelism). // which caps segments based on available parallelism).
db.compact(&CompactConfig { db.compact(&CompactConfig {
max_merge_segment_count: usize::MAX, max_merge_jobs: usize::MAX,
..turbo::COMPACT_CONFIG ..turbo::COMPACT_CONFIG
})?; })?;
db.shutdown() db.shutdown()
......
...@@ -105,7 +105,7 @@ pub use crate::{ ...@@ -105,7 +105,7 @@ pub use crate::{
ScheduleKey, TaskPersistence, TaskPriority, TurboTasks, TurboTasksApi, TurboTasksCallApi, ScheduleKey, TaskPersistence, TaskPriority, TurboTasks, TurboTasksApi, TurboTasksCallApi,
Unused, UpdateInfo, dynamic_call, emit, get_serialization_invalidator, mark_finished, Unused, UpdateInfo, dynamic_call, emit, get_serialization_invalidator, mark_finished,
mark_stateful, mark_top_level_task, prevent_gc, run, run_once, run_once_with_reason, mark_stateful, mark_top_level_task, prevent_gc, run, run_once, run_once_with_reason,
trait_call, turbo_tasks, turbo_tasks_scope, turbo_tasks_weak, trait_call, try_turbo_tasks, turbo_tasks, turbo_tasks_scope, turbo_tasks_weak,
unmark_top_level_task_may_leak_eventually_consistent_state, with_turbo_tasks, unmark_top_level_task_may_leak_eventually_consistent_state, with_turbo_tasks,
}, },
mapped_read_ref::MappedReadRef, mapped_read_ref::MappedReadRef,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment