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

Simplify TaskCache buckets and evict collected transient keys

Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 5e71b223
......@@ -1407,12 +1407,10 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
let task_type_hash =
crate::backing_storage::compute_task_type_hash_from_components(native_fn, this, arg);
// A complete in-memory bucket already includes every candidate on disk. In particular,
// direct-by-ID restores during eviction must not repeatedly read the DB or recurse into
// task storage; a partially populated bucket still needs a full restore.
if let Some(bucket) = self.backend.storage.task_cache.get(&task_type_hash)
&& bucket.is_complete()
{
// With persistence enabled, a published bucket includes every on-disk candidate.
// Direct-by-ID restores during eviction must not repeatedly read the DB or recurse into
// task storage when that bucket is already in memory.
if let Some(bucket) = self.backend.storage.task_cache.get(&task_type_hash) {
return bucket.find(native_fn, this, arg);
}
......@@ -1423,8 +1421,8 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
.lookup_task_candidates(native_fn, this, arg)
.expect("Failed to lookup task ids");
// Restore every candidate's full type before locking the TaskCache bucket. This makes the
// in-memory bucket complete even when the matching candidate appears first.
// Restore every candidate's full type before locking the TaskCache bucket, even when
// the matching candidate appears first.
let mut restored_candidates = SmallVec::<[(CachedTaskTypeArc, TaskId); 1]>::new();
let mut matching_candidate = None;
for candidate_id in candidates {
......@@ -1450,7 +1448,6 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
for (stored_type, candidate_id) in restored_candidates {
bucket.insert(stored_type, candidate_id);
}
bucket.mark_complete();
matching_candidate
}
......
......@@ -322,6 +322,37 @@ impl Storage {
});
}
/// Eviction holds a task-storage shard, while creation locks the transient cache first.
/// Try the matching cache shard without blocking and defer the removal on contention.
fn try_evict_transient_task_cache_id(
&self,
task_type: &CachedTaskTypeArc,
task_id: TaskId,
) -> Option<bool> {
let cache = &self.transient_task_cache;
let hash = cache.hasher().hash_one(task_type);
let shard = &cache.shards()[cache.determine_shard(hash as usize)];
let mut shard = shard.try_write()?;
if let Ok(entry) = shard.find_entry(hash, |(key, id)| key == task_type && *id == task_id) {
entry.remove();
Some(true)
} else {
Some(false)
}
}
/// Remove a GC-collected transient task's type mapping after dropping its task-storage lock.
/// The ID check avoids removing a replacement that was created for the same type.
fn evict_transient_task_cache_id(
&self,
task_type: &CachedTaskTypeArc,
task_id: TaskId,
) -> bool {
self.transient_task_cache
.remove_if_mut(task_type, |_, cached_id| *cached_id == task_id)
.is_some()
}
/// Live key eviction removes only singleton buckets; GC-deleted IDs are removed individually.
/// Returns `None` when the cache shard is contended while we hold a task-storage shard.
fn try_evict_task_cache_id(
......@@ -735,6 +766,8 @@ impl Storage {
// Creation locks a task-cache shard before this map shard. Try the sharded cache
// lock without blocking; defer only contended removals to avoid a lock cycle.
let mut deferred_task_cache_removals: Vec<(TaskTypeHash, TaskId, bool)> = Vec::new();
let mut deferred_transient_cache_removals: Vec<(CachedTaskTypeArc, TaskId)> =
Vec::new();
let remove_from_task_cache = |evicted: &mut EvictionCounts,
deferred: &mut Vec<(TaskTypeHash, TaskId, bool)>,
task_id: TaskId,
......@@ -757,7 +790,16 @@ impl Storage {
// All GC'd tasks were tombstoned during the snapshot (or are not persisted) so we
// can drop them fully now.
if task.flags.deleted() {
if !task_id.is_transient() {
if task_id.is_transient() {
if let Some(task_type) = task.get_persistent_task_type() {
match self.try_evict_transient_task_cache_id(task_type, *task_id) {
Some(true) => evicted.key_evictions += 1,
Some(false) => {}
None => deferred_transient_cache_removals
.push((task_type.clone(), *task_id)),
}
}
} else {
let task_type = task
.get_persistent_task_type()
.expect("GC deleted persistent tasks must have a task type");
......@@ -829,6 +871,11 @@ impl Storage {
evicted.key_evictions += 1;
}
}
for (task_type, task_id) in deferred_transient_cache_removals {
if self.evict_transient_task_cache_id(&task_type, task_id) {
evicted.key_evictions += 1;
}
}
evicted
});
......
......@@ -17,12 +17,11 @@ pub type TaskCache = FxDashMap<TaskTypeHash, TaskCacheBucket>;
///
/// Hash collisions are exceptionally rare, so almost every bucket contains exactly one entry.
/// One `(CachedTaskTypeArc, TaskId)` pair fits inline; a second, exceptionally rare collision
/// spills to the heap. Complete buckets permit restore lookups without a persistence read.
/// spills to the heap. When persistence is enabled, buckets are populated after every
/// on-disk candidate for the hash has been read, so lookups need no further persistence read.
#[derive(Clone, Default)]
pub struct TaskCacheBucket {
entries: SmallVec<[(CachedTaskTypeArc, TaskId); 1]>,
/// A by-type restore has read every on-disk candidate for this hash.
complete: bool,
}
impl TaskCacheBucket {
......@@ -62,14 +61,6 @@ impl TaskCacheBucket {
self.entries.is_empty()
}
pub fn is_complete(&self) -> bool {
self.complete
}
pub fn mark_complete(&mut self) {
self.complete = true;
}
pub fn is_singleton_id(&self, task_id: TaskId) -> bool {
self.entries.len() == 1 && self.entries[0].1 == task_id
}
......
......@@ -8,7 +8,7 @@ mod util;
use std::sync::Arc;
use anyhow::Result;
use turbo_tasks::{ResolvedVc, TaskId, Vc, prevent_gc};
use turbo_tasks::{ResolvedVc, TaskId, TransientValue, Vc, prevent_gc};
use crate::{
gc_fixture::{Constant, Selector, create_constant, create_selector},
......@@ -27,6 +27,11 @@ fn leaf(n: u32) -> Vc<u32> {
Vc::cell(n)
}
#[turbo_tasks::function(root)]
fn transient_leaf(n: TransientValue<u32>) -> Vc<u32> {
Vc::cell(*n)
}
/// Resolves `leaf(n)` and returns the raw `TaskId` backing it, as a `u32`.
///
/// This runs inside a tracked task rather than at the top level of `run_once`, so the plain
......@@ -276,6 +281,117 @@ async fn dispose_root_task_releases_anchored_subgraph() {
tt.dispose_root_task(root_id);
}
/// A GC-soft-deleted transient task can be resurrected before eviction; after eviction drops its
/// storage entry, its type mapping must be gone so a fresh task is created for the same type.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn transient_type_resurrects_before_eviction_and_recreates_after() {
let (tt, _persistence_dir) = create_tt("transient_type_gc_lifecycle");
let (tx, rx) = tokio::sync::oneshot::channel();
let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
let root_id = tt.spawn_root_task(move || {
let tx = tx.lock().unwrap().take();
Box::pin(async move {
let vc = transient_leaf(TransientValue::new(88));
let value = *vc.strongly_consistent().await?;
if let Some(tx) = tx {
let _ = tx.send(task_id_of(vc));
}
anyhow::Ok(Vc::<u32>::cell(value))
})
});
let old_id = rx.await.unwrap();
assert!(old_id.is_transient());
tt.dispose_root_task(root_id);
for _ in 0..100 {
if tt.backend().transient_ref_count_for_testing(old_id) == 0 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert_eq!(tt.backend().transient_ref_count_for_testing(old_id), 0);
turbo_tasks::run_once(tt.clone(), async move { anyhow::Ok(()) })
.await
.unwrap();
let mut collected = 0;
for _ in 0..100 {
collected += tt.backend().gc_for_testing(&tt);
if collected >= 2 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert!(collected >= 2, "collected {collected} tasks");
let (tx, rx) = tokio::sync::oneshot::channel();
let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
let root_id = tt.spawn_root_task(move || {
let tx = tx.lock().unwrap().take();
Box::pin(async move {
let vc = transient_leaf(TransientValue::new(88));
let value = *vc.strongly_consistent().await?;
if let Some(tx) = tx {
let _ = tx.send(task_id_of(vc));
}
anyhow::Ok(Vc::<u32>::cell(value))
})
});
let resurrected_id = rx.await.unwrap();
assert_eq!(
resurrected_id, old_id,
"soft-deleted transient task must be resurrected before eviction"
);
tt.dispose_root_task(root_id);
for _ in 0..100 {
if tt.backend().transient_ref_count_for_testing(old_id) == 0 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
turbo_tasks::run_once(tt.clone(), async move { anyhow::Ok(()) })
.await
.unwrap();
// GC soft-deletes the resurrected task. This time run eviction, which must drop both its
// storage entry and the transient cache mapping before the next creation.
let mut collected = 0;
for _ in 0..100 {
collected += tt
.backend()
.snapshot_and_evict_for_testing(&tt)
.gc_stats()
.collected;
if collected >= 2 {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
assert!(
collected >= 2,
"collected {collected} tasks after resurrection"
);
let (tx, rx) = tokio::sync::oneshot::channel();
let tx = Arc::new(std::sync::Mutex::new(Some(tx)));
let root_id = tt.spawn_root_task(move || {
let tx = tx.lock().unwrap().take();
Box::pin(async move {
let vc = transient_leaf(TransientValue::new(88));
let value = *vc.strongly_consistent().await?;
if let Some(tx) = tx {
let _ = tx.send(task_id_of(vc));
}
anyhow::Ok(Vc::<u32>::cell(value))
})
});
let new_id = rx.await.unwrap();
assert!(new_id.is_transient());
assert_ne!(
new_id, old_id,
"evicted transient ID must not survive in the type cache"
);
tt.dispose_root_task(root_id);
tt.stop_and_wait().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unpin_after_stop_does_not_panic() {
let (tt, _persistence_dir) = create_tt("unpin_after_stop_does_not_panic");
......
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