Unverified Commit 3d3405a1 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbopack] use zero copy qfilter deserialization (#90574)

## What

Switch turbo-persistence AMQF filters from owned `qfilter::Filter` (heap-allocated) to zero-copy `qfilter::FilterRef` that borrows directly from the memory-mapped meta file.

## Why

- **Lower memory usage** — no heap copy of filter data; `FilterRef` is just a pointer into the mmap
- **Faster open time** — no deserialization/allocation, just pointer math over the mmap
- **OS-managed memory** — mmap pages can be cheaply evicted under pressure (free LRU behavior), unlike heap-allocated `Filter` data which needs to be swapped

## How

- Update `qfilter` dependency to the latest alpha release with `FilterRef` support 
- Switch per-entry AMQF serialization from `turbo_bincode` to `pot` format, which supports zero-copy deserialization 
- Store `qfilter::FilterRef<'static>` directly in `MetaEntry` (lifetime transmuted from the mmap borrow)
- Rely on Rust's struct field drop order guarantee: `MetaFile::entries` is declared before `MetaFile::mmap`, so all `FilterRef`s are dropped before the mmap is unmapped
- Update compaction code to work with `FilterRef` avoiding many allocations when merging

### Safety invariants

The `FilterRef<'static>` lifetime is transmuted 🙀 — the actual borrow is from `MetaFile::mmap`. This is safe because:

1. `MetaEntry` is never moved out of `MetaFile` (only accessed by `&` reference via `entries()` / `entry()`)
2. Rust drops struct fields in declaration order, and `entries` is declared before `mmap`
3. This is the same pattern used by `ArcBytes`/`RcBytes` in this crate (raw pointer into backing storage)

## Benchmark Results

I ran a number of the Read benchmarks and compaction benchmarks and it is all in the noise, which makes sense.  We might get a slight benefit from avoiding the `OnceLock` and lazy initialization, we should also have slightly lower maxrss and offer the OS more flexibility during memory pressure

From measuring vercel-site, a warm build saves ~40m of MaxRSS
parent 3c301acc
......@@ -1309,7 +1309,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
dependencies = [
"lazy_static",
"windows-sys 0.48.0",
"windows-sys 0.59.0",
]
[[package]]
......@@ -3053,7 +3053,7 @@ dependencies = [
"libc",
"percent-encoding",
"pin-project-lite",
"socket2 0.5.10",
"socket2 0.6.2",
"tokio",
"tower-service",
"tracing",
......@@ -5406,17 +5406,6 @@ dependencies = [
"serde",
]
[[package]]
name = "pot"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf741fa415952eb20f27fbc210dc85f31cc7cdc80aa3ce81d5e27d28a6f45dc2"
dependencies = [
"byteorder",
"half",
"serde",
]
[[package]]
name = "potential_utf"
version = "0.1.4"
......@@ -5674,9 +5663,9 @@ dependencies = [
[[package]]
name = "qfilter"
version = "0.3.0-alpha.2"
version = "0.3.0-alpha.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bd0ea20afc2eab082dde00f58d9e83ed70dcb693fa88c23890e122e19355635"
checksum = "9fb8c6e59c09e93a6dbc7ff5feff747fc4efc3f5a90c00851e1472ce1bdf2eff"
dependencies = [
"serde",
"serde_bytes",
......@@ -5723,7 +5712,7 @@ dependencies = [
"quinn-udp",
"rustc-hash 2.1.1",
"rustls",
"socket2 0.5.10",
"socket2 0.6.2",
"thiserror 2.0.12",
"tokio",
"tracing",
......@@ -5761,7 +5750,7 @@ dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2 0.5.10",
"socket2 0.6.2",
"tracing",
"windows-sys 0.60.2",
]
......@@ -9441,7 +9430,6 @@ name = "turbo-persistence"
version = "0.1.0"
dependencies = [
"anyhow",
"bincode 2.0.1",
"bitfield",
"byteorder",
"codspeed-criterion-compat",
......@@ -9453,7 +9441,7 @@ dependencies = [
"memmap2 0.9.5",
"nohash-hasher",
"parking_lot",
"pot",
"postcard",
"qfilter",
"quick_cache",
"rand 0.10.0",
......@@ -9463,9 +9451,9 @@ dependencies = [
"tempfile",
"thread_local",
"tracing",
"turbo-bincode",
"turbo-tasks-malloc",
"xxhash-rust",
"zerocopy",
]
[[package]]
......
......@@ -14,7 +14,6 @@ verbose_log = []
[dependencies]
anyhow = { workspace = true }
bincode = { workspace = true }
bitfield = { workspace = true }
byteorder = { workspace = true }
crc32fast = { workspace = true }
......@@ -25,15 +24,15 @@ lzzzz = { workspace = true }
memmap2 = "0.9.5"
nohash-hasher = { workspace = true }
parking_lot = { workspace = true }
pot = "3.0.0"
# See https://github.com/vercel/next.js/issues/91708 for why we need the legacy_x86_64_support feature
qfilter = { version = "0.3.0-alpha.2", features = ["serde", "legacy_x86_64_support"] }
qfilter = { version = "0.3.0-alpha.3", features = ["serde", "legacy_x86_64_support"] }
postcard = { workspace = true, features = ["alloc", "use-std"] }
zerocopy = { version = "0.8", features = ["derive"] }
quick_cache = { workspace = true }
rustc-hash = { workspace = true }
smallvec = { workspace = true }
thread_local = { workspace = true }
tracing = { workspace = true }
turbo-bincode= { workspace = true }
xxhash-rust = { workspace = true }
[dev-dependencies]
......
......@@ -26,6 +26,9 @@ enum Backing {
#[derive(Clone)]
pub struct ArcBytes {
data: *const [u8],
// Safety: Backing should come last so that it is dropped after the data pointer so we don't
// create a dangling pointer. This isn't really a problem since it is technically ok to have
// dangling _pointers_.
backing: Backing,
}
......
......@@ -528,6 +528,11 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
// len is only a snapshot at that time and it can change while we create the filter.
// So we give it 5% more space to make resizes less likely.
let initial_capacity = set.len() * 20 / 19;
// TODO: Using u64::BITS as fingerprint size is wasteful for a
// probabilistic membership filter. A smaller fingerprint (e.g. via
// Filter::new with a target fp_rate) would significantly reduce size,
// but would make merging slower since mismatched fingerprint sizes
// fall back to one-by-one insertion instead of sorted merge.
let mut amqf =
qfilter::Filter::with_fingerprint_size(initial_capacity as u64, u64::BITS as u8)
.unwrap();
......@@ -987,7 +992,7 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
// during the merge loop. Empty filters (from commits with no
// reads) are discarded.
let used_key_hashes: Option<qfilter::Filter> = {
let filters: Vec<qfilter::Filter> = meta_files
let filters: Vec<qfilter::FilterRef<'_>> = meta_files
.iter()
.filter(|m| m.family() == family)
.filter_map(|meta_file| {
......@@ -1001,9 +1006,11 @@ impl<S: ParallelScheduler, const FAMILIES: usize> TurboPersistence<S, FAMILIES>
None
} else if filters.len() == 1 {
// Just directly use the single item
filters.into_iter().next()
Some(filters[0].to_owned())
} else {
let total_len: u64 = filters.iter().map(|f| f.len()).sum();
// Fingerprint size must match the source filters to
// enable the efficient sorted merge path in qfilter.
let mut merged =
qfilter::Filter::with_fingerprint_size(total_len, u64::BITS as u8)
.expect("Failed to create merged AMQF filter");
......
......@@ -2,19 +2,16 @@ use std::{
cmp::Ordering,
fmt::Display,
fs::File,
io::{BufReader, Seek},
ops::Deref,
path::{Path, PathBuf},
sync::OnceLock,
};
use anyhow::{Context, Result, bail};
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 zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Ref, big_endian as be};
use crate::{
QueryKey,
......@@ -52,14 +49,50 @@ impl Display for MetaEntryFlags {
}
}
/// A wrapper around [`qfilter::Filter`] that implements [`Encode`] and [`Decode`].
#[derive(Encode, Decode)]
pub struct AmqfBincodeWrapper(
// this annotation can be replaced with `#[bincode(serde)]` once
// <https://github.com/arthurprs/qfilter/issues/13> is resolved
#[bincode(with = "turbo_bincode::serde_self_describing")] pub qfilter::Filter,
);
/// On-disk layout of a single entry header in the `.meta` file.
///
/// Fields are big-endian to match the existing wire format written by [`MetaFileBuilder`].
#[repr(C, packed)]
#[derive(FromBytes, IntoBytes, Immutable, KnownLayout, Clone, Copy)]
pub(crate) struct EntryHeader {
sequence_number: be::U32,
block_count: be::U16,
min_hash: be::U64,
max_hash: be::U64,
size: be::U64,
flags: be::U32,
amqf_end_offset: be::U32,
}
impl EntryHeader {
pub(crate) fn new(
sequence_number: u32,
block_count: u16,
min_hash: u64,
max_hash: u64,
size: u64,
flags: MetaEntryFlags,
amqf_end_offset: u32,
) -> Self {
Self {
sequence_number: be::U32::new(sequence_number),
block_count: be::U16::new(block_count),
min_hash: be::U64::new(min_hash),
max_hash: be::U64::new(max_hash),
size: be::U64::new(size),
flags: be::U32::new(flags.0),
amqf_end_offset: be::U32::new(amqf_end_offset),
}
}
}
/// # Safety
///
/// `MetaEntry` stores a `FilterRef<'static>` with a transmuted lifetime that actually borrows
/// from the parent [`MetaFile`]'s mmap. This is safe because entries are only accessed by
/// reference through `MetaFile` and are never moved out.
///
/// For this reason this type should not implement Clone or Copy.
pub struct MetaEntry {
/// The metadata for the static sorted file.
sst_data: StaticSortedFileMetaData,
......@@ -73,19 +106,22 @@ pub struct MetaEntry {
size: u64,
/// The status flags for this entry.
flags: MetaEntryFlags,
/// The offset of the start of the AMQF data in the meta file relative to the end of the
/// header.
start_of_amqf_data_offset: u32,
/// The offset of the end of the AMQF data in the the meta file relative to the end of the
/// header.
end_of_amqf_data_offset: u32,
/// The AMQF filter of this file. This is only used if the range is very large. Smaller ranges
/// use the AMQF cache instead.
amqf: OnceLock<qfilter::Filter>,
/// Byte offset range of the raw AMQF data within the mmap, used for carrying forward
/// serialized bytes during compaction without re-serializing.
amqf_data_offset: std::ops::Range<u32>,
/// The AMQF filter for this file, eagerly deserialized as a zero-copy [`qfilter::FilterRef`]
/// that borrows directly from the parent [`MetaFile`]'s memory-mapped file.
///
/// The `'static` lifetime is transmuted — the actual borrow is from `MetaFile::mmap`.
amqf: qfilter::FilterRef<'static>,
/// The static sorted file that is lazily loaded
sst: OnceLock<StaticSortedFile>,
}
// Safety: FilterRef is a read-only view into the mmap which is Send+Sync.
unsafe impl Send for MetaEntry {}
unsafe impl Sync for MetaEntry {}
impl MetaEntry {
pub fn sequence_number(&self) -> u32 {
self.sst_data.sequence_number
......@@ -100,36 +136,15 @@ impl MetaEntry {
}
pub fn amqf_size(&self) -> u32 {
self.end_of_amqf_data_offset - self.start_of_amqf_data_offset
self.amqf_data_offset.end - self.amqf_data_offset.start
}
/// Returns the raw serialized AMQF bytes from the mmap.
pub fn raw_amqf<'l>(&self, amqf_data: &'l [u8]) -> &'l [u8] {
amqf_data
.get(self.start_of_amqf_data_offset as usize..self.end_of_amqf_data_offset as usize)
.expect("AMQF data out of bounds")
}
pub fn deserialize_amqf(&self, meta: &MetaFile) -> Result<qfilter::Filter> {
let amqf = self.raw_amqf(meta.amqf_data());
Ok(turbo_bincode_decode::<AmqfBincodeWrapper>(amqf)
.with_context(|| {
format!(
"Failed to deserialize AMQF from {:08}.meta for {:08}.sst",
meta.sequence_number,
self.sequence_number()
)
})?
.0)
}
pub fn amqf(&self, meta: &MetaFile) -> Result<impl Deref<Target = qfilter::Filter>> {
self.amqf.get_or_try_init(|| {
let amqf = self.deserialize_amqf(meta)?;
anyhow::Ok(amqf)
})
&amqf_data[self.amqf_data_offset.start as usize..self.amqf_data_offset.end as usize]
}
pub fn sst(&self, meta: &MetaFile) -> Result<&StaticSortedFile> {
fn sst(&self, meta: &MetaFile) -> Result<&StaticSortedFile> {
self.sst.get_or_try_init(|| {
StaticSortedFile::open(&meta.db_path, self.sst_data).with_context(|| {
format!(
......@@ -210,6 +225,11 @@ pub struct StaticSortedFileRange {
pub max_hash: u64,
}
/// # Safety
///
/// `entries` **must** be declared before `mmap` so that Rust's field drop order (declaration
/// order) drops all `FilterRef`s before the mmap is unmapped. Reordering these fields would
/// be unsound.
pub struct MetaFile {
/// The database path
db_path: PathBuf,
......@@ -217,27 +237,28 @@ pub struct MetaFile {
sequence_number: u32,
/// The key family of the SST files in this meta file.
family: u32,
/// The entries of the file.
/// The entries of the file. Dropped before `mmap` (field declaration order).
entries: Vec<MetaEntry>,
/// The entries that have been marked as obsolete.
obsolete_entries: Vec<u32>,
/// The obsolete SST files.
obsolete_sst_files: Vec<u32>,
/// The offset of the start of the "used keys" AMQF data in the meta file relative to the end
/// of the header.
/// Byte offset within the mmap where the AMQF data region starts (i.e. the header length).
/// Entry AMQF offsets and used-keys offsets are relative to this position.
amqf_data_start: u32,
/// The offset of the start of the "used keys" AMQF data relative to the AMQF data region.
start_of_used_keys_amqf_data_offset: u32,
/// The offset of the end of the "used keys" AMQF data in the the meta file relative to the end
/// of the header.
/// The offset of the end of the "used keys" AMQF data relative to the AMQF data region.
end_of_used_keys_amqf_data_offset: u32,
/// Byte offset of the start of AMQF data within the mmap (= end of the header).
amqf_data_start: usize,
/// The memory mapped file.
/// The entire memory-mapped file. Must be the last field that matters for drop order —
/// `entries` contains `FilterRef`s that borrow from this mmap.
mmap: Mmap,
}
impl MetaFile {
/// Opens a meta file at the given path. This memory maps the file, but does not read it yet.
/// It's lazy read on demand.
/// Opens a meta file at the given path. Memory maps the entire file and eagerly deserializes
/// all AMQF filters as zero-copy [`qfilter::FilterRef`]s that borrow from the mmap.
pub fn open(db_path: &Path, sequence_number: u32) -> Result<Self> {
let filename = format!("{sequence_number:08}.meta");
let path = db_path.join(&filename);
......@@ -246,70 +267,100 @@ impl MetaFile {
}
fn open_internal(db_path: PathBuf, sequence_number: u32, path: &Path) -> Result<Self> {
let mut file = BufReader::new(File::open(path).context("Failed to open meta file")?);
let magic = file.read_u32::<BE>()?;
let file = File::open(path).context("Failed to open meta file")?;
let mmap = unsafe { MmapOptions::new().map(&file) }.context("Failed to mmap")?;
#[cfg(unix)]
mmap.advise(memmap2::Advice::Random)
.context("Failed to advise mmap")?;
advise_mmap_for_persistence(&mmap)?;
// Parse the header from the mmap via ReadBytesExt on &[u8].
let mut reader: &[u8] = &mmap;
let magic = reader.read_u32::<BE>()?;
if magic != 0xFE4ADA4A {
bail!("Invalid magic number");
}
let family = file.read_u32::<BE>()?;
let obsolete_count = file.read_u32::<BE>()?;
let family = reader.read_u32::<BE>()?;
let obsolete_count = reader.read_u32::<BE>()?;
let mut obsolete_sst_files = Vec::with_capacity(obsolete_count as usize);
for _ in 0..obsolete_count {
let obsolete_sst = file.read_u32::<BE>()?;
obsolete_sst_files.push(obsolete_sst);
obsolete_sst_files.push(reader.read_u32::<BE>()?);
}
let count = file.read_u32::<BE>()?;
let count = reader.read_u32::<BE>()?;
// Compute where the AMQF data region starts so we can deserialize filters inline.
// Remaining header: count * ENTRY_HEADER_SIZE + used_keys_end_offset.
let header_so_far = (mmap.len() - reader.len()) as u32;
let amqf_data_start =
header_so_far + count * (size_of::<EntryHeader>() as u32) + size_of::<u32>() as u32;
let amqf_data = &mmap[amqf_data_start as usize..];
// Parse entries and eagerly deserialize AMQF filters as zero-copy FilterRefs.
let mut entries = Vec::with_capacity(count as usize);
let mut start_of_amqf_data_offset = 0;
let mut start_of_amqf_data_offset: u32 = 0;
for _ in 0..count {
let entry = MetaEntry {
sst_data: StaticSortedFileMetaData {
sequence_number: file.read_u32::<BE>()?,
block_count: file.read_u16::<BE>()?,
},
let (header, rest): (Ref<&[u8], EntryHeader>, _) = Ref::from_prefix(reader)
.ok()
.context("Entry header out of bounds")?;
reader = rest;
let sst_data = StaticSortedFileMetaData {
sequence_number: header.sequence_number.get(),
block_count: header.block_count.get(),
};
let min_hash = header.min_hash.get();
let max_hash = header.max_hash.get();
let size = header.size.get();
let flags = MetaEntryFlags(header.flags.get());
let end_of_amqf_data_offset = header.amqf_end_offset.get();
let amqf_bytes = amqf_data
.get(start_of_amqf_data_offset as usize..end_of_amqf_data_offset as usize)
.expect("AMQF data out of bounds");
// Deserialize the filter borrowing from the mmap, then erase the lifetime.
let amqf: qfilter::FilterRef<'_> =
postcard::from_bytes(amqf_bytes).with_context(|| {
format!(
"Failed to deserialize AMQF from {:08}.meta for {:08}.sst",
sequence_number, sst_data.sequence_number
)
})?;
// Safety: the mmap is kept alive by MetaFile and is dropped after entries (field
// declaration order), so the borrow remains valid for the lifetime of the MetaEntry.
let amqf: qfilter::FilterRef<'static> = unsafe { std::mem::transmute(amqf) };
entries.push(MetaEntry {
sst_data,
family,
min_hash: file.read_u64::<BE>()?,
max_hash: file.read_u64::<BE>()?,
size: file.read_u64::<BE>()?,
flags: MetaEntryFlags(file.read_u32::<BE>()?),
start_of_amqf_data_offset,
end_of_amqf_data_offset: file.read_u32::<BE>()?,
amqf: OnceLock::new(),
min_hash,
max_hash,
size,
flags,
amqf_data_offset: start_of_amqf_data_offset..end_of_amqf_data_offset,
amqf,
sst: OnceLock::new(),
};
start_of_amqf_data_offset = entry.end_of_amqf_data_offset;
entries.push(entry);
});
start_of_amqf_data_offset = end_of_amqf_data_offset;
}
let start_of_used_keys_amqf_data_offset = start_of_amqf_data_offset;
let end_of_used_keys_amqf_data_offset = file.read_u32::<BE>()?;
let end_of_used_keys_amqf_data_offset = reader.read_u32::<BE>()?;
let offset = file
.stream_position()
.context("Failed to get stream position")?;
let file = file.into_inner();
let mmap = unsafe { MmapOptions::new().map(&file) }.context("Failed to mmap")?;
#[cfg(unix)]
mmap.advise(memmap2::Advice::Random)
.context("Failed to advise mmap")?;
advise_mmap_for_persistence(&mmap)?;
let file = Self {
Ok(Self {
db_path,
sequence_number,
family,
entries,
obsolete_entries: Vec::new(),
obsolete_sst_files,
amqf_data_start,
start_of_used_keys_amqf_data_offset,
end_of_used_keys_amqf_data_offset,
amqf_data_start: offset as usize,
mmap,
};
Ok(file)
})
}
pub fn clear_cache(&mut self) {
for entry in self.entries.iter_mut() {
entry.amqf.take();
entry.sst.take();
}
}
......@@ -317,7 +368,6 @@ impl MetaFile {
pub fn prepare_sst_cache(&self) {
for entry in self.entries.iter() {
let _ = entry.sst(self);
let _ = entry.amqf(self);
}
}
......@@ -339,16 +389,16 @@ impl MetaFile {
}
pub fn amqf_data(&self) -> &[u8] {
&self.mmap[self.amqf_data_start..]
&self.mmap[self.amqf_data_start as usize..]
}
pub fn deserialize_used_key_hashes_amqf(&self) -> Result<Option<qfilter::Filter>> {
pub fn deserialize_used_key_hashes_amqf(&self) -> Result<Option<qfilter::FilterRef<'_>>> {
if self.start_of_used_keys_amqf_data_offset == self.end_of_used_keys_amqf_data_offset {
return Ok(None);
}
let amqf = &self.amqf_data()[self.start_of_used_keys_amqf_data_offset as usize
..self.end_of_used_keys_amqf_data_offset as usize];
Ok(Some(pot::from_slice(amqf).with_context(|| {
Ok(Some(postcard::from_bytes(amqf).with_context(|| {
format!(
"Failed to deserialize used key hashes AMQF from {:08}.meta",
self.sequence_number
......@@ -404,8 +454,7 @@ impl MetaFile {
if key_hash < entry.min_hash || key_hash > entry.max_hash {
continue;
}
let amqf = entry.amqf(self)?;
if !amqf.contains_fingerprint(key_hash) {
if !entry.amqf.contains_fingerprint(key_hash) {
miss_result = MetaLookupResult::QuickFilterMiss;
continue;
}
......@@ -504,7 +553,6 @@ impl MetaFile {
}
continue;
}
let amqf = entry.amqf(self)?;
for (hash, index, result) in &mut cells[start_index..=end_index] {
debug_assert!(
*hash >= entry.min_hash && *hash <= entry.max_hash,
......@@ -513,7 +561,7 @@ impl MetaFile {
if result.is_some() {
continue;
}
if !amqf.contains_fingerprint(*hash) {
if !entry.amqf.contains_fingerprint(*hash) {
#[cfg(feature = "stats")]
{
lookup_result.quick_filter_misses += 1;
......
......@@ -7,8 +7,9 @@ use std::{
use anyhow::{Context, Result};
use byteorder::{BE, WriteBytesExt};
use qfilter::Filter;
use zerocopy::IntoBytes;
use crate::static_sorted_file_builder::StaticSortedFileBuilderMeta;
use crate::{meta_file::EntryHeader, static_sorted_file_builder::StaticSortedFileBuilderMeta};
pub struct MetaFileBuilder<'a> {
family: u32,
......@@ -64,19 +65,22 @@ impl<'a> MetaFileBuilder<'a> {
let mut amqf_offset = 0;
for (sequence_number, sst) in &self.entries {
file.write_u32::<BE>(*sequence_number)?;
file.write_u16::<BE>(sst.block_count)?;
file.write_u64::<BE>(sst.min_hash)?;
file.write_u64::<BE>(sst.max_hash)?;
file.write_u64::<BE>(sst.size)?;
file.write_u32::<BE>(sst.flags.0)?;
amqf_offset += sst.amqf.len();
file.write_u32::<BE>(amqf_offset as u32)?;
let header = EntryHeader::new(
*sequence_number,
sst.block_count,
sst.min_hash,
sst.max_hash,
sst.size,
sst.flags,
amqf_offset as u32,
);
file.write_all(header.as_bytes())?;
}
let serialized_used_key_hashes = self
.used_key_hashes_amqf
.as_ref()
.map(|f| pot::to_vec(f).expect("AMQF serialization failed"));
.map(|f| postcard::to_allocvec(f).expect("AMQF serialization failed"));
amqf_offset += serialized_used_key_hashes
.as_ref()
.map(|bytes| bytes.len())
......
......@@ -8,12 +8,11 @@ use std::{
use anyhow::{Context, Result};
use byteorder::{BE, ByteOrder, WriteBytesExt};
use turbo_bincode::turbo_bincode_encode;
use crate::{
compression::{checksum_block, compress_into_buffer},
constants::{MAX_INLINE_VALUE_SIZE, MAX_SMALL_VALUE_SIZE, MIN_SMALL_VALUE_BLOCK_SIZE},
meta_file::{AmqfBincodeWrapper, MetaEntryFlags},
meta_file::MetaEntryFlags,
static_sorted_file::{
BLOB_VALUE_REF_SIZE, BLOCK_TYPE_FIXED_KEY_NO_HASH, BLOCK_TYPE_FIXED_KEY_WITH_HASH,
BLOCK_TYPE_INDEX, BLOCK_TYPE_KEY_NO_HASH, BLOCK_TYPE_KEY_WITH_HASH, DELETED_VALUE_REF_SIZE,
......@@ -956,9 +955,8 @@ impl<E: Entry> StreamingSstWriter<E> {
let mut filter = self.filter.take().unwrap();
filter.shrink_to_fit();
// Serialize AMQF
let amqf =
turbo_bincode_encode(&AmqfBincodeWrapper(filter)).expect("AMQF serialization failed");
// Serialize AMQF using postcard for zero-copy deserialization via FilterRef
let amqf = postcard::to_allocvec(&filter).expect("AMQF serialization failed");
// Compute file size from block offsets rather than calling stream_position()
// (which requires a flush + seek).
......@@ -969,7 +967,7 @@ impl<E: Entry> StreamingSstWriter<E> {
let meta = StaticSortedFileBuilderMeta {
min_hash: self.min_hash,
max_hash: self.max_hash,
amqf: Cow::Owned(amqf.into_vec()),
amqf: Cow::Owned(amqf),
block_count,
size: file_size,
flags: self.flags,
......
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