Unverified Commit 287fd7e7 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

turbo-persistence: pin referenced BlockCache entries to prevent eviction (#92361)

### What?

Implements
[`quick_cache::Lifecycle`](https://docs.rs/quick_cache/latest/quick_cache/#lifecycle-hooks)
hooks for the `BlockCache` in turbo-persistence. A new
`BlockCacheLifecycle` struct overrides `is_pinned` to check whether the
`ArcBytes` value's backing `Arc` has a strong count > 1, indicating it
is still referenced outside the cache.

When `is_pinned` returns `true`, the cache's eviction algorithm
(Clock-PRO / S3-FIFO) skips the entry instead of evicting it.

### Why?

Without pinning, the cache can evict blocks that are still in use — the
caller holds an `ArcBytes` clone (which shares the `Arc` backing), so
the data isn't lost, but the cache slot is wasted. When the caller
finishes and the entry is looked up again, it results in an unnecessary
cache miss and re-read/decompress from disk.

By checking `Arc::strong_count > 1` in `is_pinned`, we avoid evicting
entries that are actively referenced, improving cache hit rates under
concurrent access.

### How?

**`ArcBytes::is_shared()`** (`arc_bytes.rs`):
- Returns `true` when the backing `Arc<[u8]>` has `strong_count > 1`
(i.e., someone outside the cache holds a clone).
- Mmap-backed entries always return `false` — the mmap `Arc` is shared
across all slices from the same file, so checking its `strong_count`
would make them permanently unevictable. This is fine because #92390
already drops mmap blocks from the cache entirely.

**`BlockCacheLifecycle`** (`static_sorted_file.rs`):
- Implements `quick_cache::Lifecycle<(u32, u16), ArcBytes>` with
`RequestState = ()`.
- `is_pinned` delegates to `val.is_shared()`.
- `begin_request` and `on_evict` are no-ops since we only need the
pinning behavior.

**`BlockCache` type alias** updated to include `BlockCacheLifecycle` as
the 5th generic parameter. All call sites use `Default::default()` for
construction, so no call-site changes were needed.

**Test cleanup**: Removed the redundant `TestBlockCache` type alias (and
its unused imports) in the builder tests in favor of the existing
`BlockCache` alias.

<!-- NEXT_JS_LLM_PR -->

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent b9a14768
......@@ -89,6 +89,17 @@ impl ArcBytes {
pub fn is_mmap_backed(&self) -> bool {
matches!(self.backing, Backing::Mmap { .. })
}
/// Returns `true` if the backing `Arc` allocation is shared (i.e., there
/// are other `Arc` clones referencing the same data outside the cache).
/// Always returns `false` for mmap-backed bytes, since the mmap `Arc` is
/// shared across all slices from the same file and is not a useful signal.
pub fn is_shared_arc(&self) -> bool {
match &self.backing {
Backing::Arc { _backing } => Arc::strong_count(_backing) > 1,
Backing::Mmap { .. } => false,
}
}
}
impl SharedBytes for ArcBytes {
......
......@@ -74,7 +74,8 @@ pub use key::{KeyBase, QueryKey, StoreKey, hash_key};
pub use meta_file::MetaEntryFlags;
pub use parallel_scheduler::{ParallelScheduler, SerialScheduler};
pub use static_sorted_file::{
BlockCache, BlockWeighter, SstLookupResult, StaticSortedFile, StaticSortedFileMetaData,
BlockCache, BlockCacheLifecycle, BlockWeighter, SstLookupResult, StaticSortedFile,
StaticSortedFileMetaData,
};
pub use static_sorted_file_builder::{
BLOCK_HEADER_SIZE, Entry, EntryValue, StreamingSstWriter, write_static_stored_file,
......
......@@ -12,7 +12,7 @@ use std::{
use anyhow::{Context, Result, bail, ensure};
use memmap2::Mmap;
use quick_cache::sync::GuardResult;
use quick_cache::{Lifecycle, sync::GuardResult};
use rustc_hash::FxHasher;
use smallvec::SmallVec;
......@@ -100,8 +100,33 @@ impl quick_cache::Weighter<(u32, u16), ArcBytes> for BlockWeighter {
}
}
pub type BlockCache =
quick_cache::sync::Cache<(u32, u16), ArcBytes, BlockWeighter, BuildHasherDefault<FxHasher>>;
/// Lifecycle hooks for the block cache that prevent eviction of entries
/// still referenced outside the cache (i.e., with `Arc` strong count > 1).
#[derive(Clone, Default)]
pub struct BlockCacheLifecycle;
impl Lifecycle<(u32, u16), ArcBytes> for BlockCacheLifecycle {
type RequestState = ();
#[inline]
fn is_pinned(&self, _key: &(u32, u16), val: &ArcBytes) -> bool {
val.is_shared_arc()
}
#[inline]
fn begin_request(&self) -> Self::RequestState {}
#[inline]
fn on_evict(&self, _state: &mut Self::RequestState, _key: (u32, u16), _val: ArcBytes) {}
}
pub type BlockCache = quick_cache::sync::Cache<
(u32, u16),
ArcBytes,
BlockWeighter,
BuildHasherDefault<FxHasher>,
BlockCacheLifecycle,
>;
/// Trait abstracting value block reading for `handle_key_match_generic`.
///
......
......@@ -1224,25 +1224,17 @@ impl<W: Write> IndexBlockBuilder<W> {
#[cfg(test)]
mod tests {
use std::hash::BuildHasherDefault;
use quick_cache::sync::Cache;
use rustc_hash::FxHasher;
use super::*;
use crate::{
key::hash_key,
lookup_entry::LookupValue,
static_sorted_file::{
BlockWeighter, SstLookupResult, StaticSortedFile, StaticSortedFileMetaData,
BlockCache, SstLookupResult, StaticSortedFile, StaticSortedFileMetaData,
},
};
type TestBlockCache =
Cache<(u32, u16), crate::ArcBytes, BlockWeighter, BuildHasherDefault<FxHasher>>;
fn make_cache() -> TestBlockCache {
TestBlockCache::with(
fn make_cache() -> BlockCache {
BlockCache::with(
100,
4 * 1024 * 1024,
Default::default(),
......@@ -1385,8 +1377,8 @@ mod tests {
fn assert_lookup(
sst: &StaticSortedFile,
entry: &TestEntry,
kc: &TestBlockCache,
vc: &TestBlockCache,
kc: &BlockCache,
vc: &BlockCache,
) -> Result<()> {
let result = sst.lookup::<_, false>(entry.hash, &entry.key, kc, vc)?;
match (&entry.value_kind, result) {
......
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