Unverified Commit 11823f84 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

Add support for multi-valued tables (#89728)

## What

Add support for multi-valued tables in `turbo-persistence`.

A multi-valued table allows multiple distinct values to be associated
with a single key. Each family is independently configured as
`SingleValue` (existing behavior) or `MultiValue` via the new
`FamilyKind` enum.

## Why

This will support the `TaskCache` table (implemented in #88904), where
keys will change to be _hashes_ instead of full `TaskType` values. This
greatly decreases DB size and speeds up queries due to smaller key
sizes, at the cost of hash collisions requiring multiple values per key.

## How

### API

- New `FamilyKind` enum (`SingleValue` / `MultiValue`) and per-family
`FamilyConfig` in `DbConfig`
- `get()` for single-valued families (panics if called on multi-valued)
- `get_multiple()` for multi-valued families, returns
`SmallVec<[ArcBytes; 1]>` — stack-allocated for the common 0–1 result
case, heap-scales when needed
- `put()` and `delete()` are unchanged — the family kind controls
dedup/compaction behavior

### Write path & compaction

- **Single-valued** (unchanged): last-write-wins per key
- **Multi-valued**: all values are maintained, deletions 'shadow' old
values.
- Deletion inserts a tombstone that shadows all older values for that
key across SST layers. Values written *after* the tombstone in the same
batch are retained.
- To avoid extra buffering logic the `MergeIter` semantics were changed
so it produces 'newest' entries first
* for SingleValues families this is no different since we only keep one
value
* for MultiValued families this makes dealing with tombstones trivial,
but does mean compaction will reverse the order of the set. For this
reason we make no guarantees about ordering.

### Read path

- Controlled by a `FIND_ALL` const generic on the internal lookup
methods
- **Single-valued** (`FIND_ALL=false`): binary search, return _last_
match, stop
* This fixes a bug where we might return Deleted when there is a value
in the SST depending on what the search algorithm found first
- **Multi-valued** (`FIND_ALL=true`): scan all matching entries in the
SST block, then continue to older SSTs. If a tombstone is found, stop
searching older layers.

---------
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
parent 872c01b5
......@@ -3,7 +3,7 @@
use std::path::PathBuf;
use anyhow::{Context, Result, bail};
use turbo_persistence::{MetaFileEntryInfo, SerialScheduler, TurboPersistence};
use turbo_persistence::{DbConfig, MetaFileEntryInfo, SerialScheduler, TurboPersistence};
fn main() -> Result<()> {
// Get CLI argument
......@@ -16,7 +16,8 @@ fn main() -> Result<()> {
bail!("The provided path does not exist: {}", path.display());
}
let db: TurboPersistence<SerialScheduler, 0> = TurboPersistence::open_read_only(path)?;
let db: TurboPersistence<SerialScheduler, 0> =
TurboPersistence::open_read_only_with_config(path, DbConfig::default())?;
let meta_info = db
.meta_info()
.context("Failed to retrieve meta information")?;
......
......@@ -10,9 +10,9 @@ use quick_cache::sync::GuardResult;
use rand::{RngExt, SeedableRng, rngs::SmallRng, seq::SliceRandom};
use tempfile::TempDir;
use turbo_persistence::{
ArcBytes, BlockCache, CompactConfig, Entry, EntryValue, MetaEntryFlags, SerialScheduler,
StaticSortedFile, StaticSortedFileMetaData, TurboPersistence, hash_key,
write_static_stored_file,
ArcBytes, BlockCache, CompactConfig, DbConfig as TpDbConfig, Entry, EntryValue, FamilyConfig,
FamilyKind, MetaEntryFlags, SerialScheduler, StaticSortedFile, StaticSortedFileMetaData,
TurboPersistence, hash_key, write_static_stored_file,
};
use turbo_tasks_malloc::TurboMalloc;
......@@ -551,6 +551,240 @@ fn bench_read_batch_get(c: &mut Criterion) {
group.finish();
}
// =============================================================================
// Read Benchmarks - Get Multiple
// =============================================================================
/// Configuration for prefilling a multi-value database
#[derive(Clone, Copy, Debug)]
struct MultiValueDbConfig {
key_size: usize,
value_size: usize,
/// Total number of entries (key-value pairs) written
entry_count: usize,
/// Number of distinct keys. Must be <= entry_count.
/// When < entry_count, some keys will have multiple values.
distinct_key_count: usize,
commit_count: usize,
compacted: bool,
}
/// Prefill a multi-value database and return the distinct keys
fn prefill_multi_value_database(
path: &Path,
config: &MultiValueDbConfig,
) -> Result<Vec<Box<[u8]>>> {
let db_config = TpDbConfig {
family_configs: [FamilyConfig {
kind: FamilyKind::MultiValue,
}],
};
let db =
TurboPersistence::<SerialScheduler, 1>::open_with_config(path.to_path_buf(), db_config)?;
let mut rng = SmallRng::seed_from_u64(42);
// Generate all distinct keys up front
let max_stored_keys = config
.distinct_key_count
.min(MAX_KEY_MEMORY / (config.key_size + size_of::<Box<[u8]>>()));
let mut keys: Vec<Box<[u8]>> = (0..max_stored_keys)
.map(|_| random_key(&mut rng, config.key_size))
.collect();
let entries_per_commit = config.entry_count / config.commit_count;
for commit_idx in 0..config.commit_count {
let batch = db.write_batch()?;
let start = commit_idx * entries_per_commit;
let end = if commit_idx == config.commit_count - 1 {
config.entry_count
} else {
start + entries_per_commit
};
for i in start..end {
// Cycle through keys to create duplicates
let key = &keys[i % keys.len()];
let value = random_value(&mut rng, config.value_size);
batch.put(0, key.clone(), value.into())?;
}
db.commit_write_batch(batch)?;
}
if config.compacted {
for _ in 0..3 {
db.full_compact()?;
}
}
db.shutdown()?;
keys.shuffle(&mut rng);
Ok(keys)
}
/// Create a temporary directory with a prefilled multi-value database
fn setup_prefilled_multi_value_db(
config: &MultiValueDbConfig,
id: &str,
) -> Result<(TempDir, Vec<Box<[u8]>>)> {
let tempdir = tempfile::tempdir()?;
let keys = prefill_multi_value_database(tempdir.path(), config)?;
let db_size = tempdir
.path()
.read_dir()?
.filter_map(|entry| entry.ok())
.filter_map(|entry| entry.metadata().ok())
.map(|metadata| metadata.len())
.sum::<u64>();
println!(
"\n{id} db size: {}B = {}B per item = {}% of original size",
format_number(db_size as usize),
format_number(db_size as usize / config.entry_count),
(db_size as usize * 100 / (config.entry_count * (config.key_size + config.value_size)))
);
Ok((tempdir, keys))
}
fn open_multi_value_db(path: &Path) -> TurboPersistence<SerialScheduler, 1> {
let db_config = TpDbConfig {
family_configs: [FamilyConfig {
kind: FamilyKind::MultiValue,
}],
};
TurboPersistence::<SerialScheduler, 1>::open_with_config(path.to_path_buf(), db_config).unwrap()
}
fn bench_read_get_multiple(c: &mut Criterion) {
let mut group = c.benchmark_group("read/get_multiple");
group.measurement_time(Duration::from_secs(10));
// Configuration parameters: (key_size, value_size)
let entry_sizes = [(8, 4), (4, 32 * 1024), (32 * 1024, 4)];
// Configuration parameters: (database_size, values_per_key, commit_count, compacted)
let db_configs: &[(usize, usize, usize, bool)] = &[
// 1 value per key (similar to SingleValue, baseline)
(128 * 1024 * 1024, 1, 1, true),
(128 * 1024 * 1024, 1, 1, false),
// Multiple values per key
(128 * 1024 * 1024, 4, 1, true),
(128 * 1024 * 1024, 4, 1, false),
(128 * 1024 * 1024, 4, 20, false),
];
for &(key_size, value_size) in &entry_sizes {
for &(database_size, values_per_key, commit_count, compacted) in db_configs {
let entry_count = database_size / (key_size + value_size);
let distinct_key_count = entry_count / values_per_key;
let config = MultiValueDbConfig {
key_size,
value_size,
entry_count,
distinct_key_count,
commit_count,
compacted,
};
let compacted_str = if compacted {
"compacted"
} else {
"uncompacted"
};
let id = format!(
"key_{}/value_{}/entries_{}/vpk_{}/commits_{}/{}",
format_number(key_size),
format_number(value_size),
format_number(entry_count),
values_per_key,
commit_count,
compacted_str,
);
let db = LazyLock::new(|| {
let (tempdir, keys) = setup_prefilled_multi_value_db(&config, &id).unwrap();
let db = open_multi_value_db(tempdir.path());
let rng = Mutex::new(SmallRng::seed_from_u64(123));
(tempdir, db, keys, rng)
});
group.bench_function(format!("{id}/hit/uncached"), |b| {
let (_, db, keys, rng) = &*db;
let mut rng = rng.lock();
iter_batched_with_init(
b,
|_| prepare_db_for_benchmarking(db),
|_| {
let idx = rng.random_range(0..keys.len());
&keys[idx]
},
|key| {
let result = db.get_multiple(0, key).unwrap();
black_box(result)
},
BatchSize::PerIteration,
);
});
group.bench_function(format!("{id}/hit/cached"), |b| {
let (_, db, keys, _) = &*db;
iter_batched_with_init(
b,
|_| prepare_db_for_benchmarking(db),
|i| &keys[i as usize % keys.len()],
|key| {
let result = db.get_multiple(0, key).unwrap();
black_box(result)
},
BatchSize::NumBatches(1),
);
});
group.bench_function(format!("{id}/miss/uncached"), |b| {
let (_, db, _, rng) = &*db;
let mut rng = rng.lock();
iter_batched_with_init(
b,
|_| prepare_db_for_benchmarking(db),
|_| random_key(&mut rng, key_size),
|key| {
let result = db.get_multiple(0, &key).unwrap();
black_box(result)
},
BatchSize::PerIteration,
);
});
group.bench_function(format!("{id}/miss/cached"), |b| {
let (_, db, _, rng) = &*db;
let mut rng = rng.lock();
let miss_keys = UnsafeCell::new(Vec::new());
iter_batched_with_init(
b,
|batch_size| {
prepare_db_for_benchmarking(db);
// SAFETY: We are the only ones mutating miss_keys during this
// initialization phase
let miss_keys = unsafe { &mut *miss_keys.get() };
while miss_keys.len() < batch_size as usize {
miss_keys.push(random_key(&mut rng, key_size));
}
},
|i| {
let miss_keys = unsafe { &*miss_keys.get() };
&miss_keys[i as usize]
},
|key| {
let result = db.get_multiple(0, key).unwrap();
black_box(result)
},
BatchSize::NumBatches(1),
);
});
}
}
group.finish();
}
// =============================================================================
// Compaction Benchmarks
// =============================================================================
......@@ -635,6 +869,136 @@ fn bench_compaction(c: &mut Criterion) {
group.finish();
}
// =============================================================================
// Write Benchmarks - Multi-Value
// =============================================================================
fn bench_write_multi_value(c: &mut Criterion) {
let mut group = c.benchmark_group("write/multi_value");
group.sample_size(10);
group.sampling_mode(SamplingMode::Flat);
// Key-value sizes to test
let entry_sizes = [(8, 4), (4, 32 * 1024)];
// (database_size, values_per_key)
let configs: &[(usize, usize)] = &[
(10 * 1024 * 1024, 1), // Baseline: 1 value per key
(10 * 1024 * 1024, 4), // 4 values per key
];
for &(key_size, value_size) in &entry_sizes {
for &(database_size, values_per_key) in configs {
let entry_count = database_size / (key_size + value_size);
let distinct_key_count = entry_count / values_per_key;
let id = format!(
"key_{}/value_{}/entries_{}/vpk_{}",
format_number(key_size),
format_number(value_size),
format_number(entry_count),
values_per_key,
);
group.bench_function(&id, |b| {
b.iter_batched(
|| {
let tempdir = tempfile::tempdir().unwrap();
let mut rng = SmallRng::seed_from_u64(42);
// Generate distinct keys
let keys: Vec<Box<[u8]>> = (0..distinct_key_count)
.map(|_| random_key(&mut rng, key_size))
.collect();
let mut random_data = vec![0u8; entry_count * value_size];
rng.fill(&mut random_data[..]);
(tempdir, keys, random_data)
},
|(tempdir, keys, random_data)| {
let db_config = TpDbConfig {
family_configs: [FamilyConfig {
kind: FamilyKind::MultiValue,
}],
};
let db = TurboPersistence::<SerialScheduler, 1>::open_with_config(
tempdir.path().to_path_buf(),
db_config,
)
.unwrap();
let batch = db.write_batch().unwrap();
for i in 0..entry_count {
let key = &keys[i % distinct_key_count];
let value = &random_data[i * value_size..(i + 1) * value_size];
batch.put(0, &**key, value.into()).unwrap();
}
db.commit_write_batch(batch).unwrap();
db.shutdown().unwrap();
tempdir
},
BatchSize::PerIteration,
);
});
}
}
group.finish();
}
// =============================================================================
// Compaction Benchmarks - Multi-Value
// =============================================================================
fn bench_compaction_multi_value(c: &mut Criterion) {
let mut group = c.benchmark_group("compaction/multi_value");
group.sample_size(10);
group.sampling_mode(SamplingMode::Flat);
// (entry_count, values_per_key, commit_count)
let configs = [
(1024 * 1024 * 4, 1, 8), // Baseline: 1 value/key
(1024 * 1024 * 4, 4, 8), // 4 values/key
(1024 * 1024 * 4, 4, 32), // 4 values/key, more commits
];
let key_size = 8;
let value_size = 4;
for &(entry_count, values_per_key, commit_count) in &configs {
let distinct_key_count = entry_count / values_per_key;
let config = MultiValueDbConfig {
key_size,
value_size,
entry_count,
distinct_key_count,
commit_count,
compacted: false,
};
let id = format!(
"entries_{}/vpk_{}/commits_{}",
format_number(entry_count),
values_per_key,
commit_count,
);
let setup = || {
let (tempdir, _keys) = setup_prefilled_multi_value_db(&config, &id).unwrap();
let db = open_multi_value_db(tempdir.path());
(tempdir, db)
};
group.bench_function(format!("{id}/full"), |b| {
b.iter_batched(
setup,
|(_tempdir, db)| {
db.full_compact().unwrap();
black_box(db)
},
BatchSize::PerIteration,
);
});
}
group.finish();
}
// =============================================================================
// QFilter Benchmarks
// =============================================================================
......@@ -839,7 +1203,7 @@ fn bench_static_sorted_file_lookup(c: &mut Criterion) {
},
|(key, hash)| {
let result = sst
.lookup(hash, &key, key_block_cache, value_block_cache)
.lookup::<_, false>(hash, &key, key_block_cache, value_block_cache)
.unwrap();
black_box(result)
},
......@@ -858,7 +1222,7 @@ fn bench_static_sorted_file_lookup(c: &mut Criterion) {
|i| keys[i as usize % keys.len()],
|(key, hash)| {
let result = sst
.lookup(hash, &key, key_block_cache, value_block_cache)
.lookup::<_, false>(hash, &key, key_block_cache, value_block_cache)
.unwrap();
black_box(result)
},
......@@ -884,7 +1248,7 @@ fn bench_static_sorted_file_lookup(c: &mut Criterion) {
},
|(key, hash)| {
let result = sst
.lookup(hash, &key, key_block_cache, value_block_cache)
.lookup::<_, false>(hash, &key, key_block_cache, value_block_cache)
.unwrap();
black_box(result)
},
......@@ -917,7 +1281,7 @@ fn bench_static_sorted_file_lookup(c: &mut Criterion) {
},
|(key, hash)| {
let result = sst
.lookup(*hash, &key, key_block_cache, value_block_cache)
.lookup::<_, false>(*hash, &key, key_block_cache, value_block_cache)
.unwrap();
black_box(result)
},
......@@ -1069,6 +1433,6 @@ fn bench_block_cache(c: &mut Criterion) {
criterion_group!(
name = benches;
config = Criterion::default();
targets = bench_write, bench_read_get, bench_read_batch_get, bench_compaction, bench_qfilter, bench_static_sorted_file_lookup, bench_block_cache
targets = bench_write, bench_write_multi_value, bench_read_get, bench_read_batch_get, bench_read_get_multiple, bench_compaction, bench_compaction_multi_value, bench_qfilter, bench_static_sorted_file_lookup, bench_block_cache
);
criterion_main!(benches);
use std::mem::take;
use crate::{
ValueBuffer,
FamilyKind, ValueBuffer,
collector_entry::{CollectorEntry, CollectorEntryValue, EntryKey, TINY_VALUE_THRESHOLD},
constants::{
DATA_THRESHOLD_PER_INITIAL_FILE, MAX_ENTRIES_PER_INITIAL_FILE, MAX_SMALL_VALUE_SIZE,
......@@ -110,10 +110,44 @@ impl<K: StoreKey, const SIZE_SHIFT: usize> Collector<K, SIZE_SHIFT> {
self.entries.push(entry);
}
/// Sorts the entries and returns them along with the total key size. This doesn't
/// clear the entries.
pub fn sorted(&mut self) -> (&[CollectorEntry<K>], usize) {
self.entries.sort_unstable_by(|a, b| a.key.cmp(&b.key));
/// Sorts entries by key. Tombstones are placed last within each key group.
/// This method does not deduplicate entries.
///
/// In debug builds, asserts that SingleValue families have no duplicate keys.
pub fn sorted(&mut self, family_kind: FamilyKind) -> (&[CollectorEntry<K>], usize) {
// Sort by (hash, key) with tombstones placed last within each key group.
// We can use unstable sort because the relative order of equal elements
// doesn't matter — duplicates are either disallowed (SingleValue) or
// allowed without deduplication (MultiValue).
self.entries.sort_unstable_by(|a, b| {
a.key
.cmp(&b.key)
.then_with(|| a.value.is_deleted().cmp(&b.value.is_deleted()))
});
#[cfg(debug_assertions)]
if family_kind == FamilyKind::SingleValue {
// WriteBatch callers must not insert duplicate keys for SingleValue families.
for w in self.entries.windows(2) {
if w[0].key == w[1].key {
let mut key_buf = Vec::new();
w[0].key.data.write_to(&mut key_buf);
panic!(
"WriteBatch invariant violation: SingleValue family has duplicate key \
(hash={:#018x}, key={})",
w[0].key.hash,
key_buf
.iter()
.map(|b| format!("{b:02x}"))
.collect::<String>(),
);
}
}
}
// Suppress unused variable warning in release builds
let _ = family_kind;
(&self.entries, self.total_key_size)
}
......
......@@ -16,7 +16,7 @@ pub struct CollectorEntry<K: StoreKey> {
pub const TINY_VALUE_THRESHOLD: usize = 22;
pub enum CollectorEntryValue {
/// Tiny value stored inline (22 16 bytes, no heap allocation)
/// Tiny value stored inline (≤22 bytes, no heap allocation)
Tiny {
value: [u8; TINY_VALUE_THRESHOLD],
len: u8,
......@@ -61,6 +61,11 @@ impl CollectorEntryValue {
_ => 0,
}
}
/// Returns true if this value is a deletion tombstone.
pub fn is_deleted(&self) -> bool {
matches!(self, CollectorEntryValue::Deleted)
}
}
pub struct EntryKey<K: StoreKey> {
......
......@@ -17,10 +17,11 @@ use memmap2::Mmap;
use nohash_hasher::BuildNoHashHasher;
use parking_lot::{Mutex, RwLock};
use smallvec::SmallVec;
use tracing::span::EnteredSpan;
pub use crate::compaction::selector::CompactConfig;
use crate::{
QueryKey,
DbConfig, FamilyKind, QueryKey,
arc_bytes::ArcBytes,
compaction::selector::{Compactable, get_merge_segments},
compression::decompress_into_arc,
......@@ -29,7 +30,7 @@ use crate::{
MAX_ENTRIES_PER_COMPACTED_FILE, VALUE_BLOCK_AVG_SIZE, VALUE_BLOCK_CACHE_SIZE,
},
key::{StoreKey, hash_key},
lookup_entry::{LookupEntry, LookupValue},
lookup_entry::{LazyLookupValue, LookupEntry, LookupValue},
merge_iter::MergeIter,
meta_file::{MetaEntryFlags, MetaFile, MetaLookupResult, StaticSortedFileRange},
meta_file_builder::MetaFileBuilder,
......@@ -121,6 +122,8 @@ pub struct TurboPersistence<S: ParallelScheduler, const FAMILIES: usize> {
key_block_cache: BlockCache,
/// A cache for decompressed value blocks.
value_block_cache: BlockCache,
/// Per-family configuration for file limits.
config: DbConfig<FAMILIES>,
/// Statistics for the database.
#[cfg(feature = "stats")]
stats: TrackedStats,
......@@ -157,15 +160,25 @@ impl<S: ParallelScheduler + Default, const FAMILIES: usize> TurboPersistence<S,
Self::open_with_parallel_scheduler(path, Default::default())
}
/// Open a TurboPersistence database at the given path with custom per-family configuration.
pub fn open_with_config(path: PathBuf, config: DbConfig<FAMILIES>) -> Result<Self> {
Self::open_with_config_and_parallel_scheduler(path, config, Default::default())
}
/// Open a TurboPersistence database at the given path in read only mode.
/// This will read the directory. No Cleanup is performed.
pub fn open_read_only(path: PathBuf) -> Result<Self> {
Self::open_read_only_with_parallel_scheduler(path, Default::default())
pub fn open_read_only_with_config(path: PathBuf, config: DbConfig<FAMILIES>) -> Result<Self> {
Self::open_read_only_with_parallel_scheduler(path, config, Default::default())
}
}
impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES> {
fn new(path: PathBuf, read_only: bool, parallel_scheduler: S) -> Self {
fn new(
path: PathBuf,
read_only: bool,
parallel_scheduler: S,
config: DbConfig<FAMILIES>,
) -> Self {
Self {
parallel_scheduler,
path,
......@@ -191,6 +204,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
Default::default(),
Default::default(),
),
config,
#[cfg(feature = "stats")]
stats: TrackedStats::default(),
}
......@@ -201,18 +215,28 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
/// properly. Cleanup only requires to read a few bytes from a few files and to delete
/// files, so it's fast.
pub fn open_with_parallel_scheduler(path: PathBuf, parallel_scheduler: S) -> Result<Self> {
let mut db = Self::new(path, false, parallel_scheduler);
Self::open_with_config_and_parallel_scheduler(path, DbConfig::default(), parallel_scheduler)
}
/// Open a TurboPersistence database at the given path with custom per-family configuration.
pub fn open_with_config_and_parallel_scheduler(
path: PathBuf,
config: DbConfig<FAMILIES>,
parallel_scheduler: S,
) -> Result<Self> {
let mut db = Self::new(path, false, parallel_scheduler, config);
db.open_directory(false)?;
Ok(db)
}
/// Open a TurboPersistence database at the given path in read only mode.
/// This will read the directory. No Cleanup is performed.
pub fn open_read_only_with_parallel_scheduler(
fn open_read_only_with_parallel_scheduler(
path: PathBuf,
config: DbConfig<FAMILIES>,
parallel_scheduler: S,
) -> Result<Self> {
let mut db = Self::new(path, true, parallel_scheduler);
let mut db = Self::new(path, true, parallel_scheduler, config);
db.open_directory(false)?;
Ok(db)
}
......@@ -422,6 +446,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
self.path.clone(),
current,
self.parallel_scheduler.clone(),
self.config.family_configs,
))
}
......@@ -986,7 +1011,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
new_sst_files: Vec<(u32, File, StaticSortedFileBuilderMeta<'static>)>,
blob_seq_numbers_to_delete: Vec<u32>,
keys_written: u64,
indicies: SmallVec<[usize; 1]>,
indices: SmallVec<[usize; 1]>,
},
Move {
seq: u32,
......@@ -995,185 +1020,175 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
}
let merge_result = self
.parallel_scheduler
.parallel_map_collect_owned::<_, _, Result<Vec<_>>>(
merge_jobs,
|indicies| {
let _span = span.clone().entered();
if indicies.len() == 1 {
// If we only have one file, we can just move it
let index = indicies[0];
.parallel_map_collect_owned::<_, _, Result<Vec<_>>>(merge_jobs, |indices| {
let _span = span.clone().entered();
if indices.len() == 1 {
// If we only have one file, we can just move it
let index = indices[0];
let meta_index = ssts_with_ranges[index].meta_index;
let index_in_meta = ssts_with_ranges[index].index_in_meta;
let meta_file = &meta_files[meta_index];
let entry = meta_file.entry(index_in_meta);
let amqf = Cow::Borrowed(entry.raw_amqf(meta_file.amqf_data()));
let meta = StaticSortedFileBuilderMeta {
min_hash: entry.min_hash(),
max_hash: entry.max_hash(),
amqf,
block_count: entry.block_count(),
size: entry.size(),
flags: entry.flags(),
entries: 0,
};
return Ok(PartialMergeResult::Move {
seq: entry.sequence_number(),
meta,
});
}
// Open SST files independently for compaction.
// Uses MADV_SEQUENTIAL for better OS page management
// and avoids caching mmaps on MetaEntry's OnceLock.
let iters = indices
.iter()
.map(|&index| {
let meta_index = ssts_with_ranges[index].meta_index;
let index_in_meta = ssts_with_ranges[index].index_in_meta;
let meta_file = &meta_files[meta_index];
let entry = meta_file.entry(index_in_meta);
let amqf = Cow::Borrowed(entry.raw_amqf(meta_file.amqf_data()));
let meta = StaticSortedFileBuilderMeta {
min_hash: entry.min_hash(),
max_hash: entry.max_hash(),
amqf,
block_count: entry.block_count(),
size: entry.size(),
flags: entry.flags(),
entries: 0,
};
return Ok(PartialMergeResult::Move {
seq: entry.sequence_number(),
meta,
});
}
// Open SST files independently for compaction.
// Uses MADV_SEQUENTIAL for better OS page management
// and avoids caching mmaps on MetaEntry's OnceLock.
let iters = indicies
.iter()
.map(|&index| {
let meta_index = ssts_with_ranges[index].meta_index;
let index_in_meta = ssts_with_ranges[index].index_in_meta;
let entry = meta_files[meta_index].entry(index_in_meta);
StaticSortedFile::open_for_compaction(
path,
entry.sst_metadata(),
)?
.try_into_iter()
})
.collect::<Result<Vec<_>>>()?;
let iter = MergeIter::new(iters.into_iter())?;
// TODO figure out how to delete blobs when they are no longer
// referenced
let blob_seq_numbers_to_delete: Vec<u32> = Vec::new();
let mut keys_written = 0;
let mut current: Option<LookupEntry> = None;
struct Collector {
/// The active writer and its sequence number. `None` if no
/// entries have been added since the last flush. We defer
/// allocation to avoid creating empty SST files for collectors
/// that receive no entries (e.g., the unused_collector when
/// all keys are in the
/// used set).
writer: Option<(u32, StreamingSstWriter<LookupEntry>)>,
flags: MetaEntryFlags,
new_sst_files:
Vec<(u32, File, StaticSortedFileBuilderMeta<'static>)>,
}
impl Collector {
fn new(flags: MetaEntryFlags) -> Self {
Self {
writer: None,
flags,
new_sst_files: Vec::new(),
}
let entry = meta_files[meta_index].entry(index_in_meta);
StaticSortedFile::open_for_compaction(
path,
entry.sst_metadata(),
)?
.try_into_iter()
})
.collect::<Result<Vec<_>>>()?;
let iter = MergeIter::new(iters.into_iter())?;
// TODO figure out how to delete blobs when they are no longer
// referenced
let blob_seq_numbers_to_delete: Vec<u32> = Vec::new();
struct Collector {
/// The active writer and its sequence number. `None` if no
/// entries have been added since the last flush. We defer
/// allocation to avoid creating empty SST files for collectors
/// that receive no entries (e.g., the unused_collector when
/// all keys are in the
/// used set).
writer: Option<(u32, StreamingSstWriter<LookupEntry>)>,
flags: MetaEntryFlags,
new_sst_files:
Vec<(u32, File, StaticSortedFileBuilderMeta<'static>)>,
/// Hash of the last key added. Used to ensure we only split
/// SST files at key boundaries (not mid-key-group for MultiValue).
last_hash: Option<u64>,
}
impl Collector {
fn new(flags: MetaEntryFlags) -> Self {
Self {
writer: None,
flags,
new_sst_files: Vec::new(),
last_hash: None,
}
}
/// Ensures a writer is open, creating one if needed.
fn ensure_writer(
&mut self,
path: &Path,
sequence_number: &AtomicU32,
) -> Result<&mut StreamingSstWriter<LookupEntry>>
{
if self.writer.is_none() {
let seq =
sequence_number.fetch_add(1, Ordering::SeqCst) + 1;
let sst_path = path.join(format!("{seq:08}.sst"));
let writer = StreamingSstWriter::new(
&sst_path,
self.flags,
MAX_ENTRIES_PER_COMPACTED_FILE as u64,
)?;
self.writer = Some((seq, writer));
}
Ok(&mut self.writer.as_mut().unwrap().1)
/// Ensures a writer is open, creating one if needed.
fn ensure_writer(
&mut self,
path: &Path,
sequence_number: &AtomicU32,
) -> Result<&mut StreamingSstWriter<LookupEntry>>
{
if self.writer.is_none() {
let seq =
sequence_number.fetch_add(1, Ordering::SeqCst) + 1;
let sst_path = path.join(format!("{seq:08}.sst"));
let writer = StreamingSstWriter::new(
&sst_path,
self.flags,
MAX_ENTRIES_PER_COMPACTED_FILE as u64,
)?;
self.writer = Some((seq, writer));
}
Ok(&mut self.writer.as_mut().unwrap().1)
}
/// Closes the current SST file (flushing remaining blocks and
/// writing the index) and records it in the completed files
/// list.
fn close_sst_file(
&mut self,
keys_written: &mut u64,
) -> Result<()> {
if let Some((seq, writer)) = self.writer.take() {
let _span =
tracing::trace_span!("close merged sst file")
.entered();
let (meta, file) = writer.close()?;
*keys_written += meta.entries;
self.new_sst_files.push((seq, file, meta));
}
Ok(())
/// Closes the current SST file (flushing remaining blocks and
/// writing the index) and records it in the completed files
/// list.
fn close_sst_file(&mut self, keys_written: &mut u64) -> Result<()> {
if let Some((seq, writer)) = self.writer.take() {
let _span =
tracing::trace_span!("close merged sst file").entered();
let (meta, file) = writer.close()?;
*keys_written += meta.entries;
self.new_sst_files.push((seq, file, meta));
}
Ok(())
}
/// Adds an entry to the collector. Writes the entry first,
/// then checks if the file is full and closes it if so.
fn add_entry(
&mut self,
entry: LookupEntry,
path: &Path,
sequence_number: &AtomicU32,
keys_written: &mut u64,
) -> Result<()> {
let writer = self.ensure_writer(path, sequence_number)?;
writer.add(entry)?;
// Check fullness after adding -- the writer tracks sizes
// and block counts internally.
if writer.is_full(
/// Adds an entry to the collector. Only splits the SST file at
/// key boundaries to avoid breaking key groups for MultiValue
/// families.
fn add_entry(
&mut self,
entry: LookupEntry,
path: &Path,
sequence_number: &AtomicU32,
keys_written: &mut u64,
) -> Result<()> {
let key_changed = self.last_hash != Some(entry.hash);
// Only check fullness at key boundaries to avoid splitting
// a key group across two SST files.
if key_changed
&& let Some((_, ref writer)) = self.writer
&& writer.is_full(
MAX_ENTRIES_PER_COMPACTED_FILE,
DATA_THRESHOLD_PER_COMPACTED_FILE,
) {
self.close_sst_file(keys_written)?;
}
Ok(())
)
{
self.close_sst_file(keys_written)?;
}
self.last_hash = Some(entry.hash);
let writer = self.ensure_writer(path, sequence_number)?;
writer.add(entry)?;
Ok(())
}
#[cfg(debug_assertions)]
impl Drop for Collector {
fn drop(&mut self) {
if !std::thread::panicking() {
assert!(
self.writer.is_none(),
"Collector dropped with an open writer"
);
}
}
#[cfg(debug_assertions)]
impl Drop for Collector {
fn drop(&mut self) {
if !std::thread::panicking() {
assert!(
self.writer.is_none(),
"Collector dropped with an open writer"
);
}
}
let mut used_collector = Collector::new(MetaEntryFlags::WARM);
let mut unused_collector = Collector::new(MetaEntryFlags::COLD);
for entry in iter {
let entry = entry?;
// Remove duplicates
if let Some(current) = current.take() {
if current.key != entry.key {
let is_used =
used_key_hashes.as_ref().is_some_and(|amqf| {
amqf.contains_fingerprint(current.hash)
});
let collector = if is_used {
&mut used_collector
} else {
&mut unused_collector
};
collector.add_entry(
current,
path,
sequence_number,
&mut keys_written,
)?;
} else {
// Override value
// TODO delete blob file
}
}
current = Some(entry);
}
let mut used_collector = Collector::new(MetaEntryFlags::WARM);
let mut unused_collector = Collector::new(MetaEntryFlags::COLD);
let mut current_key: Option<ArcBytes> = None;
let mut keys_written = 0;
// MergeIter yields entries from newer SSTs first (by SST sequence
// number). Within each SST, tombstones sort last within key groups.
// Use a skip flag to handle:
// - SingleValue: skip all older entries after writing the first
// - MultiValue: skip all older entries after encountering a tombstone
// (which signals deletion of all prior values for this key)
let mut skip_remaining_for_this_key = false;
let family_config = &self.config.family_configs[family as usize];
for entry in iter {
let entry = entry?;
if current_key.as_ref() != Some(&entry.key) {
// we changed keys so undo this flag
skip_remaining_for_this_key = false;
current_key = Some(entry.key.clone());
}
if let Some(entry) = current {
if !skip_remaining_for_this_key {
let is_used = used_key_hashes
.as_ref()
.is_some_and(|amqf| amqf.contains_fingerprint(entry.hash));
......@@ -1182,6 +1197,23 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
} else {
&mut unused_collector
};
match family_config.kind {
FamilyKind::MultiValue => {
// For MultiValue families we only skip remaining if we
// see a tombstone
if matches!(
entry.value,
LazyLookupValue::Eager(LookupValue::Deleted)
) {
skip_remaining_for_this_key = true;
}
}
FamilyKind::SingleValue => {
// Since MergeItr is in newest to oldest order anything
// else that comes out must be skipped
skip_remaining_for_this_key = true;
}
}
collector.add_entry(
entry,
path,
......@@ -1189,21 +1221,21 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
&mut keys_written,
)?;
}
}
// Close remaining writers
used_collector.close_sst_file(&mut keys_written)?;
unused_collector.close_sst_file(&mut keys_written)?;
let mut new_sst_files = take(&mut unused_collector.new_sst_files);
new_sst_files.append(&mut used_collector.new_sst_files);
Ok(PartialMergeResult::Merged {
new_sst_files,
blob_seq_numbers_to_delete,
keys_written,
indicies,
})
},
)
// Close remaining writers
used_collector.close_sst_file(&mut keys_written)?;
unused_collector.close_sst_file(&mut keys_written)?;
let mut new_sst_files = take(&mut unused_collector.new_sst_files);
new_sst_files.append(&mut used_collector.new_sst_files);
Ok(PartialMergeResult::Merged {
new_sst_files,
blob_seq_numbers_to_delete,
keys_written,
indices,
})
})
.with_context(|| {
format!("Failed to merge database files for family {family}")
})?;
......@@ -1214,7 +1246,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
if let PartialMergeResult::Merged {
new_sst_files,
blob_seq_numbers_to_delete,
indicies: _,
indices: _,
keys_written: _,
} = r
{
......@@ -1245,14 +1277,14 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
new_sst_files: merged_new_sst_files,
blob_seq_numbers_to_delete: merged_blob_seq_numbers_to_delete,
keys_written: merged_keys_written,
indicies,
indices,
} => {
writeln!(
log,
"{family:3} | {meta_seq:08} | MERGE \
({merged_keys_written} keys):"
)?;
for i in indicies.iter() {
for i in indices.iter() {
let seq = ssts_with_ranges[*i].seq;
let (min, max) = ssts_with_ranges[*i].range().into_inner();
writeln!(
......@@ -1340,16 +1372,75 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
/// might hold onto a block of the database and it should not be hold long-term.
pub fn get<K: QueryKey>(&self, family: usize, key: &K) -> Result<Option<ArcBytes>> {
debug_assert!(family < FAMILIES, "Family index out of bounds");
if self.config.family_configs[family].kind != FamilyKind::SingleValue {
// This is an error in our caller so just panic
panic!(
"only single valued tables can be queried with `get', call `get_multiple` instead"
)
}
let span = tracing::trace_span!(
"database read",
name = family,
result_size = tracing::field::Empty
)
.entered();
let results = self.get_impl::<K, false>(family, key, &span)?;
debug_assert!(results.len() <= 1, "get() should return at most one result");
Ok(results.into_iter().next())
}
/// Looks up a key and returns all matching values.
///
/// This is useful for keyspaces where keys are not unique and multiple mappings are possible.
/// Unlike `get`, which returns only the first match, this method returns all
/// entries with the same key from all SST files. By default however we assume these
/// collections are small and thus optimize for there being exactly 0 or 1 results.
///
/// The order of returned values is undefined and duplicates are preserved. Callers must not
/// rely on any particular ordering (neither insertion order nor byte order).
pub fn get_multiple<K: QueryKey>(
&self,
family: usize,
key: &K,
) -> Result<SmallVec<[ArcBytes; 1]>> {
debug_assert!(family < FAMILIES, "Family index out of bounds");
if self.config.family_configs[family].kind != FamilyKind::MultiValue {
// This is an error in our caller so just panic
panic!("only multi-valued tables can be queried with `get_multiple`")
}
let span = tracing::trace_span!(
"database read multiple",
name = family,
result_count = tracing::field::Empty,
result_size = tracing::field::Empty
)
.entered();
let results = self.get_impl::<K, true>(family, key, &span)?;
Ok(results)
}
/// Shared implementation for `get` and `get_multiple`.
///
/// If `FIND_ALL` is false, stops after finding the first match.
/// If `FIND_ALL` is true, continues to find all matches across all meta files.
fn get_impl<K: QueryKey, const FIND_ALL: bool>(
&self,
family: usize,
key: &K,
span: &EnteredSpan,
) -> Result<SmallVec<[ArcBytes; 1]>> {
let hash = hash_key(key);
let inner = self.inner.read();
let mut output: SmallVec<[ArcBytes; 1]> = SmallVec::new();
// Track whether we found the key in any SST (even if deleted).
// Used for miss_global stat: only fires if key was never found anywhere.
#[cfg(feature = "stats")]
let mut found_in_sst = false;
let mut size = 0;
for meta in inner.meta_files.iter().rev() {
match meta.lookup(
match meta.lookup::<K, FIND_ALL>(
family as u32,
hash,
key,
......@@ -1369,27 +1460,54 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
self.stats.miss_amqf.fetch_add(1, Ordering::Relaxed);
}
MetaLookupResult::SstLookup(result) => match result {
SstLookupResult::Found(result) => {
SstLookupResult::Found(values) => {
#[cfg(feature = "stats")]
{
found_in_sst = true;
}
inner.accessed_key_hashes[family].insert(hash);
match result {
LookupValue::Deleted => {
#[cfg(feature = "stats")]
self.stats.hits_deleted.fetch_add(1, Ordering::Relaxed);
span.record("result_size", "deleted");
return Ok(None);
}
LookupValue::Slice { value } => {
#[cfg(feature = "stats")]
self.stats.hits_small.fetch_add(1, Ordering::Relaxed);
span.record("result_size", value.len());
return Ok(Some(value));
}
LookupValue::Blob { sequence_number } => {
#[cfg(feature = "stats")]
self.stats.hits_blob.fetch_add(1, Ordering::Relaxed);
let blob = self.read_blob(sequence_number)?;
span.record("result_size", blob.len());
return Ok(Some(blob));
// Process values. Tombstones sort last within a key group,
// so when we see a tombstone, we can return immediately.
for value in values {
match value {
LookupValue::Deleted => {
#[cfg(feature = "stats")]
self.stats.hits_deleted.fetch_add(1, Ordering::Relaxed);
if !FIND_ALL {
span.record("result_size", "deleted");
return Ok(SmallVec::new());
}
// Tombstone is last in key group. Return accumulated
// values (from this SST and newer layers). Stop
// searching older SSTs.
if output.is_empty() {
span.record("result_size", "deleted");
} else {
span.record("result_size", size);
}
return Ok(output);
}
LookupValue::Slice { value } => {
#[cfg(feature = "stats")]
self.stats.hits_small.fetch_add(1, Ordering::Relaxed);
if !FIND_ALL {
span.record("result_size", value.len());
return Ok(SmallVec::from_buf([value]));
}
size += value.len();
output.push(value);
}
LookupValue::Blob { sequence_number } => {
#[cfg(feature = "stats")]
self.stats.hits_blob.fetch_add(1, Ordering::Relaxed);
let blob = self.read_blob(sequence_number)?;
if !FIND_ALL {
span.record("result_size", blob.len());
return Ok(SmallVec::from_buf([blob]));
}
size += blob.len();
output.push(blob);
}
}
}
}
......@@ -1400,10 +1518,21 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
},
}
}
#[cfg(feature = "stats")]
self.stats.miss_global.fetch_add(1, Ordering::Relaxed);
span.record("result_size", "not found");
Ok(None)
if !found_in_sst {
self.stats.miss_global.fetch_add(1, Ordering::Relaxed);
}
if FIND_ALL {
span.record("result_count", output.len());
}
if output.is_empty() {
span.record("result_size", "not_found");
} else {
span.record("result_size", size);
}
Ok(output)
}
pub fn batch_get<K: QueryKey>(
......@@ -1412,6 +1541,10 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
keys: &[K],
) -> Result<Vec<Option<ArcBytes>>> {
debug_assert!(family < FAMILIES, "Family index out of bounds");
if self.config.family_configs[family].kind != FamilyKind::SingleValue {
// This is an error in our caller so just panic
panic!("only single valued tables can be queried with `batch_get'")
}
let span = tracing::trace_span!(
"database batch read",
name = family,
......
......@@ -27,6 +27,45 @@ mod tests;
pub use arc_bytes::ArcBytes;
pub use db::{CompactConfig, MetaFileEntryInfo, MetaFileInfo, TurboPersistence};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FamilyKind {
/// Each key maps to a single value (default LSM behavior).
/// When multiple entries have the same key, only the newest is retained during compaction or
/// returned by queries
/// Access must use `get` not `get_multiple`
SingleValue,
/// Each key can map to multiple values.
/// Duplicate values are not dropped.
/// The order of values returned by `get_multiple` is undefined.
/// Access must use `get_multiple` not `get`
MultiValue,
}
/// Configuration for a single family to describe how the data is stored.
#[derive(Clone, Copy, Debug)]
pub struct FamilyConfig {
pub kind: FamilyKind,
}
/// Database-wide configuration with per-family settings.
///
/// Each family (keyspace) can have different file size limits to optimize
/// for its specific access patterns and data characteristics.
#[derive(Clone, Debug)]
pub struct DbConfig<const FAMILIES: usize> {
pub family_configs: [FamilyConfig; FAMILIES],
}
impl<const FAMILIES: usize> Default for DbConfig<FAMILIES> {
fn default() -> Self {
Self {
family_configs: [FamilyConfig {
kind: FamilyKind::SingleValue,
}; FAMILIES],
}
}
}
pub use key::{KeyBase, QueryKey, StoreKey, hash_key};
pub use meta_file::MetaEntryFlags;
pub use parallel_scheduler::{ParallelScheduler, SerialScheduler};
......
......@@ -5,6 +5,7 @@ use crate::{
};
/// A value from a SST file lookup.
#[derive(PartialEq)]
pub enum LookupValue {
/// The value was deleted.
Deleted,
......
......@@ -35,12 +35,13 @@ impl<T: Iterator<Item = Result<LookupEntry>>> Ord for Box<ActiveIterator<T>> {
.hash
.cmp(&other.entry.hash)
.then_with(|| (*self.entry.key).cmp(&other.entry.key))
.then_with(|| self.order.cmp(&other.order))
// Reverse order comparison to yield newest-first
.then_with(|| other.order.cmp(&self.order))
.reverse()
}
}
/// An iterator that merges multiple sorted iterators into a single sorted iterator. Internal it
/// An iterator that merges multiple sorted iterators into a single sorted iterator. Internally it
/// uses an heap of iterators to iterate them in order.
pub struct MergeIter<T: Iterator<Item = Result<LookupEntry>>> {
heap: BinaryHeap<Box<ActiveIterator<T>>>,
......
......@@ -13,6 +13,7 @@ use bincode::{Decode, Encode};
use bitfield::bitfield;
use byteorder::{BE, ReadBytesExt};
use memmap2::{Mmap, MmapOptions};
use smallvec::SmallVec;
use turbo_bincode::turbo_bincode_decode;
use crate::{
......@@ -374,7 +375,12 @@ impl MetaFile {
&self.obsolete_sst_files
}
pub fn lookup<K: QueryKey>(
/// Looks up a key in this meta file.
///
/// 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
/// (useful for keyspaces where keys are hashes and collisions are possible).
pub fn lookup<K: QueryKey, const FIND_ALL: bool>(
&self,
key_family: u32,
key_hash: u64,
......@@ -386,25 +392,54 @@ impl MetaFile {
return Ok(MetaLookupResult::FamilyMiss);
}
let mut miss_result = MetaLookupResult::RangeMiss;
let mut all_results: SmallVec<[LookupValue; 1]> = SmallVec::new();
for entry in self.entries.iter().rev() {
if key_hash < entry.min_hash || key_hash > entry.max_hash {
continue;
}
{
let amqf = entry.amqf(self)?;
if !amqf.contains_fingerprint(key_hash) {
miss_result = MetaLookupResult::QuickFilterMiss;
continue;
}
let amqf = entry.amqf(self)?;
if !amqf.contains_fingerprint(key_hash) {
miss_result = MetaLookupResult::QuickFilterMiss;
continue;
}
let result =
entry
.sst(self)?
.lookup(key_hash, key, key_block_cache, value_block_cache)?;
if !matches!(result, SstLookupResult::NotFound) {
return Ok(MetaLookupResult::SstLookup(result));
let result = entry.sst(self)?.lookup::<K, FIND_ALL>(
key_hash,
key,
key_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)));
}
// Check for tombstone — stops search across older SSTs within this meta file.
// Since tombstones sort last within a key group, if the last value is Deleted,
// we have a tombstone.
let has_tombstone = values.last().is_some_and(|v| *v == LookupValue::Deleted);
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)
}
......@@ -479,13 +514,18 @@ impl MetaFile {
}
continue;
}
let sst_result = entry.sst(self)?.lookup(
let sst_result = entry.sst(self)?.lookup::<_, false>(
*hash,
&keys[*index],
key_block_cache,
value_block_cache,
)?;
if let SstLookupResult::Found(value) = sst_result {
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")]
......
......@@ -11,6 +11,7 @@ use byteorder::{BE, ReadBytesExt};
use memmap2::Mmap;
use quick_cache::sync::GuardResult;
use rustc_hash::FxHasher;
use smallvec::SmallVec;
use crate::{
QueryKey,
......@@ -47,15 +48,15 @@ const _: () = assert!(
/// The result of a lookup operation.
pub enum SstLookupResult {
/// The key was found.
Found(LookupValue),
/// One or more values were found.
Found(SmallVec<[LookupValue; 1]>),
/// The key was not found.
NotFound,
}
impl From<LookupValue> for SstLookupResult {
fn from(value: LookupValue) -> Self {
SstLookupResult::Found(value)
SstLookupResult::Found(smallvec::smallvec![value])
}
}
......@@ -198,7 +199,11 @@ impl StaticSortedFile {
}
/// Looks up a key in this file.
pub fn lookup<K: QueryKey>(
///
/// If `FIND_ALL` is false, returns after finding the first match.
/// If `FIND_ALL` is true, returns all entries with the same key (useful for
/// keyspaces where keys are hashes and collisions are possible).
pub fn lookup<K: QueryKey, const FIND_ALL: bool>(
&self,
key_hash: u64,
key: &K,
......@@ -215,7 +220,7 @@ impl StaticSortedFile {
}
BLOCK_TYPE_KEY_WITH_HASH | BLOCK_TYPE_KEY_NO_HASH => {
let has_hash = block_type == BLOCK_TYPE_KEY_WITH_HASH;
return self.lookup_key_block(
return self.lookup_key_block::<K, FIND_ALL>(
key_block_arc,
key_hash,
key,
......@@ -277,7 +282,10 @@ impl StaticSortedFile {
}
/// Looks up a key in a key block and the value in a value block.
fn lookup_key_block<K: QueryKey>(
///
/// If `FIND_ALL` is false, returns after finding the first match.
/// If `FIND_ALL` is true, collects all entries with the same key.
fn lookup_key_block<K: QueryKey, const FIND_ALL: bool>(
&self,
mut block: ArcBytes,
key_hash: u64,
......@@ -292,32 +300,73 @@ impl StaticSortedFile {
let mut l = 0;
let mut r = entry_count;
// binary search for the key
// binary search for a matching key
while l < r {
let m = (l + r) / 2;
let GetKeyEntryResult {
hash: mid_hash,
key: mid_key,
ty,
val: mid_val,
val,
} = get_key_entry(offsets, entries, entry_count, m, hash_len)?;
let comparison = compare_hash_key(mid_hash, mid_key, key_hash, key);
match comparison {
Ordering::Less => {
r = m;
}
Ordering::Less => r = m,
Ordering::Equal => {
return Ok(self
.handle_key_match(ty, mid_val, &block, value_block_cache)?
.into());
}
Ordering::Greater => {
l = m + 1;
if !FIND_ALL {
// SingleValue mode: each key has exactly one entry
// this is enforced when writing
let result = self.handle_key_match(ty, val, &block, value_block_cache)?;
return Ok(SstLookupResult::Found(SmallVec::from_buf([result])));
}
// FIND_ALL (MultiValue) mode: collect all values for this key.
// Tombstones (Deleted) sort last within each key group, so we
// scan backward to find the start of the key group, then forward
// to collect all entries. The tombstone, if present, will be the
// last entry in the results.
let mut results = SmallVec::new();
// Backward scan: collect all entries before `m` with the same key
for i in (0..m).rev() {
let GetKeyEntryResult {
hash,
key: entry_key,
ty,
val,
} = get_key_entry(offsets, entries, entry_count, i, hash_len)?;
if compare_hash_key(hash, entry_key, key_hash, key) != Ordering::Equal {
break;
}
results.push(self.handle_key_match(ty, val, &block, value_block_cache)?);
}
// Technically we could `.reverse()` the items collected by the backwards scan,
// but the only ordering constraint we need to maintain for single sst
// multivalue reads is that a deleted token, if it exists comes last. Because
// all the backwards scan items are strictly before the found item we know they
// don't contain the _last_ item. So we don't care about their order
// Add the entry at `m`
results.push(self.handle_key_match(ty, val, &block, value_block_cache)?);
// Forward scan: collect remaining entries with the same key
for i in (m + 1)..entry_count {
let GetKeyEntryResult {
hash,
key: entry_key,
ty,
val,
} = get_key_entry(offsets, entries, entry_count, i, hash_len)?;
if compare_hash_key(hash, entry_key, key_hash, key) != Ordering::Equal {
break;
}
results.push(self.handle_key_match(ty, val, &block, value_block_cache)?);
}
return Ok(SstLookupResult::Found(results));
}
Ordering::Greater => l = m + 1,
}
}
Ok(SstLookupResult::NotFound)
}
......
......@@ -1206,9 +1206,14 @@ mod tests {
kc: &TestBlockCache,
vc: &TestBlockCache,
) -> Result<()> {
let result = sst.lookup(entry.hash, &entry.key, kc, vc)?;
let result = sst.lookup::<_, false>(entry.hash, &entry.key, kc, vc)?;
match (&entry.value_kind, result) {
(_, SstLookupResult::Found(LookupValue::Slice { value })) => {
(_, SstLookupResult::Found(values))
if values.len() == 1 && matches!(values[0], LookupValue::Slice { .. }) =>
{
let LookupValue::Slice { value } = &values[0] else {
unreachable!()
};
let expected = entry
.expected_value()
.expect("Got Slice but entry has no value");
......@@ -1219,13 +1224,16 @@ mod tests {
std::str::from_utf8(&entry.key)
);
}
(
TestValueKind::Blob(expected_id),
SstLookupResult::Found(LookupValue::Blob { sequence_number }),
) => {
assert_eq!(sequence_number, *expected_id);
(TestValueKind::Blob(expected_id), SstLookupResult::Found(values))
if values.len() == 1 && matches!(values[0], LookupValue::Blob { .. }) =>
{
let LookupValue::Blob { sequence_number } = &values[0] else {
unreachable!()
};
assert_eq!(*sequence_number, *expected_id);
}
(TestValueKind::Deleted, SstLookupResult::Found(LookupValue::Deleted)) => {}
(TestValueKind::Deleted, SstLookupResult::Found(values))
if values.len() == 1 && matches!(values[0], LookupValue::Deleted) => {}
_ => {
panic!(
"Unexpected lookup result for key {:?}",
......@@ -1507,33 +1515,40 @@ mod tests {
let vc = make_cache();
for entry in &entries {
let r1 = sst1.lookup(entry.hash, &entry.key, &kc, &vc)?;
let r2 = sst2.lookup(entry.hash, &entry.key, &kc, &vc)?;
match (r1, r2) {
(
SstLookupResult::Found(LookupValue::Slice { value: v1 }),
SstLookupResult::Found(LookupValue::Slice { value: v2 }),
) => {
assert_eq!(
v1.as_ref(),
v2.as_ref(),
"Value mismatch for key {:?}",
std::str::from_utf8(&entry.key)
);
}
(
SstLookupResult::Found(LookupValue::Deleted),
SstLookupResult::Found(LookupValue::Deleted),
) => {}
(
SstLookupResult::Found(LookupValue::Blob {
sequence_number: s1,
}),
SstLookupResult::Found(LookupValue::Blob {
sequence_number: s2,
}),
) => {
assert_eq!(s1, s2);
let r1 = sst1.lookup::<_, false>(entry.hash, &entry.key, &kc, &vc)?;
let r2 = sst2.lookup::<_, false>(entry.hash, &entry.key, &kc, &vc)?;
match (&r1, &r2) {
(SstLookupResult::Found(v1), SstLookupResult::Found(v2))
if v1.len() == 1 && v2.len() == 1 =>
{
match (&v1[0], &v2[0]) {
(
LookupValue::Slice { value: val1 },
LookupValue::Slice { value: val2 },
) => {
assert_eq!(
val1.as_ref(),
val2.as_ref(),
"Value mismatch for key {:?}",
std::str::from_utf8(&entry.key)
);
}
(LookupValue::Deleted, LookupValue::Deleted) => {}
(
LookupValue::Blob {
sequence_number: s1,
},
LookupValue::Blob {
sequence_number: s2,
},
) => {
assert_eq!(s1, s2);
}
_ => panic!(
"Mismatched results for key {:?}",
std::str::from_utf8(&entry.key)
),
}
}
_ => panic!(
"Mismatched results for key {:?}",
......
......@@ -4,6 +4,7 @@ use anyhow::Result;
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use crate::{
DbConfig, FamilyConfig, FamilyKind,
constants::{MAX_MEDIUM_VALUE_SIZE, MAX_SMALL_VALUE_SIZE},
db::{CompactConfig, TurboPersistence},
parallel_scheduler::ParallelScheduler,
......@@ -132,18 +133,18 @@ fn full_cycle() -> Result<()> {
"Simple",
|batch| {
for i in 10..100u8 {
batch.put(0, vec![i], vec![i].into())?;
batch.put(0, vec![1, i], vec![i].into())?;
}
Ok(())
},
|db| {
let Some(value) = db.get(0, &[42u8])? else {
let Some(value) = db.get(0, &[1, 42u8])? else {
panic!("Value not found");
};
assert_eq!(&*value, &[42]);
assert_eq!(db.get(0, &[42u8, 42])?, None);
assert_eq!(db.get(0, &[1u8])?, None);
assert_eq!(db.get(0, &[255u8])?, None);
assert_eq!(db.get(0, &[1, 42u8, 42])?, None);
assert_eq!(db.get(0, &[1, 1u8])?, None);
assert_eq!(db.get(0, &[1, 255u8])?, None);
Ok(())
},
);
......@@ -153,19 +154,19 @@ fn full_cycle() -> Result<()> {
"Many SST files",
|batch| {
for i in 10..100u8 {
batch.put(0, vec![i], vec![i].into())?;
batch.put(0, vec![2, i], vec![i].into())?;
unsafe { batch.flush(0)? };
}
Ok(())
},
|db| {
let Some(value) = db.get(0, &[42u8])? else {
let Some(value) = db.get(0, &[2, 42u8])? else {
panic!("Value not found");
};
assert_eq!(&*value, &[42]);
assert_eq!(db.get(0, &[42u8, 42])?, None);
assert_eq!(db.get(0, &[1u8])?, None);
assert_eq!(db.get(0, &[255u8])?, None);
assert_eq!(db.get(0, &[2, 42u8, 42])?, None);
assert_eq!(db.get(0, &[2, 1u8])?, None);
assert_eq!(db.get(0, &[2, 255u8])?, None);
Ok(())
},
);
......@@ -196,13 +197,17 @@ fn full_cycle() -> Result<()> {
"Medium keys and values",
|batch| {
for i in 0..200u8 {
batch.put(0, vec![i; 10 * 1024], vec![i; 100 * 1024].into())?;
let mut key = vec![3u8];
key.extend(vec![i; 10 * 1024]);
batch.put(0, key, vec![i; 100 * 1024].into())?;
}
Ok(())
},
|db| {
for i in 0..200u8 {
let Some(value) = db.get(0, &vec![i; 10 * 1024])? else {
let mut key = vec![3u8];
key.extend(vec![i; 10 * 1024]);
let Some(value) = db.get(0, &key)? else {
panic!("Value not found");
};
assert_eq!(&*value, &vec![i; 100 * 1024]);
......@@ -221,17 +226,21 @@ fn full_cycle() -> Result<()> {
"Large keys and values (blob files)",
|batch| {
for i in 0..2u8 {
batch.put(0, vec![i; BLOB_SIZE], vec![i; BLOB_SIZE].into())?;
let mut key = vec![4u8];
key.extend(vec![i; BLOB_SIZE]);
batch.put(0, key, vec![i; BLOB_SIZE].into())?;
}
Ok(())
},
|db| {
for i in 0..2u8 {
let key_and_value = vec![i; BLOB_SIZE];
let Some(value) = db.get(0, &key_and_value)? else {
let mut key = vec![4u8];
key.extend(vec![i; BLOB_SIZE]);
let value_expected = vec![i; BLOB_SIZE];
let Some(value) = db.get(0, &key)? else {
panic!("Value not found");
};
assert_eq!(&*value, &key_and_value);
assert_eq!(&*value, &value_expected);
}
Ok(())
},
......@@ -245,13 +254,17 @@ fn full_cycle() -> Result<()> {
"Different sizes keys and values",
|batch| {
for i in different_sizes_range() {
batch.put(0, vec![i; i as usize], vec![i; i as usize].into())?;
let mut key = vec![5u8];
key.extend(vec![i; i as usize]);
batch.put(0, key, vec![i; i as usize].into())?;
}
Ok(())
},
|db| {
for i in different_sizes_range() {
let Some(value) = db.get(0, &vec![i; i as usize])? else {
let mut key = vec![5u8];
key.extend(vec![i; i as usize]);
let Some(value) = db.get(0, &key)? else {
panic!("Value not found");
};
assert_eq!(&*value, &vec![i; i as usize]);
......@@ -265,14 +278,16 @@ fn full_cycle() -> Result<()> {
"Many items (1% read)",
|batch| {
for i in 0..1000 * 1024u32 {
batch.put(0, i.to_be_bytes().into(), i.to_be_bytes().to_vec().into())?;
let key = [&[6u8], &i.to_be_bytes()[..]].concat();
batch.put(0, key, i.to_be_bytes().to_vec().into())?;
}
Ok(())
},
|db| {
for i in 0..10 * 1024u32 {
let i = i * 100;
let Some(value) = db.get(0, &i.to_be_bytes())? else {
let key = [&[6u8], &i.to_be_bytes()[..]].concat();
let Some(value) = db.get(0, &key)? else {
panic!("Value not found");
};
assert_eq!(&*value, &i.to_be_bytes());
......@@ -286,16 +301,16 @@ fn full_cycle() -> Result<()> {
"Many items (1% read, multi-threaded)",
|batch| {
(0..10 * 1024 * 1024u32).into_par_iter().for_each(|i| {
batch
.put(0, i.to_be_bytes().into(), i.to_be_bytes().to_vec().into())
.unwrap();
let key = [&[7u8], &i.to_be_bytes()[..]].concat();
batch.put(0, key, i.to_be_bytes().to_vec().into()).unwrap();
});
Ok(())
},
|db| {
(0..100 * 1024u32).into_par_iter().for_each(|i| {
let i = i * 100;
let Some(value) = db.get(0, &i.to_be_bytes()).unwrap() else {
let key = [&[7u8], &i.to_be_bytes()[..]].concat();
let Some(value) = db.get(0, &key).unwrap() else {
panic!("Value not found");
};
assert_eq!(&*value, &i.to_be_bytes());
......@@ -1448,3 +1463,508 @@ fn many_medium_values_compaction() -> Result<()> {
db.shutdown()?;
Ok(())
}
#[test]
fn compaction_multi_value_preserves_different_values() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let config = multi_value_config();
let key = vec![42u8];
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config,
RayonParallelScheduler,
)?;
// Write same key with different values in separate batches
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![1u8].into())?;
db.commit_write_batch(batch)?;
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![2u8].into())?;
db.commit_write_batch(batch)?;
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![3u8].into())?;
db.commit_write_batch(batch)?;
// Before compaction: all 3 values exist
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(results.len(), 3, "Should have 3 values before compaction");
// Compact with MultiValue mode
db.full_compact()?;
// After compaction: all different values should be preserved
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(
results.len(),
3,
"MultiValue should preserve all different values after compaction"
);
let mut values: Vec<u8> = results.iter().map(|r| r[0]).collect();
values.sort();
assert_eq!(values, vec![1, 2, 3], "All values should be preserved");
db.shutdown()?;
}
Ok(())
}
fn multi_value_config() -> DbConfig<1> {
let mut config = DbConfig::<1>::default();
config.family_configs[0] = FamilyConfig {
kind: FamilyKind::MultiValue,
};
config
}
#[test]
fn compaction_multi_value_multiple_compactions() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let config = multi_value_config();
let key = vec![42u8];
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config.clone(),
RayonParallelScheduler,
)?;
// Write initial values
for value in [1u8, 2, 3] {
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![value].into())?;
db.commit_write_batch(batch)?;
}
db.full_compact()?;
// After first compaction: 3 unique values
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(results.len(), 3);
// Add more values (some duplicates of existing values)
for value in [2u8, 4, 1] {
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![value].into())?;
db.commit_write_batch(batch)?;
}
// Before second compaction: all 6 entries present (no dedup)
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(results.len(), 6);
// Second compaction
db.full_compact()?;
// After second compaction: all 6 entries preserved (no dedup)
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(
results.len(),
6,
"Should have all 6 values after second compaction (no dedup)"
);
let mut values: Vec<u8> = results.iter().map(|r| r[0]).collect();
values.sort();
assert_eq!(
values,
vec![1, 1, 2, 2, 3, 4],
"Should have values 1, 1, 2, 2, 3, 4"
);
db.shutdown()?;
}
// Reopen and verify persistence
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config,
RayonParallelScheduler,
)?;
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(results.len(), 6, "Should still have 6 values after reopen");
db.shutdown()?;
}
Ok(())
}
#[test]
fn multi_value_delete_key() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let config = multi_value_config();
let key = vec![42u8];
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config.clone(),
RayonParallelScheduler,
)?;
// Write multiple values for the same key across separate batches
for value in [1u8, 2, 3] {
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![value].into())?;
db.commit_write_batch(batch)?;
}
// Verify all values are present
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(results.len(), 3, "Should have 3 values before deletion");
// Delete the key
let batch = db.write_batch()?;
batch.delete(0, key.clone())?;
db.commit_write_batch(batch)?;
// Verify deleted
let results = db.get_multiple(0, &key.as_slice())?;
assert!(
results.is_empty(),
"get_multiple should return empty after delete"
);
// Compact and verify still deleted
db.full_compact()?;
let results = db.get_multiple(0, &key.as_slice())?;
assert!(
results.is_empty(),
"get_multiple should return empty after compaction"
);
db.shutdown()?;
}
// Reopen and verify deletion persists
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config,
RayonParallelScheduler,
)?;
let results = db.get_multiple(0, &key.as_slice())?;
assert!(
results.is_empty(),
"get_multiple should return empty after reopen"
);
db.shutdown()?;
}
Ok(())
}
#[test]
fn multi_value_delete_then_rewrite() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let config = multi_value_config();
let key = vec![42u8];
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config.clone(),
RayonParallelScheduler,
)?;
// Write initial values
for value in [1u8, 2, 3] {
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![value].into())?;
db.commit_write_batch(batch)?;
}
// Delete the key
let batch = db.write_batch()?;
batch.delete(0, key.clone())?;
db.commit_write_batch(batch)?;
let results = db.get_multiple(0, &key.as_slice())?;
assert!(results.is_empty(), "Should be deleted");
// Write new values for the same key
for value in [10u8, 20] {
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![value].into())?;
db.commit_write_batch(batch)?;
}
// Only the new values should be visible — old values must not reappear
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(results.len(), 2, "Should have only the 2 new values");
let mut values: Vec<u8> = results.iter().map(|r| r[0]).collect();
values.sort();
assert_eq!(values, vec![10, 20], "Should have only new values 10, 20");
// After compaction, the tombstone prunes old values; only new values remain
db.full_compact()?;
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(
results.len(),
2,
"Should still have 2 values after compaction"
);
let mut values: Vec<u8> = results.iter().map(|r| r[0]).collect();
values.sort();
assert_eq!(
values,
vec![10, 20],
"Should still have values 10, 20 after compaction"
);
db.shutdown()?;
}
// Reopen and verify
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config,
RayonParallelScheduler,
)?;
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(results.len(), 2, "Should have 2 values after reopen");
let mut values: Vec<u8> = results.iter().map(|r| r[0]).collect();
values.sort();
assert_eq!(
values,
vec![10, 20],
"Should have values 10, 20 after reopen"
);
db.shutdown()?;
}
Ok(())
}
#[test]
fn multi_value_delete_with_compaction_interleaved() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let config = multi_value_config();
let key = vec![42u8];
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config.clone(),
RayonParallelScheduler,
)?;
// Write values 1, 2
for value in [1u8, 2] {
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![value].into())?;
db.commit_write_batch(batch)?;
}
// Compact — values 1, 2 are now in a compacted SST
db.full_compact()?;
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(
results.len(),
2,
"Should have 2 values after first compaction"
);
// Write value 3 (new SST on top of compacted data)
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![3u8].into())?;
db.commit_write_batch(batch)?;
// Delete the key
let batch = db.write_batch()?;
batch.delete(0, key.clone())?;
db.commit_write_batch(batch)?;
// Verify deleted
let results = db.get_multiple(0, &key.as_slice())?;
assert!(results.is_empty(), "Should be deleted");
// Compact again — merges everything
db.full_compact()?;
// After compaction, the tombstone prunes all values — key appears empty
let results = db.get_multiple(0, &key.as_slice())?;
assert!(
results.is_empty(),
"get_multiple should return empty after compaction"
);
// Write new value 4 — visible because it goes into a newer SST than the tombstone
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![4u8].into())?;
db.commit_write_batch(batch)?;
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(results.len(), 1, "Should have only value 4");
assert_eq!(results[0].as_ref(), &[4u8]);
db.shutdown()?;
}
// Reopen and verify
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config,
RayonParallelScheduler,
)?;
let results = db.get_multiple(0, &key.as_slice())?;
assert_eq!(results.len(), 1, "Should have only value 4 after reopen");
assert_eq!(results[0].as_ref(), &[4u8]);
db.shutdown()?;
}
Ok(())
}
// Tests for the new WriteBatch semantics:
// - SingleValue: duplicate keys in the same batch is a user error (panics in debug builds)
// - MultiValue: tombstone only shadows entries from older SSTs, not entries in the same batch
#[test]
#[cfg(debug_assertions)]
#[should_panic(expected = "WriteBatch invariant violation: SingleValue family has duplicate key")]
fn single_value_duplicate_key_panics() {
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path();
// For SingleValue, writing the same key twice in one batch should panic in debug builds.
let key = vec![1u8];
let db = TurboPersistence::<_, 1>::open_with_parallel_scheduler(
path.to_path_buf(),
RayonParallelScheduler,
)
.unwrap();
let batch = db.write_batch().unwrap();
batch.put(0, key.clone(), vec![10u8].into()).unwrap();
batch.put(0, key.clone(), vec![20u8].into()).unwrap(); // should panic
db.commit_write_batch(batch).unwrap(); // panics during commit
}
#[test]
fn multi_value_tombstone_only_shadows_older_ssts() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let config = multi_value_config();
// For MultiValue, a tombstone only shadows entries from older SSTs.
// Entries in the same batch are NOT shadowed by the tombstone.
let key = vec![3u8];
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config.clone(),
RayonParallelScheduler,
)?;
// First write an older value in a separate batch (separate SST)
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![99u8].into())?;
db.commit_write_batch(batch)?;
// Now in a single batch: put(A), delete, put(B)
// With the new semantics:
// - The tombstone shadows the older SST (99)
// - Entries in the same batch (A=10 and B=20) are preserved
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![10u8].into())?;
batch.delete(0, key.clone())?;
batch.put(0, key.clone(), vec![20u8].into())?;
db.commit_write_batch(batch)?;
let results = db.get_multiple(0, &key.as_slice())?;
// Should have both values from the same batch (10 and 20), but not 99
// The tombstone shadows the older SST but not the same-batch entries
assert_eq!(
results.len(),
2,
"Should have 2 values (both from same batch), got {:?}",
results
);
db.shutdown()?;
}
Ok(())
}
#[test]
fn multi_value_tombstone_shadows_older_sst_only() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let config = multi_value_config();
// For MultiValue, tombstone in a batch shadows only entries from older SSTs.
let key = vec![4u8];
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
config.clone(),
RayonParallelScheduler,
)?;
// Write an older value in a separate batch
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![99u8].into())?;
db.commit_write_batch(batch)?;
// Now in a single batch: put(A), put(B), delete
// The tombstone shadows the older SST (99), but A (10) and B (20) are preserved.
let batch = db.write_batch()?;
batch.put(0, key.clone(), vec![10u8].into())?;
batch.put(0, key.clone(), vec![20u8].into())?;
batch.delete(0, key.clone())?;
db.commit_write_batch(batch)?;
let results = db.get_multiple(0, &key.as_slice())?;
// Should have both values from the same batch (10 and 20), but not 99
assert_eq!(
results.len(),
2,
"Should have 2 values (both from same batch, tombstone shadows older SST), got {:?}",
results
);
db.shutdown()?;
}
Ok(())
}
......@@ -15,7 +15,7 @@ use smallvec::SmallVec;
use thread_local::ThreadLocal;
use crate::{
ValueBuffer,
FamilyConfig, ValueBuffer,
collector::Collector,
collector_entry::CollectorEntry,
compression::compress_into_buffer,
......@@ -71,6 +71,9 @@ pub struct WriteBatch<K: StoreKey + Send, S: ParallelScheduler, const FAMILIES:
parallel_scheduler: S,
/// The database path
db_path: PathBuf,
/// Per-family configuration (kind: SingleValue/MultiValue).
#[cfg_attr(not(feature = "verify_sst_content"), allow(dead_code))]
family_configs: [FamilyConfig; FAMILIES],
/// The current sequence number counter. Increased for every new SST file or blob file.
current_sequence_number: AtomicU32,
/// The thread local state.
......@@ -87,14 +90,20 @@ pub struct WriteBatch<K: StoreKey + Send, S: ParallelScheduler, const FAMILIES:
impl<K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
WriteBatch<K, S, FAMILIES>
{
/// Creates a new write batch for a database.
pub(crate) fn new(path: PathBuf, current: u32, parallel_scheduler: S) -> Self {
/// Creates a new write batch for a database with per-family configuration.
pub(crate) fn new(
path: PathBuf,
current: u32,
parallel_scheduler: S,
family_configs: [FamilyConfig; FAMILIES],
) -> Self {
const {
assert!(FAMILIES <= usize_from_u32(u32::MAX));
};
Self {
parallel_scheduler,
db_path: path,
family_configs,
current_sequence_number: AtomicU32::new(current),
thread_locals: ThreadLocal::new(),
collectors: [(); FAMILIES]
......@@ -195,7 +204,10 @@ impl<K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
// driving the work to slow down task submission in this case.
for mut global_collector in full_collectors {
// When the global collector is full, we create a new SST file.
let sst = self.create_sst_file(family, global_collector.sorted())?;
let sst = self.create_sst_file(
family,
global_collector.sorted(self.family_configs[usize_from_u32(family)].kind),
)?;
self.new_sst_files.lock().push(sst);
drop(global_collector);
}
......@@ -256,7 +268,10 @@ impl<K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
match &mut *collector_state {
GlobalCollectorState::Unsharded(collector) => {
if !collector.is_empty() {
let sst = self.create_sst_file(family, collector.sorted())?;
let sst = self.create_sst_file(
family,
collector.sorted(self.family_configs[usize_from_u32(family)].kind),
)?;
collector.clear();
self.new_sst_files.lock().push(sst);
}
......@@ -271,7 +286,10 @@ impl<K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
self.parallel_scheduler
.try_parallel_for_each_mut(&mut shards, |collector| {
if !collector.is_empty() {
let sst = self.create_sst_file(family, collector.sorted())?;
let sst = self.create_sst_file(
family,
collector.sorted(self.family_configs[usize_from_u32(family)].kind),
)?;
collector.clear();
self.new_sst_files.lock().push(sst);
collector.drop_contents();
......@@ -356,7 +374,10 @@ impl<K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
|(family, mut collector)| {
let family = family as u32;
if !collector.is_empty() {
let sst = self.create_sst_file(family, collector.sorted())?;
let sst = self.create_sst_file(
family,
collector.sorted(self.family_configs[usize_from_u32(family)].kind),
)?;
collector.clear();
drop(collector);
shared_new_sst_files.lock().push(sst);
......@@ -479,25 +500,52 @@ impl<K: StoreKey + Send + Sync, S: ParallelScheduler, const FAMILIES: usize>
Default::default(),
);
let mut key_buf = Vec::new();
let family_config = self.family_configs[usize_from_u32(family)].kind;
for entry in entries {
entry.write_key_to(&mut key_buf);
let result = sst
.lookup(hash_key(&key_buf), &key_buf, &cache2, &cache3)
.lookup::<_, true>(hash_key(&key_buf), &key_buf, &cache2, &cache3)
.expect("key found");
key_buf.clear();
match result {
SstLookupResult::Found(LookupValue::Deleted) => {}
SstLookupResult::Found(LookupValue::Slice {
value: lookup_value,
}) => {
let expected_value_slice = match &entry.value {
CollectorEntryValue::Small { value } => &**value,
CollectorEntryValue::Medium { value } => &**value,
_ => panic!("Unexpected value"),
};
assert_eq!(*lookup_value, *expected_value_slice);
SstLookupResult::Found(values) => {
if values.len() > 1 {
use crate::FamilyKind;
assert!(
values.len() == 1 || family_config == FamilyKind::MultiValue,
"only multi-value tables can have more than one value, got {} \
values",
values.len()
)
}
match &entry.value {
CollectorEntryValue::Large { blob } => {
assert!(
values.contains(&LookupValue::Blob {
sequence_number: *blob
}),
"we wrote a blob but did not read it"
);
}
CollectorEntryValue::Deleted => assert!(
values.first() == Some(&LookupValue::Deleted),
"we wrote a deleted tombstone but it was not first in results"
),
v => {
assert!(
values.into_iter().any(|lv| {
if let LookupValue::Slice { value } = lv {
&*value == v.as_bytes().unwrap()
} else {
false
}
}),
"we wrote a slice of bytes but did not read it"
)
}
}
}
SstLookupResult::Found(LookupValue::Blob { sequence_number: _ }) => {}
SstLookupResult::NotFound => panic!("All keys must exist"),
}
}
......
......@@ -6,6 +6,7 @@ use std::{
};
use anyhow::{Context, Result};
use rustc_hash::FxHashSet;
use turbo_bincode::{
TurboBincodeBuffer, new_turbo_bincode_decoder, turbo_bincode_decode, turbo_bincode_encode,
turbo_bincode_encode_into,
......@@ -311,6 +312,7 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
|updates| {
let _span = _span.clone().entered();
let mut max_task_id = 0;
let mut seen = FxHashSet::default();
// Re-use the same buffer across every `serialize_task_type` call in
// this chunk. `ConcurrentWriteBatch::put` will copy the data out of
......@@ -318,6 +320,9 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
let mut task_type_bytes =
TurboBincodeBuffer::with_capacity(INITIAL_ENCODE_BUFFER_CAPACITY);
for (task_type, task_id) in updates {
if !seen.insert(task_id) {
continue;
}
task_type_bytes.clear();
encode_task_type(&task_type, &mut task_type_bytes, Some(task_id))?;
let task_id: u32 = *task_id;
......@@ -401,7 +406,11 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
// smaller exact-sized vecs.
let mut task_type_bytes =
TurboBincodeBuffer::with_capacity(INITIAL_ENCODE_BUFFER_CAPACITY);
let mut seen = FxHashSet::default();
for (task_type, task_id) in task_cache_updates.into_iter().flatten() {
if !seen.insert(task_id) {
continue;
}
encode_task_type(&task_type, &mut task_type_bytes, Some(task_id))?;
let task_id = *task_id;
......
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