Unverified Commit b059afdf authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Revert "perf(turbopack/rcstr): Add serialization-time optimization (#78645)" (#81112)

This reverts commit 2689a741.

Reverts https://github.com/vercel/next.js/pull/78645 as it causes an
incremental build regression
parent dde872d7
......@@ -9159,11 +9159,9 @@ version = "0.1.0"
dependencies = [
"bytes-str",
"codspeed-criterion-compat",
"indexmap 2.9.0",
"napi",
"new_debug_unreachable",
"rustc-hash 2.1.1",
"scoped-tls",
"serde",
"shrink-to-fit",
"triomphe 0.1.12",
......@@ -9255,7 +9253,6 @@ dependencies = [
"rstest",
"rustc-hash 2.1.1",
"serde",
"serde_bytes",
"serde_json",
"serde_path_to_error",
"smallvec",
......
......@@ -13,15 +13,16 @@ mod db;
mod key;
mod lookup_entry;
mod merge_iter;
mod static_sorted_file;
mod static_sorted_file_builder;
mod write_batch;
mod meta_file;
mod meta_file_builder;
mod sst_filter;
mod static_sorted_file;
mod static_sorted_file_builder;
#[cfg(test)]
mod tests;
mod value_buf;
mod write_batch;
pub use arc_slice::ArcSlice;
pub use db::{CompactConfig, MetaFileEntryInfo, MetaFileInfo, TurboPersistence};
......
......@@ -15,15 +15,11 @@ turbo-tasks-hash = { workspace = true }
serde = { workspace = true }
new_debug_unreachable = "1.0.6"
shrink-to-fit = { workspace = true }
bytes-str = { workspace = true }
indexmap = { workspace = true }
rustc-hash = { workspace = true }
scoped-tls = "1.0.1"
bytes-str = { workspace = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
napi = { workspace = true, optional = true }
scoped-tls = "1.0.1"
indexmap = { workspace = true }
[dev-dependencies]
criterion = { workspace = true }
......
......@@ -11,18 +11,17 @@ use std::{
use bytes_str::BytesStr;
use debug_unreachable::debug_unreachable;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use shrink_to_fit::ShrinkToFit;
use triomphe::Arc;
use turbo_tasks_hash::{DeterministicHash, DeterministicHasher};
pub use crate::serde::{set_de_map, set_ser_map};
use crate::{
dynamic::{deref_from, new_atom},
tagged_value::TaggedValue,
};
mod dynamic;
mod serde;
mod tagged_value;
/// An immutable reference counted [`String`], similar to [`Arc<String>`][std::sync::Arc].
......@@ -319,6 +318,19 @@ impl Hash for RcStr {
}
}
impl Serialize for RcStr {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for RcStr {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let s = String::deserialize(deserializer)?;
Ok(RcStr::from(s))
}
}
impl Drop for RcStr {
fn drop(&mut self) {
if self.tag() == DYNAMIC_TAG {
......
use std::{cell::RefCell, hash::BuildHasherDefault};
use indexmap::IndexSet;
use rustc_hash::FxHasher;
use scoped_tls::scoped_thread_local;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::RcStr;
scoped_thread_local!(
/// Map of strings to their interned ids.
///
/// This is used to serialize strings to their interned ids.
static SER_MAP: RefCell<IndexSet<RcStr, BuildHasherDefault<FxHasher>>>
);
scoped_thread_local!(
/// Read-only map interned ids to their strings
static DE_MAP: Vec<RcStr>
);
pub fn set_ser_map<F, R>(f: F) -> (R, IndexSet<RcStr, BuildHasherDefault<FxHasher>>)
where
F: FnOnce() -> R,
{
let map = Default::default();
let r = { SER_MAP.set(&map, f) };
(r, map.into_inner())
}
pub fn set_de_map<F, R>(map: &Vec<RcStr>, f: F) -> R
where
F: FnOnce() -> R,
{
DE_MAP.set(map, f)
}
/// Intern a string for serialization.
///
/// This function exists to move the logic for accessing the SER_MAP out of the hot path of
/// `Serialize::serialize`.
#[inline(never)]
fn intern_for_serialize(str: &RcStr) -> Option<u32> {
if !SER_MAP.is_set() {
return None;
}
Some(SER_MAP.with(|ser| {
let mut borrow = ser.borrow_mut();
if let Some(id) = borrow.get_index_of(str) {
id as u32
} else {
let id = borrow.len();
borrow.insert(str.clone());
id as u32
}
}))
}
impl Serialize for RcStr {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
// If it's too short, it's not worth interning.
// If it's too long, it's unlikely to be repeated.
if self.len() >= 3 && self.len() < 512 {
let id = intern_for_serialize(self);
if let Some(id) = id {
return serializer.serialize_u32(id);
}
}
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for RcStr {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use serde::de::Error;
#[derive(Deserialize)]
#[serde(untagged)]
enum Repr {
Id(u32),
String(String),
}
let repr = Repr::deserialize(deserializer)?;
match repr {
Repr::String(s) => Ok(RcStr::from(s)),
Repr::Id(id) => DE_MAP.with(|map| {
let s = map
.get(id as usize)
.ok_or_else(|| D::Error::custom(format!("failed to find id: {id}")))?;
Ok(s.clone())
}),
}
}
}
......@@ -42,10 +42,9 @@ rayon = { workspace = true }
ringmap = { workspace = true, features = ["serde"] }
rustc-hash = { workspace = true }
serde = { workspace = true }
serde_bytes = { workspace = true }
serde_json = { workspace = true }
serde_path_to_error = { workspace = true }
smallvec = { workspace = true, features = ["write"] }
smallvec = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
thread_local = { workspace = true }
......
......@@ -62,7 +62,6 @@ use crate::{
CachedDataItemValueRef, CellRef, CollectibleRef, CollectiblesRef, DirtyState,
InProgressCellState, InProgressState, InProgressStateInner, OutputValue, RootType,
},
interning_serde::RcStrToLocalId,
utils::{
bi_map::BiMap, chunked_vec::ChunkedVec, ptr_eq_arc::PtrEqArc, sharded::Sharded, swap_retain,
},
......@@ -963,14 +962,12 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
let task_snapshots = snapshot
.into_iter()
.filter_map(|iter| {
type SerializedData = (SmallVec<[u8; 16]>, RcStrToLocalId);
let mut iter = iter
.filter_map(
|(task_id, meta, data): (
_,
Option<Result<SerializedData>>,
Option<Result<SerializedData>>,
Option<Result<SmallVec<_>>>,
Option<Result<SmallVec<_>>>,
)| {
let meta = match meta {
Some(Ok(meta)) => {
......@@ -1172,8 +1169,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
.flatten();
let task_id = {
// Safety: `tx` is a valid transaction from `self.backend.backing_storage`.
if let Some((task_id, _rcstr_map)) = unsafe {
// We can ignore rcstr_map because those are all already stored in the database.
if let Some(task_id) = unsafe {
self.backing_storage
.forward_lookup_task_cache(tx.as_ref(), &task_type)
.expect("Failed to lookup task id")
......
......@@ -7,7 +7,6 @@ use turbo_tasks::{SessionId, TaskId, backend::CachedTaskType};
use crate::{
backend::{AnyOperation, TaskDataCategory},
data::CachedDataItem,
interning_serde::RcStrToLocalId,
utils::chunked_vec::ChunkedVec,
};
......@@ -49,10 +48,7 @@ pub trait BackingStorageSealed: 'static + Send + Sync {
fn next_session_id(&self) -> Result<SessionId>;
fn uncompleted_operations(&self) -> Result<Vec<AnyOperation>>;
#[allow(clippy::ptr_arg)]
fn serialize(
task: TaskId,
data: &Vec<CachedDataItem>,
) -> Result<(SmallVec<[u8; 16]>, RcStrToLocalId)>;
fn serialize(task: TaskId, data: &Vec<CachedDataItem>) -> Result<SmallVec<[u8; 16]>>;
fn save_snapshot<I>(
&self,
session_id: SessionId,
......@@ -64,8 +60,8 @@ pub trait BackingStorageSealed: 'static + Send + Sync {
I: Iterator<
Item = (
TaskId,
Option<(SmallVec<[u8; 16]>, RcStrToLocalId)>,
Option<(SmallVec<[u8; 16]>, RcStrToLocalId)>,
Option<SmallVec<[u8; 16]>>,
Option<SmallVec<[u8; 16]>>,
),
> + Send
+ Sync;
......@@ -77,7 +73,7 @@ pub trait BackingStorageSealed: 'static + Send + Sync {
&self,
tx: Option<&Self::ReadTransaction<'_>>,
key: &CachedTaskType,
) -> Result<Option<(TaskId, RcStrToLocalId)>>;
) -> Result<Option<TaskId>>;
/// # Safety
///
/// `tx` must be a transaction from this BackingStorage instance.
......
......@@ -11,8 +11,6 @@ pub enum KeySpace {
TaskData = 2,
ForwardTaskCache = 3,
ReverseTaskCache = 4,
StringInternMap = 5,
ReverseStringInternMap = 6,
}
pub trait KeyValueDatabase {
......
......@@ -122,7 +122,7 @@ impl KeyValueDatabase for TurboKeyValueDatabase {
}
pub struct TurboWriteBatch<'a> {
batch: turbo_persistence::WriteBatch<WriteBuffer<'static>, 7>,
batch: turbo_persistence::WriteBatch<WriteBuffer<'static>, 5>,
db: &'a Arc<TurboPersistence>,
compact_join_handle: &'a Mutex<Option<JoinHandle<Result<()>>>>,
initial_write: bool,
......
//! Exposed for usage in `turbo-tasks-backend`
use std::io::Write;
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_tasks::FxIndexSet;
pub fn to_vec<T>(config: &pot::Config, value: &T) -> anyhow::Result<(Vec<u8>, RcStrToLocalId)>
where
T: Serialize,
{
let mut vec = Vec::new();
let ser_map = to_writer(config, value, &mut vec)?;
Ok((vec, ser_map))
}
pub struct LocalIdToRcStr(Vec<RcStr>);
impl From<Vec<RcStr>> for LocalIdToRcStr {
fn from(value: Vec<RcStr>) -> Self {
Self(value)
}
}
#[derive(Default)]
pub struct RcStrToLocalId(FxIndexSet<RcStr>);
impl RcStrToLocalId {
pub fn iter(&self) -> impl Iterator<Item = &RcStr> {
self.0.iter()
}
}
#[derive(Default)]
pub struct LocalIdToGlobalId(Vec<u32>);
impl From<Vec<u32>> for LocalIdToGlobalId {
fn from(value: Vec<u32>) -> Self {
Self(value)
}
}
impl LocalIdToGlobalId {
pub fn len(&self) -> usize {
self.0.len()
}
pub fn iter(&self) -> impl '_ + Iterator<Item = u32> {
self.0.iter().copied()
}
pub fn write_to(&self, writer: &mut impl Write) -> anyhow::Result<()> {
let len = self.0.len() as u32;
for id in self.0.iter().rev() {
writer.write_all(&id.to_le_bytes())?;
}
writer.write_all(&len.to_le_bytes())?;
Ok(())
}
pub fn read_from_slice(mut bytes: &[u8]) -> anyhow::Result<(Self, &[u8])> {
let mut global_ids = Vec::new();
// Length is the last 4 bytes
let len = u32::from_le_bytes(bytes[bytes.len() - 4..].try_into().unwrap());
global_ids.reserve(len as usize);
bytes = &bytes[..bytes.len() - 4];
// Read the ids in reverse order
for _ in 0..len {
let id = u32::from_le_bytes(bytes[bytes.len() - 4..].try_into().unwrap());
global_ids.push(id);
bytes = &bytes[..bytes.len() - 4];
}
Ok((Self(global_ids), bytes))
}
}
pub fn to_writer<T, W>(config: &pot::Config, value: &T, writer: W) -> anyhow::Result<RcStrToLocalId>
where
T: Serialize,
W: Write,
{
let (result, ser_map) = turbo_rcstr::set_ser_map(|| config.serialize_into(value, writer));
result?;
Ok(RcStrToLocalId(ser_map))
}
pub fn from_slice<'de, T>(
config: &pot::Config,
bytes: &'de [u8],
de_map: &LocalIdToRcStr,
) -> anyhow::Result<T>
where
T: Deserialize<'de>,
{
turbo_rcstr::set_de_map(&de_map.0, || Ok(config.deserialize(bytes)?))
}
......@@ -3,21 +3,16 @@ use std::{
cmp::max,
env,
path::PathBuf,
sync::{
Arc, LazyLock, Mutex, OnceLock, PoisonError, Weak,
atomic::{AtomicU32, Ordering},
},
sync::{Arc, LazyLock, Mutex, PoisonError, Weak},
};
use anyhow::{Context, Result, anyhow, bail};
use anyhow::{Context, Result, anyhow};
use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator};
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use tracing::Span;
use turbo_rcstr::RcStr;
use turbo_tasks::{
FxDashMap, SessionId, TaskId,
SessionId, TaskId,
backend::CachedTaskType,
panic_hooks::{PanicHookGuard, register_panic_hook},
turbo_tasks_scope,
......@@ -38,16 +33,12 @@ use crate::{
},
},
db_invalidation::invalidation_reasons,
interning_serde,
interning_serde::{LocalIdToGlobalId, LocalIdToRcStr, RcStrToLocalId},
utils::chunked_vec::ChunkedVec,
};
const POT_CONFIG: pot::Config = pot::Config::new().compatibility(pot::Compatibility::V4);
fn pot_serialize_small_vec<T: Serialize>(
value: &T,
) -> Result<(SmallVec<[u8; 16]>, RcStrToLocalId)> {
fn pot_serialize_small_vec<T: Serialize>(value: &T) -> pot::Result<SmallVec<[u8; 16]>> {
struct SmallVecWrite<'l>(&'l mut SmallVec<[u8; 16]>);
impl std::io::Write for SmallVecWrite<'_> {
#[inline]
......@@ -69,8 +60,8 @@ fn pot_serialize_small_vec<T: Serialize>(
}
let mut output = SmallVec::new();
let ser_map = interning_serde::to_writer(&POT_CONFIG, value, SmallVecWrite(&mut output))?;
Ok((output, ser_map))
POT_CONFIG.serialize_into(value, SmallVecWrite(&mut output))?;
Ok(output)
}
fn pot_ser_symbol_map() -> pot::ser::SymbolMap {
......@@ -84,7 +75,6 @@ fn pot_de_symbol_list<'l>() -> pot::de::SymbolList<'l> {
const META_KEY_OPERATIONS: u32 = 0;
const META_KEY_NEXT_FREE_TASK_ID: u32 = 1;
const META_KEY_SESSION_ID: u32 = 2;
const META_KEY_NEXT_STRING_ID: u32 = 3;
struct IntKey([u8; 4]);
......@@ -308,16 +298,13 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
else {
return Ok(Vec::new());
};
let operations = deserialize_with_good_error(database, &tx, operations.borrow())?;
let operations = deserialize_with_good_error(operations.borrow())?;
Ok(operations)
}
get(&self.inner.database).context("Unable to read uncompleted operations from database")
}
fn serialize(
task: TaskId,
data: &Vec<CachedDataItem>,
) -> Result<(SmallVec<[u8; 16]>, RcStrToLocalId)> {
fn serialize(task: TaskId, data: &Vec<CachedDataItem>) -> Result<SmallVec<[u8; 16]>> {
serialize(task, data)
}
......@@ -332,8 +319,8 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
I: Iterator<
Item = (
TaskId,
Option<(SmallVec<[u8; 16]>, RcStrToLocalId)>,
Option<(SmallVec<[u8; 16]>, RcStrToLocalId)>,
Option<SmallVec<[u8; 16]>>,
Option<SmallVec<[u8; 16]>>,
),
> + Send
+ Sync,
......@@ -379,11 +366,7 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
let mut task_type_bytes = Vec::new();
for (task_type, task_id) in updates {
let task_id: u32 = *task_id;
let rcstr_map =
serialize_task_type(&task_type, &mut task_type_bytes, task_id)?;
let global_ids = save_strings_concurrent(batch, &rcstr_map)?;
global_ids.write_to(&mut task_type_bytes)?;
serialize_task_type(&task_type, &mut task_type_bytes, task_id)?;
batch
.put(
......@@ -453,11 +436,7 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
let mut task_type_bytes = Vec::new();
for (task_type, task_id) in task_cache_updates.into_iter().flatten() {
let task_id = *task_id;
let rcstr_map =
serialize_task_type(&task_type, &mut task_type_bytes, task_id)?;
let global_ids = save_strings_serial(batch, &rcstr_map)?;
global_ids.write_to(&mut task_type_bytes)?;
serialize_task_type(&task_type, &mut task_type_bytes, task_id)?;
batch
.put(
......@@ -495,30 +474,16 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
for (task_id, meta, data) in task_items_result?.into_iter().flatten() {
let key = IntKey::new(*task_id);
let key = key.as_ref();
if let Some((mut meta, rcstr_map)) = meta {
let global_ids = save_strings_serial(batch, &rcstr_map)?;
global_ids.write_to(&mut meta)?;
if let Some(meta) = meta {
batch
.put(
KeySpace::TaskMeta,
WriteBuffer::Borrowed(key),
WriteBuffer::SmallVec(meta),
)
.put(KeySpace::TaskMeta, WriteBuffer::Borrowed(key), meta)
.with_context(|| {
anyhow!("Unable to write meta items for {task_id}")
})?;
}
if let Some((mut data, rcstr_map)) = data {
let global_ids = save_strings_serial(batch, &rcstr_map)?;
global_ids.write_to(&mut data)?;
if let Some(data) = data {
batch
.put(
KeySpace::TaskData,
WriteBuffer::Borrowed(key),
WriteBuffer::SmallVec(data),
)
.put(KeySpace::TaskData, WriteBuffer::Borrowed(key), data)
.with_context(|| {
anyhow!("Unable to write data items for {task_id}")
})?;
......@@ -545,22 +510,21 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
&self,
tx: Option<&T::ReadTransaction<'_>>,
task_type: &CachedTaskType,
) -> Result<Option<(TaskId, RcStrToLocalId)>> {
) -> Result<Option<TaskId>> {
let inner = &*self.inner;
fn lookup<D: KeyValueDatabase>(
database: &D,
tx: &D::ReadTransaction<'_>,
task_type: &CachedTaskType,
) -> Result<Option<(TaskId, RcStrToLocalId)>> {
let (task_type, map) = interning_serde::to_vec(&POT_CONFIG, task_type)?;
) -> Result<Option<TaskId>> {
let task_type = POT_CONFIG.serialize(task_type)?;
let Some(bytes) = database.get(tx, KeySpace::ForwardTaskCache, &task_type)? else {
return Ok(None);
};
let bytes = bytes.borrow().try_into()?;
let id = TaskId::try_from(u32::from_le_bytes(bytes)).unwrap();
Ok(Some((id, map)))
Ok(Some(id))
}
let inner = &*self.inner;
if inner.database.is_empty() {
// Checking if the database is empty is a performance optimization
// to avoid serializing the task type.
......@@ -590,11 +554,7 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
else {
return Ok(None);
};
Ok(Some(deserialize_with_good_error(
database,
tx,
bytes.borrow(),
)?))
Ok(Some(deserialize_with_good_error(bytes.borrow())?))
}
inner
.with_tx(tx, |tx| lookup(&inner.database, tx, task_id))
......@@ -626,8 +586,7 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
else {
return Ok(Vec::new());
};
let result: Vec<CachedDataItem> =
deserialize_with_good_error(database, tx, bytes.borrow())?;
let result: Vec<CachedDataItem> = deserialize_with_good_error(bytes.borrow())?;
Ok(result)
}
inner
......@@ -640,55 +599,6 @@ impl<T: KeyValueDatabase + Send + Sync + 'static> BackingStorageSealed
}
}
fn restore_strings<D: KeyValueDatabase>(
database: &D,
tx: &D::ReadTransaction<'_>,
global_ids: &LocalIdToGlobalId,
) -> Result<LocalIdToRcStr> {
let mut map = Vec::with_capacity(global_ids.len());
for global_id in global_ids.iter() {
// First, check the in-memory cache
let rcstr = {
let cache = STRING_CACHE.lock().unwrap_or_else(PoisonError::into_inner);
cache.get(&global_id).cloned()
};
let rcstr = if let Some(rcstr) = rcstr {
// Cache hit
rcstr
} else {
// Cache miss, fetch from database
let Some(value) = database.get(
tx,
KeySpace::ReverseStringInternMap,
IntKey::new(global_id).as_ref(),
)?
else {
bail!("Unable to find string for {global_id}")
};
let mut rcstr = unsafe {
// Safety: We interned a rust string, so it is valid utf-8
RcStr::from(str::from_utf8_unchecked(value.borrow()))
};
// Update both caches
{
let mut cache = STRING_CACHE.lock().unwrap_or_else(PoisonError::into_inner);
rcstr = cache.entry(global_id).or_insert(rcstr).clone();
}
STRING_TO_ID_CACHE.insert(rcstr.clone(), global_id);
rcstr
};
map.push(rcstr);
}
Ok(map.into())
}
fn get_next_free_task_id<'a, S, C>(
batch: &mut WriteBatchRef<'_, 'a, S, C>,
) -> Result<u32, anyhow::Error>
......@@ -739,15 +649,8 @@ where
{
let _span =
tracing::trace_span!("update operations", operations = operations.len()).entered();
let (mut operations, rcstr_map) = pot_serialize_small_vec(&operations)
let operations = pot_serialize_small_vec(&operations)
.with_context(|| anyhow!("Unable to serialize operations"))?;
let global_ids = match batch {
WriteBatchRef::Serial(_) => save_strings_serial(batch, &rcstr_map)?,
WriteBatchRef::Concurrent(batch, _) => save_strings_concurrent(&**batch, &rcstr_map)?,
};
// Prepend the global ids to the operations
global_ids.write_to(&mut operations)?;
batch
.put(
KeySpace::Infra,
......@@ -756,23 +659,7 @@ where
)
.with_context(|| anyhow!("Unable to write operations"))?;
}
if let Some(next_string_id) = STRING_INTERN_ID.get() {
let _span = tracing::trace_span!("update next string id").entered();
let next_string_id = next_string_id.load(Ordering::SeqCst);
batch
.put(
KeySpace::Infra,
WriteBuffer::Borrowed(IntKey::new(META_KEY_NEXT_STRING_ID).as_ref()),
WriteBuffer::Borrowed(&next_string_id.to_le_bytes()),
)
.with_context(|| anyhow!("Unable to write next string id"))?;
}
batch.flush(KeySpace::Infra)?;
Ok(())
}
......@@ -780,9 +667,10 @@ fn serialize_task_type(
task_type: &Arc<CachedTaskType>,
mut task_type_bytes: &mut Vec<u8>,
task_id: u32,
) -> Result<RcStrToLocalId> {
) -> Result<()> {
task_type_bytes.clear();
let result = interning_serde::to_writer(&POT_CONFIG, task_type, &mut task_type_bytes)
POT_CONFIG
.serialize_into(&**task_type, &mut task_type_bytes)
.with_context(|| anyhow!("Unable to serialize task {task_id} cache key {task_type:?}"))?;
#[cfg(feature = "verify_serialization")]
{
......@@ -794,14 +682,14 @@ fn serialize_task_type(
panic!("Task type would not be deserializable {task_id}: {err:?}");
}
}
Ok(result)
Ok(())
}
type SerializedTasks = Vec<
Vec<(
TaskId,
Option<(SmallVec<[u8; 16]>, RcStrToLocalId)>,
Option<(SmallVec<[u8; 16]>, RcStrToLocalId)>,
Option<WriteBuffer<'static>>,
Option<WriteBuffer<'static>>,
)>,
>;
......@@ -813,8 +701,8 @@ where
I: Iterator<
Item = (
TaskId,
Option<(SmallVec<[u8; 16]>, RcStrToLocalId)>,
Option<(SmallVec<[u8; 16]>, RcStrToLocalId)>,
Option<SmallVec<[u8; 16]>>,
Option<SmallVec<[u8; 16]>>,
),
> + Send
+ Sync,
......@@ -833,20 +721,14 @@ where
if let Some(batch) = batch {
let key = IntKey::new(*task_id);
let key = key.as_ref();
if let Some((mut meta, rcstr_map)) = meta {
let global_ids = save_strings_concurrent(batch, &rcstr_map)?;
global_ids.write_to(&mut meta)?;
if let Some(meta) = meta {
batch.put(
KeySpace::TaskMeta,
WriteBuffer::Borrowed(key),
WriteBuffer::SmallVec(meta),
)?;
}
if let Some((mut data, rcstr_map)) = data {
let global_ids = save_strings_concurrent(batch, &rcstr_map)?;
global_ids.write_to(&mut data)?;
if let Some(data) = data {
batch.put(
KeySpace::TaskData,
WriteBuffer::Borrowed(key),
......@@ -855,7 +737,11 @@ where
}
} else {
// Store the new task data
result.push((task_id, meta, data));
result.push((
task_id,
meta.map(WriteBuffer::SmallVec),
data.map(WriteBuffer::SmallVec),
));
}
}
......@@ -865,10 +751,7 @@ where
.collect::<Result<Vec<_>>>()
}
fn serialize(
task: TaskId,
data: &Vec<CachedDataItem>,
) -> Result<(SmallVec<[u8; 16]>, RcStrToLocalId)> {
fn serialize(task: TaskId, data: &Vec<CachedDataItem>) -> Result<SmallVec<[u8; 16]>> {
Ok(match pot_serialize_small_vec(data) {
#[cfg(not(feature = "verify_serialization"))]
Ok(value) => value,
......@@ -914,128 +797,14 @@ fn serialize(
})
}
fn deserialize_with_good_error<'de, D: KeyValueDatabase, T: Deserialize<'de>>(
database: &D,
tx: &D::ReadTransaction<'_>,
data: &'de [u8],
) -> Result<T> {
let (global_ids, data) = LocalIdToGlobalId::read_from_slice(data)?;
let map = restore_strings(database, tx, &global_ids)?;
match interning_serde::from_slice::<T>(&POT_CONFIG, data, &map) {
fn deserialize_with_good_error<'de, T: Deserialize<'de>>(data: &'de [u8]) -> Result<T> {
match POT_CONFIG.deserialize(data) {
Ok(value) => Ok(value),
Err(error) => serde_path_to_error::deserialize::<'_, _, T>(
&mut pot_de_symbol_list().deserializer_for_slice(data)?,
)
.map_err(anyhow::Error::from)
.and(Err(error))
.and(Err(error.into()))
.context("Deserialization failed"),
}
}
/// Store the strings in the database and return the global ids.
fn save_strings_serial<'a>(
batch: &mut impl SerialWriteBatch<'a>,
strings: &RcStrToLocalId,
) -> Result<LocalIdToGlobalId> {
let mut global_ids = Vec::new();
for s in strings.iter() {
let (global_id, is_new) = get_string_id(batch, s)?;
if is_new {
batch.put(
KeySpace::StringInternMap,
WriteBuffer::Borrowed(s.as_bytes()),
WriteBuffer::Borrowed(&global_id.to_le_bytes()),
)?;
batch.put(
KeySpace::ReverseStringInternMap,
WriteBuffer::Borrowed(IntKey::new(global_id).as_ref()),
WriteBuffer::Borrowed(s.as_bytes()),
)?;
}
global_ids.push(global_id);
}
Ok(LocalIdToGlobalId::from(global_ids))
}
/// Store the strings in the database and return the global ids.
fn save_strings_concurrent<'a>(
batch: &impl ConcurrentWriteBatch<'a>,
strings: &RcStrToLocalId,
) -> Result<LocalIdToGlobalId> {
let mut global_ids = Vec::new();
for s in strings.iter() {
let (global_id, is_new) = get_string_id(batch, s)?;
if is_new {
batch.put(
KeySpace::StringInternMap,
WriteBuffer::Borrowed(s.as_bytes()),
WriteBuffer::Borrowed(&global_id.to_le_bytes()),
)?;
batch.put(
KeySpace::ReverseStringInternMap,
WriteBuffer::Borrowed(IntKey::new(global_id).as_ref()),
WriteBuffer::Borrowed(s.as_bytes()),
)?;
}
global_ids.push(global_id);
}
Ok(LocalIdToGlobalId::from(global_ids))
}
static STRING_INTERN_ID: OnceLock<AtomicU32> = OnceLock::new();
static STRING_CACHE: LazyLock<Mutex<FxHashMap<u32, RcStr>>> =
LazyLock::new(|| Mutex::new(FxHashMap::default()));
static STRING_TO_ID_CACHE: LazyLock<FxDashMap<RcStr, u32>> = LazyLock::new(FxDashMap::default);
/// Returns `(global_id, is_new)`
fn get_string_id<'a>(batch: &impl BaseWriteBatch<'a>, s: &RcStr) -> Result<(u32, bool)> {
// First check the synchronization cache
if let Some(global_id) = STRING_TO_ID_CACHE.get(s) {
return Ok((*global_id, false));
}
// Check the database
let original = batch.get(KeySpace::StringInternMap, s.as_bytes())?;
if let Some(bytes) = original {
let global_id = as_u32(bytes)?;
// Cache the result for future lookups
STRING_TO_ID_CACHE.insert(s.clone(), global_id);
STRING_CACHE.lock().unwrap().insert(global_id, s.clone());
return Ok((global_id, false));
}
// Allocate a new ID
let global_id = STRING_INTERN_ID
.get_or_try_init(|| {
let Some(bytes) = batch.get(
KeySpace::Infra,
IntKey::new(META_KEY_NEXT_STRING_ID).as_ref(),
)?
else {
return anyhow::Ok(AtomicU32::new(0));
};
let latest_id = as_u32(bytes)?;
Ok(AtomicU32::new(latest_id))
})?
.fetch_add(1, Ordering::Relaxed);
// Cache the new assignment to prevent duplicates within the same batch
match STRING_TO_ID_CACHE.entry(s.clone()) {
dashmap::Entry::Occupied(occupied_entry) => {
return Ok((*occupied_entry.get(), false));
}
dashmap::Entry::Vacant(vacant_entry) => {
vacant_entry.insert(global_id);
}
}
STRING_CACHE.lock().unwrap().insert(global_id, s.clone());
Ok((global_id, true))
}
......@@ -2,13 +2,12 @@
#![feature(associated_type_defaults)]
#![feature(iter_collect_into)]
#![feature(box_patterns)]
#![feature(once_cell_try)]
mod backend;
mod backing_storage;
mod data;
mod data_storage;
mod database;
mod interning_serde;
mod kv_backing_storage;
mod utils;
......
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