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")?;
......
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> {
......
......@@ -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 {:?}",
......
......@@ -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