Unverified Commit e4b54a10 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Address persistence cleanup review feedback

Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 4f67421d
......@@ -13,8 +13,8 @@ use rand::{RngExt, SeedableRng, rngs::SmallRng, seq::SliceRandom};
use tempfile::TempDir;
use turbo_persistence::{
ArcBytes, BlockCache, CompactConfig, Compression, DbConfig as TpDbConfig, Entry, EntryValue,
FamilyConfig, FamilyKind, MetaEntryFlags, SerialScheduler, StaticSortedFile,
StaticSortedFileMetaData, TurboPersistence, hash_key, write_static_stored_file,
FamilyConfig, MetaEntryFlags, SerialScheduler, StaticSortedFile, StaticSortedFileMetaData,
TurboPersistence, hash_key, write_static_stored_file,
};
use turbo_tasks_malloc::TurboMalloc;
......@@ -597,252 +597,6 @@ 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)]
#[cfg(any())]
struct RemovedSetModeDbConfig {
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
#[cfg(any())]
fn prefill_multi_value_database(
path: &Path,
config: &RemovedSetModeDbConfig,
) -> Result<Vec<Box<[u8]>>> {
let db_config = TpDbConfig {
family_configs: [FamilyConfig {
name: "test",
kind: FamilyKind::SingleValue,
compression: Compression::Lz4,
}],
..TpDbConfig::new()
};
let db =
TurboPersistence::<SerialScheduler, 1>::open_with_config(path.to_path_buf(), db_config)?;
let mut rng = SmallRng::seed_from_u64(42);
let entry_count = scaled(config.entry_count);
let distinct_key_count = scaled(config.distinct_key_count);
// Generate all distinct keys up front.
let max_stored_keys =
distinct_key_count.min(MAX_KEY_MEMORY / (config.key_size + size_of::<Box<[u8]>>()));
let mut keys = unique_keys(&mut rng, config.key_size, max_stored_keys);
let entries_per_commit = 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 {
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
#[cfg(any())]
fn setup_prefilled_multi_value_db(
config: &RemovedSetModeDbConfig,
id: &str,
) -> Result<(TempDir, Vec<Box<[u8]>>)> {
let tempdir = tempfile::tempdir()?;
let keys = prefill_multi_value_database(tempdir.path(), config)?;
let entry_count = scaled(config.entry_count);
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 / entry_count),
(db_size as usize * 100 / (entry_count * (config.key_size + config.value_size)))
);
Ok((tempdir, keys))
}
#[cfg(any())]
fn open_multi_value_db(path: &Path) -> TurboPersistence<SerialScheduler, 1> {
let db_config = TpDbConfig {
family_configs: [FamilyConfig {
name: "test",
kind: FamilyKind::SingleValue,
compression: Compression::Lz4,
}],
..TpDbConfig::new()
};
TurboPersistence::<SerialScheduler, 1>::open_with_config(path.to_path_buf(), db_config).unwrap()
}
#[cfg(any())]
fn bench_read_get(c: &mut Criterion) {
let mut group = c.benchmark_group("read/get");
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 = RemovedSetModeDbConfig {
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(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(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(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(0, key).unwrap();
black_box(result)
},
BatchSize::NumBatches(1),
);
});
}
}
group.finish();
}
// =============================================================================
// Compaction Benchmarks
// =============================================================================
......@@ -865,7 +619,6 @@ fn bench_family_sharding(c: &mut Criterion) {
family_configs: ["family-0", "family-1", "family-2", "family-3"].map(|name| {
FamilyConfig {
name,
kind: FamilyKind::SingleValue,
compression: Compression::Lz4,
}
}),
......@@ -1004,142 +757,6 @@ fn bench_compaction(c: &mut Criterion) {
group.finish();
}
// =============================================================================
// Write Benchmarks - Multi-Value
// =============================================================================
#[cfg(any())]
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 {
// `id` uses the configured size so real-run reports are unaffected; the scaled
// counts bound the actual work unless `LARGE_DB` is set.
let full_entry_count = database_size / (key_size + value_size);
let entry_count = scaled(full_entry_count);
let distinct_key_count = (entry_count / values_per_key).max(1);
let id = format!(
"key_{}/value_{}/entries_{}/vpk_{}",
format_number(key_size),
format_number(value_size),
format_number(full_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 (unique) keys to keep the true distinct count exact.
let keys = unique_keys(&mut rng, key_size, distinct_key_count);
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 {
name: "test",
kind: FamilyKind::SingleValue,
compression: Compression::Lz4,
}],
..TpDbConfig::new()
};
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
// =============================================================================
#[cfg(any())]
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 = RemovedSetModeDbConfig {
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
// =============================================================================
......
......@@ -25,7 +25,6 @@ use nohash_hasher::BuildNoHashHasher;
use parking_lot::{Mutex, RwLock};
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use tracing::span::EnteredSpan;
pub use crate::compaction::selector::CompactConfig;
#[cfg(feature = "mmap")]
......@@ -2030,15 +2029,6 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
result_size = tracing::field::Empty
)
.entered();
self.get_impl(family, key, &span)
}
fn get_impl<K: QueryKey>(
&self,
family: usize,
key: &K,
span: &EnteredSpan,
) -> Result<Option<ArcBytes>> {
let hash = hash_key(key);
let inner = self.inner.read();
// Track whether we found the key in any SST (even if deleted).
......
......@@ -118,53 +118,36 @@ impl<T: KeyBase> KeyBase for &'_ T {
/// comparison with a byte slice (total order).
pub trait QueryKey: KeyBase {
fn cmp(&self, key: &[u8]) -> std::cmp::Ordering;
fn eq(&self, key: &[u8]) -> bool;
}
impl QueryKey for &'_ [u8] {
fn cmp(&self, key: &[u8]) -> std::cmp::Ordering {
Ord::cmp(self, &key)
}
fn eq(&self, key: &[u8]) -> bool {
PartialEq::eq(*self, key)
}
}
impl<const N: usize> QueryKey for [u8; N] {
fn cmp(&self, key: &[u8]) -> std::cmp::Ordering {
Ord::cmp(&self[..], key)
}
fn eq(&self, key: &[u8]) -> bool {
PartialEq::eq(self, key)
}
}
impl QueryKey for Vec<u8> {
fn cmp(&self, key: &[u8]) -> std::cmp::Ordering {
Ord::cmp(&**self, key)
}
fn eq(&self, key: &[u8]) -> bool {
PartialEq::eq(self.as_slice(), key)
}
}
impl QueryKey for Box<[u8]> {
fn cmp(&self, key: &[u8]) -> std::cmp::Ordering {
Ord::cmp(&**self, key)
}
fn eq(&self, key: &[u8]) -> bool {
PartialEq::eq(&**self, key)
}
}
impl QueryKey for u8 {
fn cmp(&self, key: &[u8]) -> std::cmp::Ordering {
Ord::cmp(&[*self][..], key)
}
fn eq(&self, key: &[u8]) -> bool {
PartialEq::eq(&[*self][..], key)
}
}
impl<A: QueryKey, B: QueryKey> QueryKey for (A, B) {
......@@ -175,22 +158,12 @@ impl<A: QueryKey, B: QueryKey> QueryKey for (A, B) {
let (key_part, value_part) = key.split_at(min(key_len, len));
a.cmp(key_part).then_with(|| b.cmp(value_part))
}
fn eq(&self, key: &[u8]) -> bool {
let (a, b) = self;
let len = a.len();
let key_len = key.len();
let (key_part, value_part) = &key.split_at(min(key_len, len));
a.eq(key_part) && b.eq(value_part)
}
}
impl<T: QueryKey> QueryKey for &'_ T {
fn cmp(&self, key: &[u8]) -> std::cmp::Ordering {
(*self).cmp(key)
}
fn eq(&self, key: &[u8]) -> bool {
(*self).eq(key)
}
}
/// A trait for keys that can be stored in the database. They need to allow hashing and comparison.
......
......@@ -49,19 +49,10 @@ pub enum AccessMode {
File,
}
#[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.
SingleValue,
}
/// Configuration for a single family to describe how the data is stored.
#[derive(Clone, Copy, Debug)]
pub struct FamilyConfig {
pub name: &'static str,
pub kind: FamilyKind,
pub compression: Compression,
}
......@@ -122,7 +113,6 @@ impl<const FAMILIES: usize> DbConfig<FAMILIES> {
Self {
family_configs: [FamilyConfig {
name: "unknown",
kind: FamilyKind::SingleValue,
compression: Compression::Lz4,
}; FAMILIES],
access_mode: default_access_mode(),
......
......@@ -1358,7 +1358,6 @@ fn value_type_val_size(ty: EntryType) -> usize {
KEY_BLOCK_ENTRY_TYPE_MEDIUM => MEDIUM_VALUE_REF_SIZE,
KEY_BLOCK_ENTRY_TYPE_BLOB => BLOB_VALUE_REF_SIZE,
KEY_BLOCK_ENTRY_TYPE_KEY_DELETED => KEY_DELETED_REF_SIZE,
// Must precede the inline arm: both are open-ended and the tombstone range sits above it.
ty if ty >= KEY_BLOCK_ENTRY_TYPE_INLINE_MIN => {
(ty - KEY_BLOCK_ENTRY_TYPE_INLINE_MIN) as usize
}
......
......@@ -155,30 +155,6 @@ fn open_db_with_config<const F: usize>(
)
}
#[cfg(any())]
fn multi_value_config_with_mmap(mmap: bool) -> DbConfig<1> {
DbConfig {
family_configs: [FamilyConfig {
name: "test",
kind: FamilyKind::SingleValue,
compression: Compression::Lz4,
}],
access_mode: if mmap {
crate::mmap_access_mode()
} else {
AccessMode::File
},
}
}
#[cfg(any())]
fn open_multi_value_db(
path: &std::path::Path,
mmap: bool,
) -> Result<TurboPersistence<RayonParallelScheduler, 1>> {
open_db_with_config(path, multi_value_config_with_mmap(mmap))
}
// This stress test writes more than ten million entries and uses Rayon directly, so it is too slow
// to run under Miri and depends on concurrency that Miri cannot provide efficiently.
#[cfg(not(miri))]
......@@ -1538,364 +1514,7 @@ fn many_medium_values_compaction(#[case] mmap: bool) -> Result<()> {
Ok(())
}
#[rstest]
#[case(true)]
#[case(false)]
#[cfg(any())]
fn compaction_multi_value_preserves_different_values(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let key = vec![42u8];
{
let db = open_multi_value_db(path, mmap)?;
// 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(0, &key.as_slice())?;
assert_eq!(results.len(), 3, "Should have 3 values before compaction");
// Compact with removed set-valued mode mode
db.full_compact()?;
// After compaction: all different values should be preserved
let results = db.get(0, &key.as_slice())?;
assert_eq!(
results.len(),
3,
"removed set-valued mode 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(())
}
#[cfg(any())]
fn multi_value_config() -> DbConfig<1> {
let mut config = DbConfig::<1>::default();
config.family_configs[0] = FamilyConfig {
name: "test",
kind: FamilyKind::SingleValue,
compression: Compression::Lz4,
};
config
}
#[rstest]
#[case(true)]
#[case(false)]
#[cfg(any())]
fn compaction_multi_value_multiple_compactions(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let key = vec![42u8];
{
let db = open_multi_value_db(path, mmap)?;
// 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(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(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(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 = open_multi_value_db(path, mmap)?;
let results = db.get(0, &key.as_slice())?;
assert_eq!(results.len(), 6, "Should still have 6 values after reopen");
db.shutdown()?;
}
Ok(())
}
#[rstest]
#[case(true)]
#[case(false)]
#[cfg(any())]
fn multi_value_delete_key(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let key = vec![42u8];
{
let db = open_multi_value_db(path, mmap)?;
// 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(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(0, &key.as_slice())?;
assert!(results.is_empty(), "get should return empty after delete");
// Compact and verify still deleted
db.full_compact()?;
let results = db.get(0, &key.as_slice())?;
assert!(
results.is_empty(),
"get should return empty after compaction"
);
db.shutdown()?;
}
// Reopen and verify deletion persists
{
let db = open_multi_value_db(path, mmap)?;
let results = db.get(0, &key.as_slice())?;
assert!(results.is_empty(), "get should return empty after reopen");
db.shutdown()?;
}
Ok(())
}
#[rstest]
#[case(true)]
#[case(false)]
#[cfg(any())]
fn multi_value_delete_then_rewrite(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let key = vec![42u8];
{
let db = open_multi_value_db(path, mmap)?;
// 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(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(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(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 = open_multi_value_db(path, mmap)?;
let results = db.get(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(())
}
#[rstest]
#[case(true)]
#[case(false)]
#[cfg(any())]
fn multi_value_delete_with_compaction_interleaved(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let key = vec![42u8];
{
let db = open_multi_value_db(path, mmap)?;
// 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(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(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(0, &key.as_slice())?;
assert!(
results.is_empty(),
"get 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(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 = open_multi_value_db(path, mmap)?;
let results = db.get(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:
// - A write after `flush` supersedes earlier writes of the same key in the batch.
// - The removed set-valued mode had tombstones that only shadowed older SSTs.
// A write after `flush` supersedes earlier writes of the same key in the batch.
#[rstest]
#[case(true)]
#[case(false)]
......@@ -1904,11 +1523,7 @@ fn single_value_write_after_flush_supersedes_duplicates(#[case] mmap: bool) -> R
let path = tempdir.path();
let duplicated = vec![1u8];
let deleted = vec![2u8];
let open = || {
let mut config = multi_value_config_with_mmap(mmap);
config.family_configs[0].kind = FamilyKind::SingleValue;
open_db_with_config(path, config)
};
let open = || open_db_with_config(path, config_with_mmap::<1>(mmap));
{
let db = open()?;
......@@ -1941,94 +1556,6 @@ fn single_value_write_after_flush_supersedes_duplicates(#[case] mmap: bool) -> R
Ok(())
}
#[rstest]
#[case(true)]
#[case(false)]
#[cfg(any())]
fn multi_value_tombstone_only_shadows_older_ssts(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
// For removed set-valued mode, 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 = open_multi_value_db(path, mmap)?;
// 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(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(())
}
#[rstest]
#[case(true)]
#[case(false)]
#[cfg(any())]
fn multi_value_tombstone_shadows_older_sst_only(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
// For removed set-valued mode, tombstone in a batch shadows only entries from older SSTs.
let key = vec![4u8];
{
let db = open_multi_value_db(path, mmap)?;
// 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(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(())
}
/// Returns the number of `.blob` files in the given directory.
#[cfg(not(miri))]
fn count_blob_files(dir: &Path) -> usize {
......@@ -2159,55 +1686,6 @@ fn compaction_deletes_blob_on_tombstone(#[case] mmap: bool) -> Result<()> {
/// tombstone prunes older blob entries.
// The first access-mode variant exceeded 20 minutes under Miri while processing the production-size
// blob boundary.
#[cfg(not(miri))]
#[rstest]
#[case(true)]
#[case(false)]
#[cfg(any())]
fn compaction_deletes_blob_multi_value_tombstone(#[case] mmap: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let db = open_multi_value_db(path, mmap)?;
let blob_value = vec![42u8; MAX_MEDIUM_VALUE_SIZE + 1];
// Write a blob-sized value
let batch = db.write_batch()?;
batch.put(0, vec![1u8], blob_value.clone().into())?;
db.commit_write_batch(batch)?;
assert_eq!(count_blob_files(path), 1);
// Delete the key (tombstone) and write a new small value in a new batch
let batch = db.write_batch()?;
batch.delete(0, vec![1u8])?;
batch.put(0, vec![1u8], vec![99u8].into())?;
db.commit_write_batch(batch)?;
// Blob file still exists before compaction
assert_eq!(count_blob_files(path), 1);
// Compact — tombstone prunes the old blob entry
db.full_compact()?;
// The new value should still be readable
let results = db.get(0, &vec![1u8].as_slice())?;
assert_eq!(results.len(), 1);
assert_eq!(results[0].as_ref(), &[99u8]);
// After compaction, the old blob file should be deleted immediately.
assert_eq!(
count_blob_files(path),
0,
"Blob file should be deleted after compaction"
);
db.shutdown()?;
Ok(())
}
/// Test that compaction preserves blob files that are still referenced
/// (not superseded).
// The first access-mode variant exceeded 20 minutes under Miri while processing the production-size
......@@ -2325,581 +1803,6 @@ fn current_file_is_json_with_commit_time() -> Result<()> {
Ok(())
}
/// A value-specific tombstone deletes only the pair it names, leaving other values for the same
/// key.
#[test]
#[cfg(any())]
fn valued_tombstone_deletes_only_its_pair() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let key = vec![1u8];
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
multi_value_config(),
RayonParallelScheduler,
)?;
// Three values under one key, each in its own SST.
for v in [10u32, 20, 30] {
let batch = db.write_batch()?;
batch.put(0, key.clone(), v.to_be_bytes().to_vec().into())?;
db.commit_write_batch(batch)?;
}
// Delete just the middle one.
let batch = db.write_batch()?;
batch.delete(0, key.clone(), 20u32.to_be_bytes().to_vec().into())?;
db.commit_write_batch(batch)?;
let mut results = db
.get(0, &key.as_slice())?
.iter()
.map(|v| u32::from_be_bytes((**v).try_into().unwrap()))
.collect::<Vec<_>>();
results.sort();
assert_eq!(results, vec![10, 30], "only the named pair should be gone");
db.shutdown()?;
Ok(())
}
/// A partial compaction must NOT drop a value-specific tombstone: an unmerged older SST may still
/// hold a matching value, and dropping the tombstone would resurrect it.
// This test takes about 16 minutes under Miri and is too slow for the Miri CI job.
#[cfg(not(miri))]
#[test]
#[cfg(any())]
fn valued_tombstone_survives_partial_compaction() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
multi_value_config(),
RayonParallelScheduler,
)?;
// Enough distinct keys that each SST spans a real slice of the hash space. The compaction
// selector estimates duplication by scaling sizes against that spread, so a couple of keys
// sharing one hash makes the estimate degenerate and no merge is ever chosen — which would
// leave this test passing without compacting anything.
const KEYS: u32 = 2000;
// Oldest layer holds the values that the tombstones must keep suppressing.
let batch = db.write_batch()?;
for k in 0..KEYS {
batch.put(
0,
k.to_be_bytes().to_vec(),
42u32.to_be_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
// Newer layers so compaction has overlapping candidates to merge partially.
for v in [1u32, 2, 3] {
let batch = db.write_batch()?;
for k in 0..KEYS {
batch.put(0, k.to_be_bytes().to_vec(), v.to_be_bytes().to_vec().into())?;
}
db.commit_write_batch(batch)?;
}
let batch = db.write_batch()?;
for k in 0..KEYS {
batch.delete(
0,
k.to_be_bytes().to_vec(),
42u32.to_be_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
// Compact repeatedly; whatever coverage the selector chooses, 42 must stay deleted.
for round in 0..3 {
db.compact(&CompactConfig {
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] {
let results = db
.get(0, &k.to_be_bytes().to_vec().as_slice())?
.iter()
.map(|v| u32::from_be_bytes((**v).try_into().unwrap()))
.collect::<Vec<_>>();
assert!(
!results.contains(&42),
"42 was resurrected for key {k} in round {round}: {results:?}"
);
}
}
db.shutdown()?;
Ok(())
}
/// Deletes must survive a reopen: the tombstone is persisted, not just held in memory.
#[test]
#[cfg(any())]
fn valued_tombstone_persists_across_reopen() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let key = vec![3u8];
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
multi_value_config(),
RayonParallelScheduler,
)?;
let batch = db.write_batch()?;
batch.put(0, key.clone(), 100u32.to_be_bytes().to_vec().into())?;
batch.put(0, key.clone(), 200u32.to_be_bytes().to_vec().into())?;
db.commit_write_batch(batch)?;
let batch = db.write_batch()?;
batch.delete(0, key.clone(), 100u32.to_be_bytes().to_vec().into())?;
db.commit_write_batch(batch)?;
db.shutdown()?;
}
{
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
multi_value_config(),
RayonParallelScheduler,
)?;
let results = db
.get(0, &key.as_slice())?
.iter()
.map(|v| u32::from_be_bytes((**v).try_into().unwrap()))
.collect::<Vec<_>>();
assert_eq!(results, vec![200], "tombstone lost across reopen");
db.shutdown()?;
}
Ok(())
}
/// A key tombstone still deletes everything, including values a value-specific tombstone left
/// alone.
#[test]
#[cfg(any())]
fn whole_key_tombstone_still_deletes_all_values() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let key = vec![5u8];
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
multi_value_config(),
RayonParallelScheduler,
)?;
let batch = db.write_batch()?;
batch.put(0, key.clone(), 1u32.to_be_bytes().to_vec().into())?;
batch.put(0, key.clone(), 2u32.to_be_bytes().to_vec().into())?;
db.commit_write_batch(batch)?;
let batch = db.write_batch()?;
batch.delete(0, key.clone(), 1u32.to_be_bytes().to_vec().into())?;
db.commit_write_batch(batch)?;
let batch = db.write_batch()?;
batch.delete(0, key.clone())?;
db.commit_write_batch(batch)?;
assert!(
db.get(0, &key.as_slice())?.is_empty(),
"key tombstone should remove everything"
);
db.shutdown()?;
Ok(())
}
/// Counts tombstone entries (both kinds) across every live SST, by reading the files directly.
/// Tombstone counts are not tracked in the meta file, so there is nothing cheaper to read.
#[cfg(any())]
fn count_tombstones(
path: &Path,
db: &TurboPersistence<RayonParallelScheduler, 1>,
) -> Result<usize> {
let mut count = 0;
for meta in db.meta_info()? {
for entry in &meta.entries {
let sst = StaticSortedFileMetaData {
sequence_number: entry.sequence_number,
block_count: entry.block_count,
};
for item in
StaticSortedFileIter::open(path, sst, Compression::Lz4, crate::mmap_access_mode())?
{
if matches!(item?.value, IterValue::KeyDeleted | IterValue::KeyDeleted) {
count += 1;
}
}
}
}
Ok(count)
}
/// Compaction reclaims tombstones once no *older* SST outside the job can still hold the key.
/// Without this, tombstones accumulate forever.
#[test]
#[cfg(any())]
fn compaction_reclaims_tombstones_when_no_older_sst_has_the_key() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
multi_value_config(),
RayonParallelScheduler,
)?;
// Enough distinct keys that the SSTs span a real hash range: the compaction selector
// estimates duplication by scaling sizes against the key-space spread, and a handful of
// keys sharing one hash makes that estimate degenerate.
const KEYS: u32 = 2000;
let batch = db.write_batch()?;
for k in 0..KEYS {
batch.put(
0,
k.to_be_bytes().to_vec(),
1u32.to_be_bytes().to_vec().into(),
)?;
batch.put(
0,
k.to_be_bytes().to_vec(),
2u32.to_be_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
// Delete one of the two values for every key.
let batch = db.write_batch()?;
for k in 0..KEYS {
batch.delete(
0,
k.to_be_bytes().to_vec(),
1u32.to_be_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
assert_eq!(
count_tombstones(path, &db)?,
KEYS as usize,
"tombstones should be on disk before compaction"
);
db.compact(&CompactConfig {
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
// on the tombstone entries themselves: total file size would shrink from dropping the deleted
// values alone, so it cannot distinguish a working probe from one that never fires.
assert_eq!(
count_tombstones(path, &db)?,
0,
"compaction should have reclaimed every tombstone"
);
// ...and the deletes must still hold after reclamation.
for k in [0u32, KEYS / 2, KEYS - 1] {
let results = db
.get(0, &k.to_be_bytes().to_vec().as_slice())?
.iter()
.map(|v| u32::from_be_bytes((**v).try_into().unwrap()))
.collect::<Vec<_>>();
assert_eq!(results, vec![2], "value 1 must stay deleted for key {k}");
}
db.shutdown()?;
Ok(())
}
/// When an older SST *outside* the compaction job still holds the key, the tombstone must be
/// kept. Dropping it would resurrect the value.
#[test]
#[cfg(any())]
fn compaction_keeps_tombstone_when_older_sst_has_the_key() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
multi_value_config(),
RayonParallelScheduler,
)?;
const KEYS: u32 = 2000;
// Oldest layer: the values that must stay suppressed.
let batch = db.write_batch()?;
for k in 0..KEYS {
batch.put(
0,
k.to_be_bytes().to_vec(),
1u32.to_be_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
// Newer layers: an unrelated value per key, then a tombstone for the old one.
let batch = db.write_batch()?;
for k in 0..KEYS {
batch.put(
0,
k.to_be_bytes().to_vec(),
2u32.to_be_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
let batch = db.write_batch()?;
for k in 0..KEYS {
batch.delete(
0,
k.to_be_bytes().to_vec(),
1u32.to_be_bytes().to_vec().into(),
)?;
}
db.commit_write_batch(batch)?;
// 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.
for round in 0..4 {
db.compact(&CompactConfig {
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] {
let mut results = db
.get(0, &k.to_be_bytes().to_vec().as_slice())?
.iter()
.map(|v| u32::from_be_bytes((**v).try_into().unwrap()))
.collect::<Vec<_>>();
results.sort();
assert_eq!(
results,
vec![2],
"value 1 resurrected for key {k} in round {round}"
);
}
}
db.shutdown()?;
Ok(())
}
/// A compaction job's SSTs need not be contiguous: the selector picks members by hash-range
/// overlap and skips already-claimed candidates, so an SST can sit "between" two job members
/// without belonging to the job. A tombstone must still be kept for it.
///
/// This is the case a sequence-number threshold gets wrong — it would treat the skipped SST as
/// part of the job and drop a tombstone that is still load-bearing.
// This multi-SST partial-compaction scenario exceeded 20 minutes under Miri.
#[cfg(not(miri))]
#[test]
#[cfg(any())]
fn compaction_keeps_tombstone_when_skipped_sst_has_the_key() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
multi_value_config(),
RayonParallelScheduler,
)?;
const KEYS: u32 = 2000;
// Every SST spans a wide, overlapping slice of the hash space. That is what lets the selector
// form jobs that skip over an intervening file: with narrow or identical ranges it only ever
// picks contiguous runs, and the bug this guards against stays hidden.
let key_for = |round: u32, i: u32| {
let mut k = vec![0u8; 8];
k[..4].copy_from_slice(&i.to_be_bytes());
k[4..].copy_from_slice(&round.to_be_bytes());
k
};
// Oldest layer: the values that must stay suppressed once deleted.
let batch = db.write_batch()?;
for i in 0..KEYS {
batch.put(0, key_for(0, i), 1u32.to_be_bytes().to_vec().into())?;
}
db.commit_write_batch(batch)?;
// Several more layers touching the same keys, so the selector has many overlapping candidates.
for round in 1..7u32 {
let batch = db.write_batch()?;
for i in 0..KEYS {
batch.put(0, key_for(0, i), (round + 1).to_be_bytes().to_vec().into())?;
batch.put(0, key_for(round, i), 9u32.to_be_bytes().to_vec().into())?;
}
db.commit_write_batch(batch)?;
}
// Delete the oldest value for every key in the first layer.
let batch = db.write_batch()?;
for i in 0..KEYS {
batch.delete(0, key_for(0, i), 1u32.to_be_bytes().to_vec().into())?;
}
db.commit_write_batch(batch)?;
// More layers *after* the tombstone, so it sits in the middle of the stack rather than at the
// newest end. A job containing the tombstone's SST can then skip over older SSTs that still
// hold value 1 — those are only caught by probing every older SST the job does not merge, not
// just the ones below the job's oldest member.
for round in 7..12u32 {
let batch = db.write_batch()?;
for i in 0..KEYS {
batch.put(0, key_for(round, i), 9u32.to_be_bytes().to_vec().into())?;
}
db.commit_write_batch(batch)?;
}
for round in 0..6 {
db.compact(&CompactConfig {
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] {
let results = db
.get(0, &key_for(0, i).as_slice())?
.iter()
.map(|v| u32::from_be_bytes((**v).try_into().unwrap()))
.collect::<Vec<_>>();
assert!(
!results.contains(&1),
"deleted value resurrected for key {i} in round {round}: {results:?}"
);
}
}
db.shutdown()?;
Ok(())
}
/// Tombstones carry the deleted value inline, so every size up to the inline limit round-trips.
/// The boundary sizes matter: the tag range is packed directly above the inline value range, so an
/// off-by-one in either bound would decode a tombstone as a value or vice versa.
#[test]
#[cfg(any())]
fn valued_tombstone_supports_all_inline_value_sizes() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
multi_value_config(),
RayonParallelScheduler,
)?;
// One key per value size, each holding a deleted value of that size plus a survivor.
for len in 0..=MAX_INLINE_VALUE_SIZE {
let key = vec![len as u8];
let doomed = vec![0xAAu8; len];
let batch = db.write_batch()?;
batch.put(0, key.clone(), doomed.clone().into())?;
batch.put(0, key.clone(), vec![0xBBu8; 3].into())?;
db.commit_write_batch(batch)?;
let batch = db.write_batch()?;
batch.delete(0, key.clone(), doomed.clone().into())?;
db.commit_write_batch(batch)?;
let results = db.get(0, &key.as_slice())?;
assert_eq!(
results.iter().map(|v| v.to_vec()).collect::<Vec<_>>(),
vec![vec![0xBBu8; 3]],
"{len}-byte value should have been deleted, and only it"
);
}
db.shutdown()?;
Ok(())
}
/// Values too large to store inline are rejected rather than silently truncated: the tombstone
/// carries a copy of the value, so deleting a large value would cost more than it reclaims.
#[test]
#[cfg(any())]
fn valued_tombstone_rejects_values_larger_than_inline() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
multi_value_config(),
RayonParallelScheduler,
)?;
let batch = db.write_batch()?;
let too_big = vec![0u8; MAX_INLINE_VALUE_SIZE + 1];
let err = batch
.delete(0, vec![1u8], too_big.into())
.expect_err("oversized value should be rejected");
assert!(
err.to_string().contains("at most"),
"unexpected error: {err}"
);
db.shutdown()?;
Ok(())
}
/// Value-specific tombstones are meaningless in a SingleValue family, where `delete` already
/// removes the single value exactly. Rejecting at the API keeps the tombstone off disk, where it
/// would otherwise only surface as an error at read time.
#[test]
#[cfg(any())]
fn valued_tombstone_rejects_single_value_families() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let path = tempdir.path();
let db = TurboPersistence::<_, 1>::open_with_config_and_parallel_scheduler(
path.to_path_buf(),
DbConfig::<1>::default(),
RayonParallelScheduler,
)?;
let batch = db.write_batch()?;
let err = batch
.delete(0, vec![1u8], 1u32.to_be_bytes().to_vec().into())
.expect_err("SingleValue family should be rejected");
assert!(
err.to_string().contains("removed set-valued mode"),
"unexpected error: {err}"
);
db.shutdown()?;
Ok(())
}
// This 8,000-key meta-sharding compaction test exceeded 20 minutes under Miri.
#[cfg(not(miri))]
#[rstest]
......
use turbo_persistence::{Compression, FamilyConfig, FamilyKind};
use turbo_persistence::{Compression, FamilyConfig};
#[derive(Debug, Clone, Copy)]
pub enum KeySpace {
......@@ -37,18 +37,15 @@ impl KeySpace {
match self {
KeySpace::Infra | KeySpace::TaskMeta => FamilyConfig {
name: self.name(),
kind: FamilyKind::SingleValue,
compression: Compression::Lz4,
},
KeySpace::TaskData => FamilyConfig {
name: self.name(),
kind: FamilyKind::SingleValue,
compression: Compression::Zstd3,
},
KeySpace::TaskCache => FamilyConfig {
name: self.name(),
// TaskCache maps each hash to one list of TaskIds to handle rare collisions.
kind: FamilyKind::SingleValue,
compression: Compression::Lz4,
},
}
......
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