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

Deduplicate persisted filesystem paths

Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 8a54c08e
......@@ -2,7 +2,7 @@
pub mod macro_helpers;
pub mod serde_self_describing;
use std::{any::Any, ptr::copy_nonoverlapping};
use std::{any::Any, mem::transmute, ptr::copy_nonoverlapping};
use ::smallvec::SmallVec;
use bincode::{
......@@ -29,14 +29,101 @@ pub type TurboBincodeDecoder<'a> =
pub type AnyEncodeFn = fn(&dyn Any, &mut TurboBincodeEncoder<'_>) -> Result<(), EncodeError>;
pub type AnyDecodeFn<T> = fn(&mut TurboBincodeDecoder<'_>) -> Result<T, DecodeError>;
/// A stable reference to a string stored outside of an individual bincode value.
///
/// `namespace` identifies the owner of the string table (for example, a filesystem), while `hash`
/// identifies the string by content within that namespace.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct InternedStringKey {
pub namespace: [u8; 10],
pub hash: [u8; 16],
}
/// Collects external strings referenced by one independently encoded bincode value.
///
/// The value is borrowed and type-erased so a higher-level owner can cheaply clone its concrete
/// shared-string type without this crate depending on that type or allocating per occurrence.
pub trait InternedStringCollector {
fn insert(
&mut self,
key: InternedStringKey,
value: &(dyn Any + Send + Sync),
) -> Result<(), EncodeError>;
}
/// Resolves a persistence string reference to its concrete, allocation-sharing value.
///
/// The erased return value keeps this low-level crate independent of the concrete shared-string
/// implementation. Callers must downcast it to the type registered by the resolver.
pub trait InternedStringResolver: Send + Sync {
fn resolve(
&self,
key: InternedStringKey,
receiver: &mut dyn FnMut(&(dyn Any + Send + Sync)),
) -> Result<(), DecodeError>;
}
pub fn new_turbo_bincode_encoder(buf: &mut TurboBincodeBuffer) -> TurboBincodeEncoder<'_> {
EncoderImpl::new(TurboBincodeWriter::new(buf), TURBO_BINCODE_CONFIG)
}
pub fn new_turbo_bincode_encoder_with_interned_strings<'a>(
buf: &'a mut TurboBincodeBuffer,
interned_strings: &'a mut dyn InternedStringCollector,
) -> TurboBincodeEncoder<'a> {
EncoderImpl::new(
TurboBincodeWriter::with_interned_strings(buf, interned_strings),
TURBO_BINCODE_CONFIG,
)
}
pub fn new_turbo_bincode_decoder(buffer: &[u8]) -> TurboBincodeDecoder<'_> {
DecoderImpl::new(TurboBincodeReader::new(buffer), TURBO_BINCODE_CONFIG, ())
}
pub fn new_turbo_bincode_decoder_with_interned_strings<'a>(
buffer: &'a [u8],
resolver: &'a dyn InternedStringResolver,
) -> TurboBincodeDecoder<'a> {
DecoderImpl::new(
TurboBincodeReader::with_interned_strings(buffer, resolver),
TURBO_BINCODE_CONFIG,
(),
)
}
/// Runs `f` when `encoder` is the concrete encoder used by turbo persistence.
///
/// Hash encoders and other bincode encoders return `None`, allowing callers to preserve a semantic
/// encoding that is independent of persistence-only string references.
pub fn with_turbo_bincode_encoder<E: Encoder, T>(
encoder: &mut E,
f: impl FnOnce(&mut TurboBincodeEncoder<'_>) -> T,
) -> Option<T> {
if unty::type_equal::<E, TurboBincodeEncoder>() {
// SAFETY: This is the same type-and-lifetime specialization used by the helper macros in
// `macro_helpers`. `type_equal` checks the concrete layout and the reference cannot escape
// this function.
let encoder = unsafe { transmute::<&mut E, &mut TurboBincodeEncoder<'_>>(encoder) };
Some(f(encoder))
} else {
None
}
}
pub fn with_turbo_bincode_decoder<Context, D: Decoder<Context = Context>, T>(
decoder: &mut D,
f: impl FnOnce(&mut TurboBincodeDecoder<'_>) -> T,
) -> Option<T> {
if unty::type_equal::<D, TurboBincodeDecoder>() {
// SAFETY: See `with_turbo_bincode_encoder`.
let decoder = unsafe { transmute::<&mut D, &mut TurboBincodeDecoder<'_>>(decoder) };
Some(f(decoder))
} else {
None
}
}
/// Encode the value into a new [`SmallVec`] using a [`TurboBincodeEncoder`].
///
/// Note: If you can re-use a buffer, you should. That will always be cheaper than creating a new
......@@ -73,11 +160,31 @@ pub fn turbo_bincode_decode<T: Decode<()>>(buf: &[u8]) -> Result<T, DecodeError>
pub struct TurboBincodeWriter<'a> {
pub buffer: &'a mut TurboBincodeBuffer,
interned_strings: Option<&'a mut dyn InternedStringCollector>,
}
impl<'a> TurboBincodeWriter<'a> {
pub fn new(buffer: &'a mut TurboBincodeBuffer) -> Self {
Self { buffer }
Self {
buffer,
interned_strings: None,
}
}
pub fn with_interned_strings(
buffer: &'a mut TurboBincodeBuffer,
interned_strings: &'a mut dyn InternedStringCollector,
) -> Self {
Self {
buffer,
interned_strings: Some(interned_strings),
}
}
pub fn interned_strings_mut(&mut self) -> Option<&mut dyn InternedStringCollector> {
self.interned_strings
.as_mut()
.map(|collector| &mut **collector as &mut dyn InternedStringCollector)
}
}
......@@ -92,11 +199,29 @@ impl Writer for TurboBincodeWriter<'_> {
/// avoid some redundant bounds checks, and `pub` access to the underlying `buffer`.
pub struct TurboBincodeReader<'a> {
pub buffer: &'a [u8],
interned_string_resolver: Option<&'a dyn InternedStringResolver>,
}
impl<'a> TurboBincodeReader<'a> {
pub fn new(buffer: &'a [u8]) -> Self {
Self { buffer }
Self {
buffer,
interned_string_resolver: None,
}
}
pub fn with_interned_strings(
buffer: &'a [u8],
resolver: &'a dyn InternedStringResolver,
) -> Self {
Self {
buffer,
interned_string_resolver: Some(resolver),
}
}
pub fn interned_string_resolver(&self) -> Option<&dyn InternedStringResolver> {
self.interned_string_resolver
}
}
......
......@@ -33,7 +33,11 @@ use rustc_hash::{FxHashMap, FxHashSet, FxHasher};
use smallvec::{SmallVec, smallvec};
use tokio::time::{Duration, Instant};
use tracing::{Span, field::display, trace_span};
use turbo_bincode::{TurboBincodeBuffer, new_turbo_bincode_decoder, new_turbo_bincode_encoder};
use turbo_bincode::{
InternedStringKey, InternedStringResolver, TurboBincodeBuffer,
new_turbo_bincode_decoder_with_interned_strings,
new_turbo_bincode_encoder_with_interned_strings,
};
use turbo_tasks::{
CellId, DynTaskInputsStorage, RawVc, RawVcUnpacked, ReadCellOptions, ReadCellTracking,
ReadConsistency, ReadOutcome, ReadOutputOptions, ReadTracking, SharedReference,
......@@ -77,7 +81,7 @@ use crate::{
storage::Storage,
storage_schema::{TaskStorage, TaskStorageAccessors},
},
backing_storage::{SnapshotItem, compute_task_type_hash},
backing_storage::{EncodedTaskData, InternedStrings, SnapshotItem, compute_task_type_hash},
data::{
ActivenessState, CellRef, CollectibleRef, CollectiblesRef, Dirtyness, InProgressCellState,
InProgressState, InProgressStateInner, OutputValue, TransientTask,
......@@ -1378,7 +1382,7 @@ impl TurboTasksBackend {
data: &TaskStorage,
category: SpecificTaskDataCategory,
buffer: &mut TurboBincodeBuffer|
-> Option<TurboBincodeBuffer> {
-> Option<EncodedTaskData> {
match encode_task_data(task_id, data, category, buffer) {
Ok(encoded) => {
#[cfg(feature = "print_cache_item_size")]
......@@ -1386,8 +1390,8 @@ impl TurboTasksBackend {
let mut stats = task_cache_stats.lock();
let entry = stats.entry(TaskCacheStats::task_name(inner)).or_default();
match category {
SpecificTaskDataCategory::Meta => entry.add_meta(&encoded),
SpecificTaskDataCategory::Data => entry.add_data(&encoded),
SpecificTaskDataCategory::Meta => entry.add_meta(&encoded.bytes),
SpecificTaskDataCategory::Data => entry.add_data(&encoded.bytes),
}
}
Some(encoded)
......@@ -4163,16 +4167,38 @@ fn encode_task_data(
data: &TaskStorage,
category: SpecificTaskDataCategory,
scratch_buffer: &mut TurboBincodeBuffer,
) -> Result<TurboBincodeBuffer> {
) -> Result<EncodedTaskData> {
scratch_buffer.clear();
let mut encoder = new_turbo_bincode_encoder(scratch_buffer);
let mut interned_strings = InternedStrings::default();
let mut encoder =
new_turbo_bincode_encoder_with_interned_strings(scratch_buffer, &mut interned_strings);
data.encode(category, &mut encoder)?;
if cfg!(feature = "verify_serialization") {
struct CollectedResolver<'a>(&'a InternedStrings);
impl InternedStringResolver for CollectedResolver<'_> {
fn resolve(
&self,
key: InternedStringKey,
receiver: &mut dyn FnMut(&(dyn std::any::Any + Send + Sync)),
) -> Result<(), bincode::error::DecodeError> {
let value = self.0.get(&key).ok_or_else(|| {
bincode::error::DecodeError::OtherString(format!(
"missing collected interned string {key:?}"
))
})?;
receiver(value);
Ok(())
}
}
TaskStorage::new()
.decode(
category,
&mut new_turbo_bincode_decoder(&scratch_buffer[..]),
&mut new_turbo_bincode_decoder_with_interned_strings(
&scratch_buffer[..],
&CollectedResolver(&interned_strings),
),
)
.with_context(|| {
format!(
......@@ -4181,5 +4207,8 @@ fn encode_task_data(
)
})?;
}
Ok(SmallVec::from_slice(scratch_buffer))
Ok(EncodedTaskData {
bytes: SmallVec::from_slice(scratch_buffer),
interned_strings,
})
}
......@@ -1147,7 +1147,7 @@ mod tests {
use turbo_tasks::TaskId;
use super::{SpecificTaskDataCategory, Storage, TrackOutcome};
use crate::backing_storage::SnapshotItem;
use crate::backing_storage::{EncodedTaskData, SnapshotItem};
fn non_transient_task(id: u32) -> TaskId {
// TRANSIENT_TASK_BIT is 0x2000_0000; any id without that bit is non-transient.
......@@ -1175,7 +1175,10 @@ mod tests {
) -> SnapshotItem {
SnapshotItem::Put {
task_id,
meta: Some(TurboBincodeBuffer::default()),
meta: Some(EncodedTaskData {
bytes: TurboBincodeBuffer::default(),
interned_strings: Default::default(),
}),
data: None,
task_type_hash: None,
}
......
use std::cmp::max;
use std::{any::Any, cmp::max};
use turbo_bincode::TurboBincodeBuffer;
use bincode::error::EncodeError;
use smallvec::SmallVec;
use turbo_bincode::{InternedStringCollector, InternedStringKey, TurboBincodeBuffer};
use turbo_rcstr::RcStr;
use turbo_tasks::{
DynTaskInputs, RawVc, TaskId, backend::CachedTaskType, macro_helpers::NativeFunction,
};
......@@ -8,6 +11,51 @@ use turbo_tasks_hash::Xxh3Hash64Hasher;
pub type TaskTypeHash = [u8; 8];
#[derive(Default)]
pub struct InternedStrings(SmallVec<[(InternedStringKey, RcStr); 1]>);
impl InternedStrings {
pub fn get(&self, key: &InternedStringKey) -> Option<&RcStr> {
self.0
.iter()
.find_map(|(entry_key, value)| (entry_key == key).then_some(value))
}
pub fn into_entries(self) -> impl Iterator<Item = (InternedStringKey, RcStr)> {
self.0.into_iter()
}
}
impl InternedStringCollector for InternedStrings {
fn insert(
&mut self,
key: InternedStringKey,
value: &(dyn Any + Send + Sync),
) -> Result<(), EncodeError> {
let value = value.downcast_ref::<RcStr>().ok_or_else(|| {
EncodeError::OtherString(
"FileSystemPath collector received the wrong value type".into(),
)
})?;
if let Some(existing) = self.get(&key) {
if existing != value {
return Err(EncodeError::OtherString(format!(
"interned string identity collision for {key:?}"
)));
}
} else {
self.0.push((key, value.clone()));
}
Ok(())
}
}
/// One independently encoded task-data record and the external strings it references.
pub struct EncodedTaskData {
pub bytes: TurboBincodeBuffer,
pub interned_strings: InternedStrings,
}
/// A single item yielded by the snapshot iterator during persistence: either a put (persist a
/// modified task's meta/data + optionally register a new task's type) or a delete (tombstone a
/// GC-collected task's on-disk copy). Both ride the one iterator `save_snapshot` consumes, so
......@@ -16,9 +64,9 @@ pub enum SnapshotItem {
Put {
task_id: TaskId,
/// Serialized task meta data, if modified
meta: Option<TurboBincodeBuffer>,
meta: Option<EncodedTaskData>,
/// Serialized task data, if modified
data: Option<TurboBincodeBuffer>,
data: Option<EncodedTaskData>,
/// Task type for new tasks that need to be added to the task cache
task_type_hash: Option<TaskTypeHash>,
},
......
......@@ -6,6 +6,9 @@ pub enum KeySpace {
TaskMeta = 1,
TaskData = 2,
TaskCache = 3,
FileSystemPath = 4,
TaskMetaPathRefs = 5,
TaskDataPathRefs = 6,
}
impl KeySpace {
/// Constructs a [`KeySpace`] from its numeric index (i.e., the `usize` discriminant).
......@@ -19,6 +22,9 @@ impl KeySpace {
1 => KeySpace::TaskMeta,
2 => KeySpace::TaskData,
3 => KeySpace::TaskCache,
4 => KeySpace::FileSystemPath,
5 => KeySpace::TaskMetaPathRefs,
6 => KeySpace::TaskDataPathRefs,
_ => panic!("KeySpace index out of range"),
}
}
......@@ -29,6 +35,9 @@ impl KeySpace {
KeySpace::TaskMeta => "TaskMeta",
KeySpace::TaskData => "TaskData",
KeySpace::TaskCache => "TaskCache",
KeySpace::FileSystemPath => "FileSystemPath",
KeySpace::TaskMetaPathRefs => "TaskMetaPathRefs",
KeySpace::TaskDataPathRefs => "TaskDataPathRefs",
}
}
......@@ -51,6 +60,13 @@ impl KeySpace {
kind: FamilyKind::MultiValue,
compression: Compression::Lz4,
},
KeySpace::FileSystemPath | KeySpace::TaskMetaPathRefs | KeySpace::TaskDataPathRefs => {
FamilyConfig {
name: self.name(),
kind: FamilyKind::SingleValue,
compression: Compression::Lz4,
}
}
}
}
}
......@@ -26,7 +26,7 @@ mod parallel_scheduler;
pub(crate) use parallel_scheduler::TurboTasksParallelScheduler;
/// Number of key families, see [`KeySpace`] enum for their numbers.
pub const FAMILIES: usize = 4;
pub const FAMILIES: usize = 7;
const COMPACTION_MESSAGE: &str = "Finished filesystem cache database compaction";
......
use std::{
any::Any,
borrow::Borrow,
collections::{BTreeMap, HashMap, HashSet},
env,
path::PathBuf,
sync::{Arc, LazyLock, Mutex, PoisonError, Weak},
};
use anyhow::{Context, Result};
use bincode::error::DecodeError;
use smallvec::SmallVec;
use turbo_bincode::{new_turbo_bincode_decoder, turbo_bincode_decode, turbo_bincode_encode};
use turbo_bincode::{
InternedStringKey, InternedStringResolver, new_turbo_bincode_decoder_with_interned_strings,
turbo_bincode_decode, turbo_bincode_encode,
};
use turbo_persistence::CommitStats;
use turbo_rcstr::RcStr;
use turbo_tasks::{
DynTaskInputs, RawVc, TaskId,
macro_helpers::NativeFunction,
panic_hooks::{PanicHookGuard, register_panic_hook},
parallel,
};
use turbo_tasks_hash::hash_xxh3_hash128;
use crate::{
GitVersionInfo,
backend::{AnyOperation, SpecificTaskDataCategory, TtlCounter, storage_schema::TaskStorage},
backing_storage::{SnapshotItem, SnapshotMeta, compute_task_type_hash_from_components},
backing_storage::{
EncodedTaskData, InternedStrings, SnapshotItem, SnapshotMeta,
compute_task_type_hash_from_components,
},
database::{
db_invalidation::{StartupCacheState, check_db_invalidation_and_cleanup, invalidate_db},
db_versioning::handle_db_versioning,
......@@ -78,6 +89,142 @@ fn as_u32(bytes: impl Borrow<[u8]>) -> Result<u32> {
Ok(n)
}
const INTERNED_STRING_KEY_LEN: usize = 26;
const INTERNED_STRING_COUNT_LEN: usize = size_of::<u64>();
fn interned_string_key_bytes(key: InternedStringKey) -> [u8; INTERNED_STRING_KEY_LEN] {
let mut bytes = [0; INTERNED_STRING_KEY_LEN];
bytes[..10].copy_from_slice(&key.namespace);
bytes[10..].copy_from_slice(&key.hash);
bytes
}
fn decode_interned_string_key(bytes: &[u8]) -> Result<InternedStringKey> {
if bytes.len() != INTERNED_STRING_KEY_LEN {
anyhow::bail!(
"invalid interned string key length {}, expected {INTERNED_STRING_KEY_LEN}",
bytes.len()
);
}
Ok(InternedStringKey {
namespace: bytes[..10].try_into().unwrap(),
hash: bytes[10..].try_into().unwrap(),
})
}
fn encode_path_references(references: &[InternedStringKey]) -> Vec<u8> {
let mut bytes = Vec::with_capacity(references.len() * INTERNED_STRING_KEY_LEN);
for &reference in references {
bytes.extend_from_slice(&interned_string_key_bytes(reference));
}
bytes
}
fn decode_path_references(bytes: &[u8]) -> Result<Vec<InternedStringKey>> {
if !bytes.len().is_multiple_of(INTERNED_STRING_KEY_LEN) {
anyhow::bail!("invalid persisted FileSystemPath reference metadata length");
}
bytes
.as_chunks::<INTERNED_STRING_KEY_LEN>()
.0
.iter()
.map(|bytes| decode_interned_string_key(bytes))
.collect()
}
fn encode_dictionary_value(count: u64, value: &str) -> Vec<u8> {
let mut bytes = Vec::with_capacity(INTERNED_STRING_COUNT_LEN + value.len());
bytes.extend_from_slice(&count.to_le_bytes());
bytes.extend_from_slice(value.as_bytes());
bytes
}
fn decode_dictionary_value(bytes: &[u8]) -> Result<(u64, &str)> {
let (count, value) = bytes
.split_at_checked(INTERNED_STRING_COUNT_LEN)
.context("persisted FileSystemPath dictionary value is truncated")?;
let count = u64::from_le_bytes(count.try_into().unwrap());
if count == 0 {
anyhow::bail!("persisted FileSystemPath dictionary value has a zero reference count");
}
Ok((count, std::str::from_utf8(value)?))
}
fn path_reference_key_space(category: SpecificTaskDataCategory) -> KeySpace {
match category {
SpecificTaskDataCategory::Meta => KeySpace::TaskMetaPathRefs,
SpecificTaskDataCategory::Data => KeySpace::TaskDataPathRefs,
}
}
struct PathReferenceDelta {
key: InternedStringKey,
delta: i64,
value: Option<RcStr>,
}
fn update_path_references(
database: &TurboKeyValueDatabase,
batch: &TurboWriteBatch<'_>,
task_id: TaskId,
category: SpecificTaskDataCategory,
new_strings: Option<InternedStrings>,
) -> Result<Vec<PathReferenceDelta>> {
let key = IntKey::new(*task_id);
let key_space = path_reference_key_space(category);
let mut old_references = match database.get(key_space, key.as_ref())? {
Some(bytes) => decode_path_references(bytes.borrow())?,
None => Vec::new(),
};
old_references.sort_unstable();
old_references.dedup();
let mut new_entries = BTreeMap::new();
if let Some(new_strings) = new_strings {
for (key, value) in new_strings.into_entries() {
if let Some(existing) = new_entries.insert(key, value.clone())
&& existing != value
{
anyhow::bail!("interned string identity collision for {key:?}");
}
}
}
let new_references: Vec<_> = new_entries.keys().copied().collect();
if new_references.is_empty() {
if !old_references.is_empty() {
batch.delete(key_space, WriteBuffer::Borrowed(key.as_ref()))?;
}
} else if new_references != old_references {
batch.put(
key_space,
WriteBuffer::Borrowed(key.as_ref()),
WriteBuffer::Vec(encode_path_references(&new_references)),
)?;
}
let mut deltas = Vec::new();
for &reference in &old_references {
if !new_entries.contains_key(&reference) {
deltas.push(PathReferenceDelta {
key: reference,
delta: -1,
value: None,
});
}
}
for (reference, value) in new_entries {
deltas.push(PathReferenceDelta {
key: reference,
delta: i64::from(old_references.binary_search(&reference).is_err()),
// Keep the value even when membership is unchanged so an existing dictionary entry is
// checked for a content-hash collision on every rewritten record.
value: Some(value),
});
}
Ok(deltas)
}
// We want to invalidate the cache on panic for most users, but this is a band-aid to underlying
// problems in turbo-tasks.
//
......@@ -104,6 +251,11 @@ struct TurboBackingStorageInner {
base_path: Option<PathBuf>,
/// Used to skip calling [`invalidate_db`] when the database has already been invalidated.
invalidated: Mutex<bool>,
/// Serializes the read/modify/write transaction used for dictionary reference counts.
snapshot_lock: Mutex<()>,
/// Lazily resolved path strings. Values are removed when their durable reference count reaches
/// zero; clones returned to decoded values continue to own the allocation normally.
file_system_paths: Mutex<HashMap<InternedStringKey, RcStr>>,
/// We configure a panic hook to invalidate the cache. This guard cleans up our panic hook upon
/// drop.
_panic_hook_guard: Option<PanicHookGuard>,
......@@ -128,6 +280,8 @@ impl TurboBackingStorage {
database,
base_path: None,
invalidated: Mutex::new(false),
snapshot_lock: Mutex::new(()),
file_system_paths: Mutex::new(HashMap::new()),
_panic_hook_guard: None,
}),
}
......@@ -176,6 +330,8 @@ impl TurboBackingStorage {
database,
base_path: Some(base_path),
invalidated: Mutex::new(false),
snapshot_lock: Mutex::new(()),
file_system_paths: Mutex::new(HashMap::new()),
_panic_hook_guard: panic_hook_guard,
}
}),
......@@ -215,6 +371,126 @@ impl TurboBackingStorageInner {
.map(as_u32)
.transpose()
}
fn apply_path_reference_deltas(
&self,
batch: &TurboWriteBatch<'_>,
deltas: Vec<PathReferenceDelta>,
) -> Result<Vec<InternedStringKey>> {
let mut aggregated: BTreeMap<InternedStringKey, (i64, Option<RcStr>)> = BTreeMap::new();
for PathReferenceDelta { key, delta, value } in deltas {
let entry = aggregated.entry(key).or_default();
entry.0 += delta;
if let Some(value) = value {
if let Some(existing) = &entry.1
&& existing != &value
{
anyhow::bail!("interned string identity collision for {key:?}");
}
entry.1 = Some(value);
}
}
let mut removed = Vec::new();
for (key, (delta, supplied_value)) in aggregated {
if delta == 0 && supplied_value.is_none() {
continue;
}
let key_bytes = interned_string_key_bytes(key);
let current = self.database.get(KeySpace::FileSystemPath, &key_bytes)?;
let (current_count, current_value) = match current.as_ref() {
Some(bytes) => {
let (count, value) = decode_dictionary_value(bytes.borrow())?;
(count, Some(value.to_owned()))
}
None => (0, None),
};
if let Some(current_value) = current_value.as_deref()
&& hash_xxh3_hash128(current_value.as_bytes()).to_le_bytes() != key.hash
{
anyhow::bail!("persisted FileSystemPath dictionary digest mismatch for {key:?}");
}
if let Some(value) = supplied_value.as_ref() {
if hash_xxh3_hash128(value.as_bytes()).to_le_bytes() != key.hash {
anyhow::bail!("invalid content digest for interned string {key:?}");
}
if let Some(current_value) = current_value.as_deref()
&& current_value != value.as_str()
{
anyhow::bail!("interned string identity collision for {key:?}");
}
}
if delta == 0 {
if current_value.is_none() {
anyhow::bail!("existing FileSystemPath reference has no dictionary value");
}
continue;
}
let new_count = i128::from(current_count) + i128::from(delta);
if new_count < 0 {
anyhow::bail!("FileSystemPath reference count underflow for {key:?}");
}
if new_count == 0 {
batch.delete(KeySpace::FileSystemPath, WriteBuffer::Borrowed(&key_bytes))?;
removed.push(key);
continue;
}
let new_count =
u64::try_from(new_count).context("FileSystemPath reference count overflow")?;
let value = supplied_value
.as_ref()
.map(RcStr::as_str)
.or(current_value.as_deref())
.context("new FileSystemPath dictionary reference has no string value")?;
batch.put(
KeySpace::FileSystemPath,
WriteBuffer::Borrowed(&key_bytes),
WriteBuffer::Vec(encode_dictionary_value(new_count, value)),
)?;
}
Ok(removed)
}
}
impl InternedStringResolver for TurboBackingStorageInner {
fn resolve(
&self,
key: InternedStringKey,
receiver: &mut dyn FnMut(&(dyn Any + Send + Sync)),
) -> Result<(), DecodeError> {
// Keep this lock across the database read. Snapshot commits take the same lock while
// removing zero-reference cache entries, preventing a concurrent lookup from resurrecting
// an entry after its durable value has been deleted.
let mut paths = self
.file_system_paths
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let std::collections::hash_map::Entry::Vacant(entry) = paths.entry(key) {
let key_bytes = interned_string_key_bytes(key);
let bytes = self
.database
.get(KeySpace::FileSystemPath, &key_bytes)
.map_err(|err| DecodeError::OtherString(err.to_string()))?
.ok_or_else(|| {
DecodeError::OtherString(format!(
"missing persisted FileSystemPath dictionary entry {key:?}"
))
})?;
let (_, value) = decode_dictionary_value(bytes.borrow())
.map_err(|err| DecodeError::OtherString(err.to_string()))?;
if hash_xxh3_hash128(value.as_bytes()).to_le_bytes() != key.hash {
return Err(DecodeError::OtherString(format!(
"persisted FileSystemPath dictionary digest mismatch for {key:?}"
)));
}
entry.insert(RcStr::from(value));
}
receiver(paths.get(&key).unwrap());
Ok(())
}
}
impl TurboBackingStorage {
......@@ -273,17 +549,24 @@ impl TurboBackingStorage {
I: IntoIterator<Item = SnapshotItem> + Send + Sync,
{
let _span = tracing::info_span!("save snapshot", operations = operations.len()).entered();
let _snapshot_guard = self
.inner
.snapshot_lock
.lock()
.unwrap_or_else(PoisonError::into_inner);
let batch = self.inner.database.write_batch()?;
{
let span = tracing::trace_span!("update task data");
let mut snapshot_meta =
let seen_path_records = Mutex::new(HashSet::new());
let snapshot_results =
parallel::map_collect_owned::<_, _, Result<Vec<_>>>(snapshots, |shard: I| {
let _span = span.clone().entered();
let mut max_new_task_id = 0;
let mut data_items = 0;
let mut meta_items = 0;
let mut task_cache_items = 0;
let mut path_reference_deltas = Vec::new();
for item in shard {
match item {
SnapshotItem::Put {
......@@ -293,20 +576,59 @@ impl TurboBackingStorage {
task_type_hash,
} => {
let key = IntKey::new(*task_id);
let key = key.as_ref();
if let Some(meta) = meta {
if let Some(EncodedTaskData {
bytes,
interned_strings,
}) = meta
{
if !seen_path_records
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert((task_id, SpecificTaskDataCategory::Meta))
{
anyhow::bail!(
"duplicate meta snapshot record for {task_id}"
);
}
path_reference_deltas.extend(update_path_references(
&self.inner.database,
&batch,
task_id,
SpecificTaskDataCategory::Meta,
Some(interned_strings),
)?);
batch.put(
KeySpace::TaskMeta,
WriteBuffer::Borrowed(key),
WriteBuffer::SmallVec(meta),
WriteBuffer::Borrowed(key.as_ref()),
WriteBuffer::SmallVec(bytes),
)?;
meta_items += 1;
}
if let Some(data) = data {
if let Some(EncodedTaskData {
bytes,
interned_strings,
}) = data
{
if !seen_path_records
.lock()
.unwrap_or_else(PoisonError::into_inner)
.insert((task_id, SpecificTaskDataCategory::Data))
{
anyhow::bail!(
"duplicate data snapshot record for {task_id}"
);
}
path_reference_deltas.extend(update_path_references(
&self.inner.database,
&batch,
task_id,
SpecificTaskDataCategory::Data,
Some(interned_strings),
)?);
batch.put(
KeySpace::TaskData,
WriteBuffer::Borrowed(key),
WriteBuffer::SmallVec(data),
WriteBuffer::Borrowed(key.as_ref()),
WriteBuffer::SmallVec(bytes),
)?;
data_items += 1;
}
......@@ -315,7 +637,7 @@ impl TurboBackingStorage {
batch.put(
KeySpace::TaskCache,
WriteBuffer::Borrowed(&task_type_hash),
WriteBuffer::Borrowed(key),
WriteBuffer::Borrowed(key.as_ref()),
)?;
task_cache_items += 1;
max_new_task_id = max_new_task_id.max(*task_id);
......@@ -326,36 +648,83 @@ impl TurboBackingStorage {
task_type_hash,
} => {
let key = IntKey::new(*task_id);
let key = key.as_ref();
batch.delete(KeySpace::TaskMeta, WriteBuffer::Borrowed(key))?;
batch.delete(KeySpace::TaskData, WriteBuffer::Borrowed(key))?;
{
let mut seen = seen_path_records
.lock()
.unwrap_or_else(PoisonError::into_inner);
if !seen.insert((task_id, SpecificTaskDataCategory::Meta))
|| !seen.insert((task_id, SpecificTaskDataCategory::Data))
{
anyhow::bail!(
"duplicate deleted snapshot record for {task_id}"
);
}
}
path_reference_deltas.extend(update_path_references(
&self.inner.database,
&batch,
task_id,
SpecificTaskDataCategory::Meta,
None,
)?);
path_reference_deltas.extend(update_path_references(
&self.inner.database,
&batch,
task_id,
SpecificTaskDataCategory::Data,
None,
)?);
batch.delete(
KeySpace::TaskMeta,
WriteBuffer::Borrowed(key.as_ref()),
)?;
batch.delete(
KeySpace::TaskData,
WriteBuffer::Borrowed(key.as_ref()),
)?;
// TaskCache is MultiValue, delete just this id from the bucket.
batch.delete_value(
KeySpace::TaskCache,
WriteBuffer::Borrowed(&task_type_hash[..]),
WriteBuffer::Borrowed(key),
WriteBuffer::Borrowed(key.as_ref()),
)?;
}
}
}
Ok(SnapshotMeta {
data_items,
meta_items,
task_cache_items,
// The on-disk byte totals aren't known until the batch is committed
// below; they're filled in from `CommitStats` after `batch.commit()`.
bytes_written: 0,
bytes_deleted: 0,
max_next_task_id: max_new_task_id,
})
})?
.into_iter()
.reduce(|t1, t2| t1.merge(t2))
.unwrap_or_default();
Ok((
SnapshotMeta {
data_items,
meta_items,
task_cache_items,
// The on-disk byte totals aren't known until the batch is committed
// below; they're filled in from `CommitStats` after `batch.commit()`.
bytes_written: 0,
bytes_deleted: 0,
max_next_task_id: max_new_task_id,
},
path_reference_deltas,
))
})?;
let mut snapshot_meta = SnapshotMeta::default();
let mut path_reference_deltas = Vec::new();
for (meta, deltas) in snapshot_results {
snapshot_meta = snapshot_meta.merge(meta);
path_reference_deltas.extend(deltas);
}
let removed_paths = self
.inner
.apply_path_reference_deltas(&batch, path_reference_deltas)?;
let span = tracing::trace_span!("flush task data");
parallel::try_for_each(
&[KeySpace::TaskMeta, KeySpace::TaskData, KeySpace::TaskCache],
&[
KeySpace::TaskMeta,
KeySpace::TaskData,
KeySpace::TaskCache,
KeySpace::FileSystemPath,
KeySpace::TaskMetaPathRefs,
KeySpace::TaskDataPathRefs,
],
|&key_space| {
let _span = span.clone().entered();
// Safety: `map_collect_owned` has returned, so no concurrent `put` or `delete`
......@@ -372,7 +741,17 @@ impl TurboBackingStorage {
let _span = tracing::trace_span!("commit").entered();
// Byte totals are the physical on-disk bytes (post-compression, including .sst /
// .blob / .meta files) produced and removed by the commit.
// Hold the cache lock across commit + eviction. Resolvers hold the same lock while
// reading the dictionary, so none can resurrect an entry removed by this commit.
let mut file_system_paths = self
.inner
.file_system_paths
.lock()
.unwrap_or_else(PoisonError::into_inner);
let stats = batch.commit().context("Unable to commit snapshot")?;
for key in removed_paths {
file_system_paths.remove(&key);
}
snapshot_meta.bytes_written = stats.bytes_written;
snapshot_meta.bytes_deleted = stats.bytes_deleted;
}
......@@ -430,7 +809,7 @@ impl TurboBackingStorage {
return Ok(None);
};
let mut storage = TaskStorage::default();
let mut decoder = new_turbo_bincode_decoder(bytes.borrow());
let mut decoder = new_turbo_bincode_decoder_with_interned_strings(bytes.borrow(), inner);
storage
.decode(category, &mut decoder)
.with_context(|| format!("Failed to decode {category:?}"))?;
......@@ -459,7 +838,8 @@ impl TurboBackingStorage {
.map(|opt_bytes| {
let mut storage = TaskStorage::new();
if let Some(bytes) = opt_bytes {
let mut decoder = new_turbo_bincode_decoder(bytes.borrow());
let mut decoder =
new_turbo_bincode_decoder_with_interned_strings(bytes.borrow(), inner);
storage
.decode(category, &mut decoder)
.map_err(|e| anyhow::anyhow!("Failed to decode {category:?}: {e:?}"))?;
......@@ -754,4 +1134,189 @@ mod tests {
db.shutdown()?;
Ok(())
}
fn encoded_path_record(
namespace: [u8; 10],
value: &str,
) -> (InternedStringKey, EncodedTaskData) {
let key = InternedStringKey {
namespace,
hash: hash_xxh3_hash128(value.as_bytes()).to_le_bytes(),
};
let mut interned_strings = InternedStrings::default();
turbo_bincode::InternedStringCollector::insert(
&mut interned_strings,
key,
&RcStr::from(value),
)
.unwrap();
(
key,
EncodedTaskData {
bytes: Default::default(),
interned_strings,
},
)
}
fn resolve_path(
storage: &TurboBackingStorage,
key: InternedStringKey,
) -> Result<RcStr, DecodeError> {
let mut result = None;
storage.inner.resolve(key, &mut |value| {
result = value.downcast_ref::<RcStr>().cloned()
})?;
result.ok_or_else(|| DecodeError::OtherString("wrong resolved test value type".into()))
}
fn dictionary_entry(
storage: &TurboBackingStorage,
key: InternedStringKey,
) -> Result<Option<(u64, String)>> {
let key = interned_string_key_bytes(key);
storage
.inner
.database
.get(KeySpace::FileSystemPath, &key)?
.map(|bytes| {
let (count, value) = decode_dictionary_value(bytes.borrow())?;
Ok((count, value.to_owned()))
})
.transpose()
}
#[tokio::test(flavor = "multi_thread")]
async fn file_system_path_dictionary_reclaims_final_record_reference() -> Result<()> {
let tempdir = tempfile::tempdir()?;
let db = TurboKeyValueDatabase::new(tempdir.path().to_path_buf(), TEST_STORAGE_OPTIONS)?;
let storage = TurboBackingStorage::new_in_memory(db);
let namespace = [42; 10];
let first_id = TaskId::try_from(301u32).unwrap();
let second_id = TaskId::try_from(302u32).unwrap();
let old_path = "src/a/realistically/long/shared/file-system-path.ts";
let new_path = "src/a/different/realistically/long/file-system-path.ts";
let (old_key, first_record) = encoded_path_record(namespace, old_path);
let (_, second_record) = encoded_path_record(namespace, old_path);
storage.save_snapshot(
Vec::new(),
None,
vec![vec![
SnapshotItem::Put {
task_id: first_id,
meta: Some(first_record),
data: None,
task_type_hash: None,
},
SnapshotItem::Put {
task_id: second_id,
meta: Some(second_record),
data: None,
task_type_hash: None,
},
]],
)?;
assert_eq!(
dictionary_entry(&storage, old_key)?,
Some((2, old_path.to_owned()))
);
// A forced content-identity collision aborts the whole snapshot before commit.
let mut colliding_strings = InternedStrings::default();
turbo_bincode::InternedStringCollector::insert(
&mut colliding_strings,
old_key,
&RcStr::from("a different string with the forced old identity"),
)?;
assert!(
storage
.save_snapshot(
Vec::new(),
None,
vec![vec![SnapshotItem::Put {
task_id: first_id,
meta: Some(EncodedTaskData {
bytes: Default::default(),
interned_strings: colliding_strings,
}),
data: None,
task_type_hash: None,
}]],
)
.is_err()
);
assert_eq!(
dictionary_entry(&storage, old_key)?,
Some((2, old_path.to_owned()))
);
// Reopening retains the durable dictionary and reconstructs the sharing cache lazily.
storage.inner.database.shutdown()?;
drop(storage);
let db = TurboKeyValueDatabase::new(tempdir.path().to_path_buf(), TEST_STORAGE_OPTIONS)?;
let storage = TurboBackingStorage::new_in_memory(db);
// Lazy resolution clones the same RcStr allocation.
let first = resolve_path(&storage, old_key)?;
let second = resolve_path(&storage, old_key)?;
assert!(std::ptr::eq(
first.as_str().as_ptr(),
second.as_str().as_ptr()
));
// Rewriting one record moves only its membership to the new path.
let (new_key, replacement) = encoded_path_record(namespace, new_path);
storage.save_snapshot(
Vec::new(),
None,
vec![vec![SnapshotItem::Put {
task_id: first_id,
meta: Some(replacement),
data: None,
task_type_hash: None,
}]],
)?;
assert_eq!(
dictionary_entry(&storage, old_key)?,
Some((1, old_path.to_owned()))
);
assert_eq!(
dictionary_entry(&storage, new_key)?,
Some((1, new_path.to_owned()))
);
// Deleting the final records removes both dictionary values and their metadata.
for task_id in [second_id, first_id] {
storage.save_snapshot(
Vec::new(),
None,
vec![vec![SnapshotItem::Delete {
task_id,
task_type_hash: [0; 8],
}]],
)?;
}
assert_eq!(dictionary_entry(&storage, old_key)?, None);
assert_eq!(dictionary_entry(&storage, new_key)?, None);
assert!(resolve_path(&storage, old_key).is_err());
assert!(resolve_path(&storage, new_key).is_err());
assert!(
storage
.inner
.database
.get(KeySpace::TaskMetaPathRefs, &(*first_id).to_le_bytes())?
.is_none()
);
assert!(
storage
.inner
.database
.get(KeySpace::TaskMetaPathRefs, &(*second_id).to_le_bytes())?
.is_none()
);
storage.inner.database.shutdown()?;
Ok(())
}
}
......@@ -4,14 +4,21 @@ use std::{borrow::Cow, error::Error, fmt, path::MAIN_SEPARATOR};
use anyhow::{Result, bail};
use auto_hash_map::{AutoMap, AutoSet};
use bincode::{Decode, Encode};
use bincode::{
Decode, Encode,
de::Decoder,
enc::Encoder,
error::{DecodeError, EncodeError},
impl_borrow_decode,
};
use indexmap::IndexSet;
use turbo_bincode::{InternedStringKey, with_turbo_bincode_decoder, with_turbo_bincode_encoder};
use turbo_rcstr::RcStr;
use turbo_tasks::{
Completion, NonLocalValue, ResolvedVc, ValueToString, ValueToStringRef, Vc, trace::TraceRawVcs,
turbobail, turbofmt,
Completion, NonLocalValue, RawVcUnpacked, ResolvedVc, ValueToString, ValueToStringRef, Vc,
trace::TraceRawVcs, turbobail, turbofmt,
};
use turbo_tasks_hash::HashAlgorithm;
use turbo_tasks_hash::{HashAlgorithm, hash_xxh3_hash128};
use turbo_unix_path::{
get_parent_path, get_relative_path_to, get_relative_request_to, join_path, normalize_path,
};
......@@ -25,12 +32,134 @@ use crate::{
};
#[derive(Debug, Clone, Hash)]
#[turbo_tasks::value(shared, task_input)]
#[turbo_tasks::value(shared, task_input, serialization = "custom")]
pub struct FileSystemPath {
pub fs: ResolvedVc<Box<dyn FileSystem>>,
pub path: RcStr,
}
const INLINE_PATH_TAG: u8 = 0;
const INTERNED_PATH_TAG: u8 = 1;
const INTERNED_PATH_HASH_BYTES: usize = size_of::<u128>();
// The backing store tracks each record's external references as an exact 10-byte filesystem cell
// identity plus the content digest. Include that cost when deciding whether interning saves bytes.
const INTERNED_PATH_REFERENCE_METADATA_BYTES: usize = 10 + INTERNED_PATH_HASH_BYTES;
fn filesystem_namespace(fs: &ResolvedVc<Box<dyn FileSystem>>) -> Option<[u8; 10]> {
match Vc::into_raw(**fs).unpack() {
RawVcUnpacked::TaskCell(task, cell) => {
let mut identity = [0; 10];
identity[..4].copy_from_slice(&(*task).to_le_bytes());
identity[4..6].copy_from_slice(&(*cell.type_id()).to_le_bytes());
identity[6..].copy_from_slice(&cell.index().to_le_bytes());
Some(identity)
}
RawVcUnpacked::TaskOutput(_) | RawVcUnpacked::LocalOutput(..) => None,
}
}
fn bincode_varint_len(value: usize) -> usize {
match value {
0..=250 => 1,
251..=0xffff => 3,
0x1_0000..=0xffff_ffff => 5,
_ => 9,
}
}
fn should_intern_path(path: &str) -> bool {
bincode_varint_len(path.len()) + path.len()
> INTERNED_PATH_HASH_BYTES + INTERNED_PATH_REFERENCE_METADATA_BYTES
}
impl Encode for FileSystemPath {
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
self.fs.encode(encoder)?;
if let Some(result) = with_turbo_bincode_encoder(encoder, |encoder| {
// Only a persistence encoder that is collecting references can use the reference form,
// and only when it is smaller than the path itself. Everything else — including hash
// encoders handled below — keeps the self-contained inline form.
let interned_key = should_intern_path(&self.path)
.then(|| filesystem_namespace(&self.fs))
.flatten()
.filter(|_| encoder.writer().interned_strings_mut().is_some())
.map(|namespace| InternedStringKey {
namespace,
hash: hash_xxh3_hash128(self.path.as_bytes()).to_le_bytes(),
});
if let Some(key) = interned_key {
encoder
.writer()
.interned_strings_mut()
.expect("checked above")
.insert(key, &self.path)?;
INTERNED_PATH_TAG.encode(encoder)?;
key.hash.encode(encoder)
} else {
INLINE_PATH_TAG.encode(encoder)?;
self.path.encode(encoder)
}
}) {
return result;
}
// Hash encoders deliberately see the semantic path bytes, not persistence dictionary state.
self.path.encode(encoder)
}
}
impl<Context> Decode<Context> for FileSystemPath {
fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
let fs = ResolvedVc::decode(decoder)?;
if let Some(result) = with_turbo_bincode_decoder(decoder, |decoder| {
let tag = u8::decode(decoder)?;
let path = match tag {
INLINE_PATH_TAG => RcStr::decode(decoder)?,
INTERNED_PATH_TAG => {
let hash = <[u8; 16]>::decode(decoder)?;
let namespace = filesystem_namespace(&fs).ok_or_else(|| {
DecodeError::OtherString(
"FileSystemPath filesystem is not a resolved task cell".into(),
)
})?;
let resolver =
decoder.reader().interned_string_resolver().ok_or_else(|| {
DecodeError::OtherString(
"interned FileSystemPath decoded without a string resolver".into(),
)
})?;
let mut path = None;
resolver.resolve(InternedStringKey { namespace, hash }, &mut |value| {
path = value.downcast_ref::<RcStr>().cloned()
})?;
path.ok_or_else(|| {
DecodeError::OtherString(
"FileSystemPath string resolver returned the wrong value type".into(),
)
})?
}
tag => {
return Err(DecodeError::OtherString(format!(
"invalid FileSystemPath path tag {tag}"
)));
}
};
Ok(Self { fs, path })
}) {
return result;
}
Ok(Self {
fs,
path: RcStr::decode(decoder)?,
})
}
}
impl_borrow_decode!(FileSystemPath);
impl ValueToStringRef for FileSystemPath {
async fn to_string_ref(&self) -> Result<RcStr> {
turbofmt!("[{}]/{}", self.fs, self.path).await
......@@ -784,13 +913,243 @@ async fn hash_file(
#[cfg(test)]
mod tests {
use std::{any::Any, collections::HashMap};
use bincode::error::DecodeError;
use smallvec::SmallVec;
use turbo_bincode::{
InternedStringCollector, InternedStringResolver, TurboBincodeBuffer, new_hash_encoder,
new_turbo_bincode_decoder_with_interned_strings,
new_turbo_bincode_encoder_with_interned_strings, turbo_bincode_decode,
turbo_bincode_encode,
};
use turbo_rcstr::rcstr;
use turbo_tasks::Vc;
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_hash::Xxh3Hash128Hasher;
use super::*;
use crate::VirtualFileSystem;
#[derive(Default)]
struct TestCollector(SmallVec<[(InternedStringKey, RcStr); 2]>);
impl InternedStringCollector for TestCollector {
fn insert(
&mut self,
key: InternedStringKey,
value: &(dyn Any + Send + Sync),
) -> Result<(), EncodeError> {
let value = value.downcast_ref::<RcStr>().ok_or_else(|| {
EncodeError::OtherString("unexpected test collector value type".into())
})?;
if let Some((_, existing)) = self.0.iter().find(|(entry_key, _)| *entry_key == key) {
if existing != value {
return Err(EncodeError::OtherString("forced test collision".into()));
}
} else {
self.0.push((key, value.clone()));
}
Ok(())
}
}
struct TestResolver(HashMap<InternedStringKey, RcStr>);
impl InternedStringResolver for TestResolver {
fn resolve(
&self,
key: InternedStringKey,
receiver: &mut dyn FnMut(&(dyn Any + Send + Sync)),
) -> Result<(), DecodeError> {
let value = self
.0
.get(&key)
.ok_or_else(|| DecodeError::OtherString(format!("missing test string {key:?}")))?;
receiver(value);
Ok(())
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn bincode_interns_long_paths_deterministically() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async move {
let fs = Vc::upcast::<Box<dyn FileSystem>>(VirtualFileSystem::new())
.to_resolved()
.await?;
let path_text = "src/a/realistically/long/repeated/file-system-path.ts";
let path = FileSystemPath::new_normalized_unchecked(fs, path_text.into());
// Persistence-aware encoding still keeps paths inline when reference metadata would
// cost more than the path itself.
let short_path = FileSystemPath::new_normalized_unchecked(fs, "src/short.ts".into());
let mut short_bytes = TurboBincodeBuffer::new();
let mut short_strings = TestCollector::default();
short_path.encode(&mut new_turbo_bincode_encoder_with_interned_strings(
&mut short_bytes,
&mut short_strings,
))?;
assert!(short_strings.0.is_empty());
assert_eq!(
turbo_bincode_decode::<FileSystemPath>(&short_bytes)?.path,
short_path.path
);
// A regular turbo-bincode call has no external dictionary and stays self-contained.
let inline = turbo_bincode_encode(&path)?;
let inline_decoded: FileSystemPath = turbo_bincode_decode(&inline)?;
assert_eq!(inline_decoded.fs, path.fs);
assert_eq!(inline_decoded.path, path.path);
let encode_referenced = || -> anyhow::Result<(TurboBincodeBuffer, TestCollector)> {
let mut bytes = TurboBincodeBuffer::new();
let mut strings = TestCollector::default();
path.encode(&mut new_turbo_bincode_encoder_with_interned_strings(
&mut bytes,
&mut strings,
))?;
Ok((bytes, strings))
};
let (referenced, strings) = encode_referenced()?;
let (referenced_again, _) = encode_referenced()?;
assert_eq!(referenced, referenced_again);
assert!(referenced.len() < inline.len());
// Task-cache hashing stays byte-for-byte equivalent to the semantic struct fields.
let mut actual_hash = Xxh3Hash128Hasher::new();
path.encode(&mut new_hash_encoder(&mut actual_hash))?;
let mut expected_hash = Xxh3Hash128Hasher::new();
{
let mut encoder = new_hash_encoder(&mut expected_hash);
path.fs.encode(&mut encoder)?;
path.path.encode(&mut encoder)?;
}
assert_eq!(actual_hash.finish(), expected_hash.finish());
// Reference-form data cannot be decoded without its owning persistence resolver.
assert!(turbo_bincode_decode::<FileSystemPath>(&referenced).is_err());
let entries = strings.0;
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].1, path_text);
let (entry_key, entry_value) = entries.into_iter().next().unwrap();
// Encountering another path first cannot change this path's content-derived identity.
let other_path = FileSystemPath::new_normalized_unchecked(
fs,
"src/another/realistically/long/file-system-path.ts".into(),
);
let mut ordered_bytes = TurboBincodeBuffer::new();
let mut ordered_strings = TestCollector::default();
{
let mut encoder = new_turbo_bincode_encoder_with_interned_strings(
&mut ordered_bytes,
&mut ordered_strings,
);
other_path.encode(&mut encoder)?;
path.encode(&mut encoder)?;
path.encode(&mut encoder)?;
}
assert_eq!(ordered_strings.0.len(), 2);
assert_eq!(
ordered_strings
.0
.iter()
.find(|(_, value)| *value == path.path)
.map(|(key, _)| *key),
Some(entry_key)
);
let resolver = TestResolver(HashMap::from([(entry_key, entry_value)]));
let decode = || -> Result<FileSystemPath, DecodeError> {
let mut decoder =
new_turbo_bincode_decoder_with_interned_strings(&referenced, &resolver);
FileSystemPath::decode(&mut decoder)
};
let first = decode()?;
let second = decode()?;
assert_eq!(first.path, path.path);
assert!(std::ptr::eq(
first.path.as_str().as_ptr(),
second.path.as_str().as_ptr()
));
// Identity conflicts are errors instead of silently aliasing different strings.
let mut collision = TestCollector::default();
collision.insert(entry_key, &RcStr::from(path_text))?;
assert!(
collision
.insert(entry_key, &RcStr::from("a different long path"))
.is_err()
);
anyhow::Ok(())
})
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[ignore = "manual encode-time and storage measurement"]
async fn measure_repeated_file_system_path_encoding() {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async move {
let fs = Vc::upcast::<Box<dyn FileSystem>>(VirtualFileSystem::new())
.to_resolved()
.await?;
let path_text =
"node_modules/a-package/src/a/realistically/long/repeated/file-system-path.ts";
let path = FileSystemPath::new_normalized_unchecked(fs, path_text.into());
const ITERATIONS: usize = 1_000_000;
let start = std::time::Instant::now();
let mut inline_bytes = 0;
for _ in 0..ITERATIONS {
inline_bytes += std::hint::black_box(turbo_bincode_encode(&path)?).len();
}
let inline_time = start.elapsed();
let start = std::time::Instant::now();
let mut reference_bytes = 0;
for _ in 0..ITERATIONS {
let mut bytes = TurboBincodeBuffer::new();
let mut strings = TestCollector::default();
path.encode(&mut new_turbo_bincode_encoder_with_interned_strings(
&mut bytes,
&mut strings,
))?;
reference_bytes += std::hint::black_box(bytes).len();
assert_eq!(strings.0.len(), 1);
}
let reference_time = start.elapsed();
let reference_metadata_bytes = ITERATIONS * INTERNED_STRING_KEY_LEN_FOR_MEASUREMENT;
let dictionary_bytes = size_of::<u64>() + path_text.len();
let total_dictionary_backed =
reference_bytes + reference_metadata_bytes + dictionary_bytes;
assert!(total_dictionary_backed < inline_bytes);
println!(
"{ITERATIONS} repeated FileSystemPath values: inline={inline_bytes} bytes in \
{inline_time:?}; references={reference_bytes} + \
metadata={reference_metadata_bytes} + dictionary={dictionary_bytes} = \
{total_dictionary_backed} bytes in {reference_time:?}"
);
anyhow::Ok(())
})
.await
.unwrap();
}
/// The backing storage metadata uses a 10-byte filesystem identity and a 16-byte digest.
const INTERNED_STRING_KEY_LEN_FOR_MEASUREMENT: usize = 26;
/// `turbo-unix-path` covers how the relative path itself is computed, so this only pins what
/// this layer adds: that each method reaches for the form it names, and that neither crosses
/// between filesystems.
......
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