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

Use Papaya for resident task storage

Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 48a01714
......@@ -4741,6 +4741,16 @@ version = "4.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48dd4f4a2c8405440fd0462561f0e5806bd0f77e86f51c761481bdd4018b545e"
[[package]]
name = "papaya"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da2442474a9404698c42509b8967f437249dbc7b50493e83020333d3943ec0ae"
dependencies = [
"equivalent",
"seize",
]
[[package]]
name = "papergrid"
version = "0.7.1"
......@@ -6362,6 +6372,22 @@ dependencies = [
"libc",
]
[[package]]
name = "seize"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b55fb86dfd3a2f5f76ea78310a88f96c4ea21a3031f8d212443d56123fd0521"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]]
name = "self_cell"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58bf37232d3bb9a2c4e641ca2a11d83b5062066f88df7fed36c28772046d65ba"
[[package]]
name = "semver"
version = "1.0.23"
......@@ -9209,6 +9235,7 @@ dependencies = [
"bincode",
"bitfield",
"codspeed-criterion-compat",
"concurrent-queue",
"crossbeam-utils",
"dashmap 7.0.0-rc2",
"fs-err",
......@@ -9218,6 +9245,7 @@ dependencies = [
"indoc",
"jiff",
"lz4_flex",
"papaya",
"parking_lot",
"rand 0.10.1",
"regex",
......
......@@ -313,6 +313,7 @@ nohash-hasher = "0.2.0"
notify = "9.0.0-rc.5"
owo-colors = "4.2.2"
parcel_selectors = "0.28.2"
papaya = "0.2.5"
parking_lot = "0.12.1"
pathdiff = "0.2.1"
phf = { version = "0.11", features = ["macros"] }
......
......@@ -41,6 +41,7 @@ anyhow = { workspace = true }
bincode = { workspace = true }
auto-hash-map = { workspace = true }
bitfield = { workspace = true }
concurrent-queue = { workspace = true }
crossbeam-utils = { workspace = true }
dashmap = { workspace = true, features = ["raw-api"]}
fs-err = { workspace = true }
......@@ -48,6 +49,7 @@ hashbrown = { workspace = true }
indexmap = { workspace = true }
jiff = "0.2.10"
lz4_flex = { workspace = true, optional = true }
papaya = { workspace = true }
parking_lot = { workspace = true }
rand = { workspace = true }
ringmap = { workspace = true, features = ["serde"] }
......
......@@ -5,6 +5,8 @@ use criterion::{Criterion, criterion_group, criterion_main};
pub(crate) mod gc;
pub(crate) mod overhead;
pub(crate) mod papaya_dirty;
pub(crate) mod papaya_map;
pub(crate) mod scope_stress;
pub(crate) mod storage_locking;
pub(crate) mod stress;
......@@ -12,6 +14,6 @@ pub(crate) mod stress;
criterion_group!(
name = turbo_tasks_backend_stress;
config = Criterion::default();
targets = stress::fibonacci, scope_stress::scope_stress, overhead::overhead, gc::gc, storage_locking::storage_locking
targets = stress::fibonacci, scope_stress::scope_stress, overhead::overhead, gc::gc, storage_locking::storage_locking, papaya_dirty::papaya_dirty, papaya_map::papaya_map
);
criterion_main!(turbo_tasks_backend_stress);
use std::{
hint::black_box,
sync::atomic::{AtomicBool, AtomicU64, Ordering},
};
use concurrent_queue::ConcurrentQueue;
use criterion::{BatchSize, BenchmarkId, Criterion, Throughput};
use papaya::HashMap;
use rustc_hash::FxBuildHasher;
const TASKS: u32 = 100_000;
fn map_with_dirty(dirty: u32) -> HashMap<u32, AtomicBool, FxBuildHasher> {
let map = HashMap::with_capacity_and_hasher(TASKS as usize, FxBuildHasher);
let guard = map.guard();
for task_id in 0..TASKS {
map.insert(task_id, AtomicBool::new(task_id < dirty), &guard);
}
drop(guard);
map
}
pub fn papaya_dirty(criterion: &mut Criterion) {
let mut mark = criterion.benchmark_group("papaya_dirty_mark_all");
mark.throughput(Throughput::Elements(TASKS as u64));
mark.bench_function("atomic_count", |b| {
b.iter_batched(
|| AtomicU64::new(0),
|count| {
for _ in 0..TASKS {
black_box(count.fetch_add(1, Ordering::Relaxed));
}
},
BatchSize::LargeInput,
)
});
mark.bench_function("concurrent_queue", |b| {
b.iter_batched(
ConcurrentQueue::unbounded,
|queue| {
for task_id in 0..TASKS {
queue.push(black_box(task_id)).unwrap();
}
},
BatchSize::LargeInput,
)
});
mark.finish();
for dirty in [1, 10, 100, 10_000, TASKS] {
let map = map_with_dirty(dirty);
let ids: Vec<_> = (0..dirty).collect();
let mut process = criterion.benchmark_group("papaya_dirty_process");
process.throughput(Throughput::Elements(dirty as u64));
process.bench_with_input(BenchmarkId::new("full_scan", dirty), &dirty, |b, _| {
b.iter(|| {
let guard = map.guard();
let count = map
.iter(&guard)
.filter(|(_, dirty)| dirty.load(Ordering::Relaxed))
.count();
black_box(count)
})
});
process.bench_with_input(BenchmarkId::new("queued_ids", dirty), &dirty, |b, _| {
b.iter(|| {
let guard = map.guard();
let count = ids
.iter()
.filter(|task_id| {
map.get(*task_id, &guard)
.is_some_and(|dirty| dirty.load(Ordering::Relaxed))
})
.count();
black_box(count)
})
});
process.finish();
}
}
use std::{hint::black_box, thread};
use criterion::{BatchSize, Criterion, Throughput};
use crossbeam_utils::CachePadded;
use dashmap::DashMap;
use papaya::HashMap;
use parking_lot::Mutex;
use rustc_hash::FxBuildHasher;
const TASKS: u32 = 4096;
const OPS: usize = 1000;
type Payload = CachePadded<Mutex<u64>>;
type Dash = DashMap<u32, Box<Payload>, FxBuildHasher>;
type Papaya = HashMap<u32, Payload, FxBuildHasher>;
fn dash() -> Dash {
let map = DashMap::with_capacity_and_hasher_and_shard_amount(TASKS as usize, FxBuildHasher, 64);
for id in 1..=TASKS {
map.insert(id, Box::new(CachePadded::new(Mutex::new(id as u64))));
}
map
}
fn papaya() -> Papaya {
let map = HashMap::with_capacity_and_hasher(TASKS as usize, FxBuildHasher);
let guard = map.guard();
for id in 1..=TASKS {
map.insert(id, CachePadded::new(Mutex::new(id as u64)), &guard);
}
drop(guard);
map
}
pub fn papaya_map(criterion: &mut Criterion) {
let before = turbo_tasks_malloc::TurboMalloc::allocation_counters();
let dash = dash();
let after_dash = turbo_tasks_malloc::TurboMalloc::allocation_counters();
eprintln!(
"dashmap resident allocation: {} bytes in {} allocations",
(after_dash.allocations - before.allocations)
.saturating_sub(after_dash.deallocations - before.deallocations),
(after_dash.allocation_count - before.allocation_count)
.saturating_sub(after_dash.deallocation_count - before.deallocation_count),
);
let before = after_dash;
let papaya = papaya();
let after_papaya = turbo_tasks_malloc::TurboMalloc::allocation_counters();
eprintln!(
"papaya resident allocation: {} bytes in {} allocations",
(after_papaya.allocations - before.allocations)
.saturating_sub(after_papaya.deallocations - before.deallocations),
(after_papaya.allocation_count - before.allocation_count)
.saturating_sub(after_papaya.deallocation_count - before.deallocation_count),
);
let mut hit = criterion.benchmark_group("papaya_map_hit");
hit.throughput(Throughput::Elements(1));
hit.bench_function("dashmap_read_intrusive", |b| {
b.iter(|| {
let task = dash.get(black_box(&1)).unwrap();
*task.lock() = black_box(1);
})
});
hit.bench_function("papaya_guard_intrusive", |b| {
b.iter(|| {
let guard = papaya.guard();
let task = papaya.get(black_box(&1), &guard).unwrap();
*task.lock() = black_box(1);
})
});
hit.finish();
let mut insert = criterion.benchmark_group("papaya_map_insert_remove");
insert.throughput(Throughput::Elements(1));
insert.bench_function("dashmap", |b| {
let map = DashMap::with_hasher(FxBuildHasher);
let mut key = 1u32;
b.iter(|| {
let current = key;
key = key.wrapping_add(1);
map.entry(current)
.or_insert_with(|| Box::new(CachePadded::new(Mutex::new(0))));
black_box(map.remove(&current));
})
});
insert.bench_function("papaya", |b| {
let map = HashMap::with_hasher(FxBuildHasher);
let mut key = 1u32;
b.iter(|| {
let current = key;
key = key.wrapping_add(1);
let guard = map.guard();
map.get_or_insert_with(current, || CachePadded::new(Mutex::new(0)), &guard);
black_box(map.remove(&current, &guard));
})
});
insert.finish();
let keys = [1, 65, 129, 193];
let mut parallel = criterion.benchmark_group("papaya_map_parallel_independent");
parallel.throughput(Throughput::Elements((keys.len() * OPS) as u64));
parallel.bench_function("dashmap_read_intrusive", |b| {
b.iter(|| {
thread::scope(|scope| {
for &key in &keys {
let map = &dash;
scope.spawn(move || {
for _ in 0..OPS {
let task = map.get(&key).unwrap();
*task.lock() = black_box(key as u64);
}
});
}
});
})
});
parallel.bench_function("papaya_guard_intrusive", |b| {
b.iter(|| {
thread::scope(|scope| {
for &key in &keys {
let map = &papaya;
scope.spawn(move || {
for _ in 0..OPS {
let guard = map.guard();
let task = map.get(&key, &guard).unwrap();
*task.lock() = black_box(key as u64);
}
});
}
});
})
});
parallel.finish();
let mut iteration = criterion.benchmark_group("papaya_map_iteration");
iteration.throughput(Throughput::Elements(TASKS as u64));
iteration.bench_function("dashmap_shards", |b| {
b.iter(|| {
let mut sum = 0u64;
for item in dash.iter() {
sum = sum.wrapping_add(*item.lock());
}
black_box(sum)
})
});
iteration.bench_function("papaya_guard", |b| {
b.iter(|| {
let guard = papaya.guard();
let mut sum = 0u64;
for (_, task) in papaya.iter(&guard) {
sum = sum.wrapping_add(*task.lock());
}
black_box(sum)
})
});
iteration.finish();
let mut snapshots = criterion.benchmark_group("papaya_snapshot_map_roundtrip");
snapshots.throughput(Throughput::Elements(TASKS as u64));
snapshots.bench_function("dashmap", |b| {
b.iter_batched(
|| DashMap::with_hasher(FxBuildHasher),
|map| {
for id in 1..=TASKS {
map.insert(id, id as u64);
}
for id in 1..=TASKS {
black_box(map.remove(&id));
}
},
BatchSize::LargeInput,
)
});
snapshots.bench_function("papaya", |b| {
b.iter_batched(
|| HashMap::with_hasher(FxBuildHasher),
|map| {
let guard = map.guard();
for id in 1..=TASKS {
map.insert(id, id as u64, &guard);
}
for id in 1..=TASKS {
black_box(map.remove(&id, &guard));
}
},
BatchSize::LargeInput,
)
});
snapshots.finish();
}
......@@ -44,13 +44,9 @@ use crate::{
/// How long a GC root may go un-anchored before it is collected.
/// Default to 3 days so that a root that is at least occasionally used can survive a weekend.
///
/// Aging out roots solves the problem of missing `gc_unpin` calls. We can miss them for structural
/// reasons, bugs or just shutdown races (drops from native threads race with turbopack shutdown).
/// So using a TTL to track roots that haven't shown up in new sessions we can solve this leak.
///
/// The TTL counter is serving as a check for both new sessions and time. To be aged out you get
/// one session to start the clock and then eventually the timer expires. This is intentionally
/// course.
/// Aging out roots solves the problem of missing `gc_unpin` calls. We can miss them for structural
/// reasons, bugs or shutdown races (drops from native threads race with turbopack shutdown).
/// The TTL counter checks both new sessions and elapsed time.
pub(crate) const DEFAULT_GC_ROOT_TTL: Duration = Duration::from_secs(3 * 24 * 60 * 60);
/// How long a GC root has gone without being observed live, as stored in the persisted roots map.
......@@ -58,15 +54,13 @@ pub(crate) const DEFAULT_GC_ROOT_TTL: Duration = Duration::from_secs(3 * 24 * 60
pub enum TtlCounter {
/// Observed live (a durable, anchored root) in the most recent session.
MostRecent,
/// System time millis at which a session's **first** GC pass first found this root not live.
/// System time millis at which a session's first GC pass found this root not live.
FirstStale(u64),
}
/// One unit of GC work.
enum GcJob {
/// Scan one shard of the resident map (by index) and enqueue its candidates as
/// [`GcJob::Collect`].
ScanShard(usize),
ScanBatch(Vec<TaskId>),
/// Collect a single task.
Collect(TaskId),
}
......@@ -240,35 +234,36 @@ impl TurboTasksBackend {
None
};
// Batch ID scans to avoid one shared-queue operation for each resident task, while the
// aged-out roots still enter the same collection scope as direct jobs.
const GC_SCAN_BATCH_SIZE: usize = 256;
let task_ids = self.storage.gc_task_ids();
let batches = task_ids
.chunks(GC_SCAN_BATCH_SIZE)
.map(|ids| GcJob::ScanBatch(ids.to_vec()))
.collect::<Vec<_>>();
let (mut stats, mut result): (GcStats, GcPassResult) = scope_unbounded_with(
// Start by scanning all shards and collecting the aged out roots from prior sessions.
(0..self.storage.shard_count())
.map(GcJob::ScanShard)
.chain(aged_out.into_iter().map(GcJob::Collect)),
batches.into_iter().chain(aged_out.into_iter().map(GcJob::Collect)),
Default::default,
|spawner, job, (stats, result): &mut (GcStats, GcPassResult)| {
// Abort the gc loop if we are interrupted
if let Some(budget) = &budget
&& budget.should_stop()
{
return ControlFlow::Break(());
}
let collector = |task_id| spawner.spawn(GcJob::Collect(task_id));
let task_id = match job {
GcJob::ScanShard(index) => {
let collector = |task_id| spawner.spawn(GcJob::Collect(task_id));
self.storage.gc_scan_shard(index, collector);
GcJob::ScanBatch(task_ids) => {
self.storage.gc_scan_batch(&task_ids, collector);
return ControlFlow::Continue(());
}
GcJob::Collect(task_id) => task_id,
};
let collector = |child_id| spawner.spawn(GcJob::Collect(child_id));
// Recheck under the task guard: the resident scan saw an earlier state and
// another thread may have changed graph edges before the collector got here.
let mut ctx = ExecuteContextImpl::new_for_gc(self, turbo_tasks, phase, &collector);
// `All` restores Data so `capture_all_edges` below can read the
// Data-category dependency sets. The recheck itself only needs Meta.
// `All` restores Data so capture_all_edges can read dependency sets.
let mut task = ctx.task(task_id, TaskDataCategory::All);
// Recheck under the guard: the shard scan saw this task without holding it, and a
// racing teardown can add uppers that temporarily remove collectibility. Such a
// task is re-enqueued by a later pass.
if !task.is_gc_collectible() {
return ControlFlow::Continue(());
}
......
......@@ -6,6 +6,7 @@ mod operation;
mod snapshot_coordinator;
mod storage;
pub mod storage_schema;
mod task_map;
// Only the `verify_aggregation_graph` feature still uses atomics here; `stopping` is an
// `RwLock<bool>` so that checking it and acting on it cannot be split (see the field's docs).
......@@ -84,7 +85,6 @@ use crate::{
kv_backing_storage::TurboBackingStorage,
utils::{
dash_map_entry::{get_in_shard, get_shard, with_entry_in_shard},
shard_amount::compute_shard_amount,
stopwatch::Stopwatch,
},
};
......@@ -307,8 +307,6 @@ impl TurboTasksBackend {
}
pub fn new(mut options: BackendOptions, backing_storage: TurboBackingStorage) -> Self {
let resident_shard_amount =
compute_shard_amount(options.num_workers, options.small_preallocation);
if !options.dependency_tracking {
options.active_tracking = false;
}
......@@ -344,7 +342,7 @@ impl TurboTasksBackend {
TaskId::try_from(TRANSIENT_TASK_BIT).unwrap(),
TaskId::MAX,
),
storage: Storage::new(resident_shard_amount, small_preallocation),
storage: Storage::new(small_preallocation),
snapshot_coord: SnapshotCoordinator::new(),
snapshot_in_progress: Mutex::new(()),
stopping: RwLock::new(false),
......
......@@ -2163,7 +2163,7 @@ mod filter_transient_tracking_tests {
#[test]
fn autoset_add_remove_only_tracks_persistent_keys() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let counter = TaskLockCounter::new();
let task_id = persistent_task(1);
......@@ -2214,7 +2214,7 @@ mod filter_transient_tracking_tests {
#[test]
fn autoset_extend_tracks_iff_any_persistent() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let counter = TaskLockCounter::new();
// Extend with only transient children: no meta modification.
......@@ -2243,7 +2243,7 @@ mod filter_transient_tracking_tests {
#[test]
fn countermap_update_count_only_tracks_persistent_keys() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let counter = TaskLockCounter::new();
let task_id = persistent_task(1);
......@@ -2267,7 +2267,7 @@ mod filter_transient_tracking_tests {
#[test]
fn countermap_update_counts_batch_tracks_iff_any_persistent() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let counter = TaskLockCounter::new();
// followers: CounterMap<TaskId>, filter_transient, has update_counts.
......@@ -2294,7 +2294,7 @@ mod filter_transient_tracking_tests {
#[test]
fn direct_option_set_take_tracks_by_value_transience() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let counter = TaskLockCounter::new();
// `output` is a direct Option<OutputValue> meta field with filter_transient.
......@@ -2443,7 +2443,7 @@ mod cell_data_tracking_tests {
// (HashOnly persists via the separate `cell_data_hash` field) — but both
// are still stored in memory. Tracking is monotonic: a later persistable
// write flips the flag even after skipped writes left it clean.
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let counter = TaskLockCounter::new();
let mut g = guard_for(&storage, &counter, persistent_task(1));
......@@ -2467,7 +2467,7 @@ mod cell_data_tracking_tests {
#[test]
fn remove_tracks_only_for_persistable() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let counter = TaskLockCounter::new();
let skip = cell_of::<SkipCheapV>(0);
let persistable = cell_of::<PersistableV>(0);
......@@ -2508,7 +2508,7 @@ mod cell_data_tracking_tests {
// `drop_partial` (which keys on Evictability, not the modified flag), so
// a task that only wrote such a cell is both evictable-clean AND keeps the
// value. This is the core safety property of not tracking Skip writes.
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let counter = TaskLockCounter::new();
let task_id = persistent_task(1);
let cell = cell_of::<SkipNeverV>(0);
......
use std::{
cell::Cell,
fmt::{Display, Formatter},
hash::{BuildHasher, Hash},
marker::PhantomData,
hash::BuildHasher,
ops::{Deref, DerefMut},
sync::{
Arc,
atomic::{AtomicBool, AtomicU64, Ordering},
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
},
};
use crossbeam_utils::CachePadded;
use hashbrown::hash_table;
use concurrent_queue::{ConcurrentQueue, PushError};
use thread_local::ThreadLocal;
use tracing::span::Id;
use turbo_bincode::TurboBincodeBuffer;
use turbo_tasks::{FxDashMap, TaskId, backend::CachedTaskTypeArc, event::Event, parallel};
use crate::{
backend::storage_schema::{
DropPartialOutcome, KeyEvictability, TaskSlot, TaskStorage, UnevictableReason,
ValueEvictability,
backend::{
storage_schema::{
DropPartialOutcome, KeyEvictability, TaskStorage, UnevictableReason, ValueEvictability,
},
task_map::{TaskMap, TaskMapGuard},
},
backing_storage::SnapshotItem,
database::key_value_database::KeySpace,
utils::{
dash_map_drop_contents::drop_contents,
dash_map_entry::{TryLockAndRemove, try_lock_and_remove},
dash_map_multi::{Ref, get_disjoint},
},
utils::dash_map_drop_contents::drop_contents,
};
/// Maximum exact dirty-ID work retained before a snapshot falls back to scanning all residents.
/// Benchmarks show queued lookup wins decisively for small incremental snapshots while a full scan
/// wins once most of a 100k-task map is dirty.
const DIRTY_QUEUE_LIMIT: usize = 16 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TaskDataCategory {
Meta,
......@@ -168,46 +169,30 @@ pub enum TrackOutcome {
pub struct Storage {
snapshot_mode: AtomicBool,
/// Per-shard counts of tasks with modified flags set. Incremented when a task
/// transitions from unmodified to modified (outside snapshot mode). Reset to zero when
/// snapshot mode begins, and re-incremented in `end_snapshot` for tasks that still have
/// modifications (promoted from `modified_during_snapshot`). Used to skip unmodified shards
/// in `take_snapshot`, avoiding unnecessary iteration and enabling early returns
///
/// Indexed by `map.determine_shard(map.hash_usize(&key))` and guaranteed by construction so
/// that `shard_modified_counts.len()==map.shards().len()`
shard_modified_counts: Box<[CachePadded<AtomicU64>]>,
/// Writers that observed snapshot mode and may still be publishing a snapshot marker.
snapshot_writers: AtomicUsize,
/// Number of tasks believed to have modified flags outside snapshot mode. Used to skip the
/// resident-map scan when no persistence work exists. Transitions are serialized by task
/// locks.
modified_count: AtomicU64,
/// Bounded exact worklist for small incremental snapshots. Once full, `dirty_overflow`
/// switches the next snapshot to a full Papaya scan, avoiding per-task queue overhead on
/// cold builds.
dirty_tasks: ConcurrentQueue<TaskId>,
dirty_overflow: AtomicBool,
/// Stores snapshots of task state for tasks accessed during snapshot mode.
/// - `Some(snapshot)`: Task was modified before snapshot mode and accessed again during it.
/// Contains a copy of the pre-snapshot state that needs to be persisted.
/// - `None`: Task was first modified during snapshot mode (not part of current snapshot). Will
/// be marked as modified at the beginning of the next snapshot cycle.
///
/// Lock Ordering: `snapshots` locks are acquired **after** `map` locks (see the comment on
/// `map` below). Holding a `snapshots` shard write lock and then trying to take a `map` shard
/// write lock is forbidden — it would deadlock against `track_modification_internal` /
/// `SnapshotShardIter::next`, which take map first.
///
/// Shard Invariant: `snapshots` is constructed with the same `shard_amount`, the same key
/// type (`TaskId`), and the same stateless hasher (`FxBuildHasher`) as `map`. Therefore shard
/// index `N` in `snapshots` corresponds exactly to shard index `N` in `map`: any `TaskId`
/// present in `snapshots.shards()[N]` (if present in `map` at all) is in `map.shards()[N]`.
/// Code that walks both maps in parallel (e.g. `end_snapshot`) relies on this to lock pairs
/// of shards by index instead of going through the top-level `DashMap` accessors.
/// Task mutation acquires the task lock before a snapshots shard lock. `end_snapshot` drains
/// snapshots shards completely before resolving and locking resident tasks, so it never holds
/// those locks in the reverse order.
snapshots: FxDashMap<TaskId, Option<Box<TaskStorage>>>,
/// The main storage map
///
/// Lock Ordering: Task creation acquires a `task_cache` lock and then inserts into this map.
/// Because both datastructures are sharded on different keys, the locks are not 'strictly'
/// ordered but we should treat them as such
/// Acquiring locks in the opposite order should be defensive
///
/// Lock Ordering vs. `snapshots`: `map` locks are acquired **before** `snapshots` locks.
/// `track_modification_internal` holds a map shard read guard plus the task's intrusive lock,
/// while `SnapshotShardIter::next` holds the map shard write lock; both then take a
/// `snapshots` shard lock. `end_snapshot` must lock in the same order — see the shard-zipping
/// pattern there.
map: FxDashMap<TaskId, Box<TaskSlot>>,
/// The main resident-task map. Papaya guards provide entry lifetime; each TaskSlot's intrusive
/// lock provides payload exclusion. Papaya pins do not participate in lock ordering.
map: TaskMap,
/// A shared event notified whenever any task finishes restoring (successfully or not).
///
/// Threads waiting for another thread's in-progress restore subscribe to this event,
......@@ -216,57 +201,40 @@ pub struct Storage {
/// Maps `CachedTaskType` → `TaskId` for deduplication of persistent task creation.
/// This is backed by the TaskCache table in the database.
///
/// LockOrdering: See the comments on [map].
/// Persistent task creation may hold a task_cache shard lock while acquiring a resident task.
/// Eviction therefore releases its task lock before removing the inverse cache entry.
pub task_cache: FxDashMap<CachedTaskTypeArc, TaskId>,
}
impl Storage {
pub fn new(shard_amount: usize, small_preallocation: bool) -> Self {
pub fn new(small_preallocation: bool) -> Self {
let map_capacity: usize = if small_preallocation {
1024
} else {
1024 * 1024
};
let map = FxDashMap::with_capacity_and_hasher_and_shard_amount(
map_capacity,
Default::default(),
shard_amount,
);
let shard_modified_counts = (0..shard_amount)
.map(|_| CachePadded::new(AtomicU64::new(0)))
.collect::<Vec<_>>()
.into_boxed_slice();
let map = TaskMap::new(map_capacity);
Self {
snapshot_mode: AtomicBool::new(false),
shard_modified_counts,
snapshots: FxDashMap::with_capacity_and_hasher_and_shard_amount(
// We expect very few updates to this map since it will only happen when updates
// race with snapshots. This never happens in a build and only rarely happens in
// dev sessions
0,
Default::default(),
shard_amount,
),
snapshot_writers: AtomicUsize::new(0),
modified_count: AtomicU64::new(0),
dirty_tasks: ConcurrentQueue::bounded(DIRTY_QUEUE_LIMIT),
dirty_overflow: AtomicBool::new(false),
snapshots: FxDashMap::default(),
map,
restored: Event::new(|| || "Storage::restored".to_string()),
task_cache: FxDashMap::default(),
}
}
/// Returns the shard index for the given key in the `map` DashMap.
fn shard_index(&self, key: &TaskId) -> usize {
let hash = self.map.hash_usize(key);
self.map.determine_shard(hash)
}
/// Promote `modified_during_snapshot` → `modified` flags on a task, and increment the
/// per-shard modified count if the task was not already marked as modified.
///
/// This is used after persisting a snapshot: _during_snapshot flags represent changes
/// that occurred concurrently and were not included in the persisted snapshot, so they
/// must be carried forward as `modified` for the next snapshot cycle.
fn promote_during_snapshot_flags(&self, task: &mut TaskStorage, shard_idx: usize) {
fn promote_during_snapshot_flags(&self, task_id: TaskId, task: &mut TaskStorage) {
let already_modified = task.flags.any_modified();
let mut promoted = false;
if task.flags.meta_modified_during_snapshot() {
......@@ -280,10 +248,28 @@ impl Storage {
promoted = true;
}
if !already_modified && promoted {
self.shard_modified_counts[shard_idx].fetch_add(1, Ordering::Relaxed);
self.mark_dirty(task_id);
}
}
/// Publish one task's transition from clean to modified into the hybrid snapshot worklist.
fn mark_dirty(&self, task_id: TaskId) {
self.modified_count.fetch_add(1, Ordering::Relaxed);
if let Err(PushError::Full(_)) = self.dirty_tasks.push(task_id) {
self.dirty_overflow.store(true, Ordering::Relaxed);
}
}
fn unmark_dirty(&self) {
// A snapshot may already have claimed and reset the global count. Saturating at zero keeps
// an undo/discard that crosses that claim from wrapping the hint to u64::MAX.
let _ = self
.modified_count
.try_update(Ordering::Relaxed, Ordering::Relaxed, |count| {
count.checked_sub(1)
});
}
/// Mark a newly allocated task as restored (skip DB queries) and new (include in persistence
/// snapshots). Optionally sets the `persistent_task_type` eagerly so it's available for
/// persistence snapshots without needing to propagate it through `connect_child`.
......@@ -306,20 +292,17 @@ impl Storage {
/// the results. Ends snapshot mode when the returned `SnapshotGuard` (held by each shard) is
/// dropped.
///
/// `process` is called while holding a read lock on the task storage, so it can access
/// the TaskStorage directly without cloning.
/// `process` is called while holding the task's intrusive lock, so it can access TaskStorage
/// directly without cloning.
///
/// Both callbacks receive a mutable scratch buffer that can be reused across iterations
/// to avoid repeated allocations.
/// The process callback receives a mutable scratch buffer reused across iterations.
///
/// The returned shards implement `IntoIterator`. Empty shards (no modified or snapshot
/// entries) are filtered out, but shards may still yield no items if all entries produce
/// empty `SnapshotItem`s (this is rare and only happens under error conditions).
/// The returned batches implement `IntoIterator`. The input scan seeds cache-friendly ID
/// batches into `scope_unbounded_with`; each worker independently pins, locks, and revalidates
/// tasks within its batch.
///
/// When `drain_entries` is true (shutdown only), the scan drains the map: unmodified entries
/// are erased and freed immediately, and the modified entries are moved out into the
/// returned shard iterators, which free each task's memory as it is serialized rather than
/// after the whole batch is written.
/// When `drain_entries` is true (shutdown only), unmodified tasks are removed during the scan;
/// modified tasks are removed after their snapshot item is serialized.
pub fn take_snapshot<
'l,
P: for<'a> Fn(TaskId, &'a TaskStorage, &mut TurboBincodeBuffer) -> SnapshotItem + Sync,
......@@ -330,115 +313,93 @@ impl Storage {
drain_entries: bool,
) -> Vec<SnapshotShard<'l, P>> {
let guard = Arc::new(guard);
let modified_count = self.modified_count.swap(0, Ordering::Relaxed);
if modified_count == 0 && !drain_entries {
return Vec::new();
}
let shards: Vec<_> = self.map.shards().iter().enumerate().collect();
// The number of shards is much larger than the number of threads, so the effect of the
// locks held is negligible.
parallel::map_collect::<_, _, Vec<_>>(&shards, |&(shard_idx, shard)| {
// Check how many modifications there are in this shard, because we have entered
// snapshot_mode, there are no racing writes
// So we can safely clear it out now that we are processing the modifications
let modified_count = self.shard_modified_counts[shard_idx].swap(0, Ordering::Relaxed);
if modified_count == 0 && !drain_entries {
// Nothing to persist in this shard and we're keeping the map, so skip the scan.
// TODO: when not draining but eviction is enabled we should run that logic here as
// well
return None;
}
// Scan the shard once, building the work this shard's iterator will perform. The two
// modes carry different data so that `next` has no per-item `drain` branch:
// - keep mode collects the modified `TaskId`s and looks them up again while iterating.
// - drain mode erases the unmodified entries here and then moves the remaining
// (modified-only) table out of the map, so the iterator owns and drains it directly.
let work = if drain_entries {
let mut shard_guard = shard.write();
shard_guard.retain(|(key, task)| {
let task = task.get_mut_exclusive();
let modified_task = task.flags.any_modified();
if modified_task {
debug_assert!(
!key.is_transient(),
"found a modified transient task: {key:?}"
);
}
// Unmodified entries are not part of the snapshot. Remove and free them now so
// the table we move out below holds only modified entries.
modified_task
});
if shard_guard.is_empty() {
// The shard held only unmodified entries, which we've now erased and freed.
// No iterator is created for an empty shard.
return None;
}
// Move the modified-only table out of the map. Iterating it frees each task box as
// it is serialized, and the shard's table allocation is released here.
ShardWork::Drain(std::mem::take(&mut *shard_guard).into_iter())
} else {
let shard_guard = shard.read();
let mut modified = Vec::with_capacity(modified_count as usize);
for (key, task) in shard_guard.iter() {
// Only check modified flags — transient tasks never have modified flags set
// (track_modification guards against it), so this naturally excludes them.
// new_task always comes with modified flags (set_persistent_task_type calls
// track_modification), so any_modified() is sufficient.
if task.with_lock(|task| task.flags.any_modified()) {
debug_assert!(
!key.is_transient(),
"found a modified transient task: {key:?}"
);
modified.push(*key);
let overflow = self.dirty_overflow.swap(false, Ordering::Relaxed);
let mut queued = Vec::with_capacity(modified_count.min(DIRTY_QUEUE_LIMIT as u64) as usize);
while let Ok(task_id) = self.dirty_tasks.pop() {
queued.push(task_id);
}
let task_ids = if drain_entries || overflow {
self.map.task_ids()
} else {
queued
};
const SNAPSHOT_SCAN_BATCH_SIZE: usize = 256;
let scan_batches = task_ids
.chunks(SNAPSHOT_SCAN_BATCH_SIZE)
.map(<[TaskId]>::to_vec)
.collect::<Vec<_>>();
let mut modified = turbo_tasks::scope_unbounded::scope_unbounded_with(
scan_batches,
Vec::new,
|_, task_ids, modified| {
for task_id in task_ids {
if let Some(task) = self.map.get(task_id) {
if task.flags.any_modified() {
debug_assert!(
!task_id.is_transient(),
"found a modified transient task: {task_id:?}"
);
modified.push(task_id);
} else if drain_entries {
self.map.remove_locked(&task);
}
}
}
// modified_count > 0 (we returned early otherwise), so this is never empty.
debug_assert!(!modified.is_empty());
ShardWork::Keep(modified)
};
std::ops::ControlFlow::Continue(())
},
|mut left, mut right| {
left.append(&mut right);
left
},
);
Some(SnapshotShard {
shard_idx,
work,
// The bounded queue intentionally tolerates stale entries after undo/re-modify cycles.
// Multiple queued copies can all appear modified during this scan, so collapse them before
// creating iterators to preserve one persistence record per task.
modified.sort_unstable();
modified.dedup();
const SNAPSHOT_BATCH_SIZE: usize = 1024;
modified
.chunks(SNAPSHOT_BATCH_SIZE)
.map(|task_ids| SnapshotShard {
work: if drain_entries {
ShardWork::Drain(task_ids.to_vec())
} else {
ShardWork::Keep(task_ids.to_vec())
},
storage: self,
process,
_guard: guard.clone(),
})
})
.into_iter()
.flatten()
.collect()
.collect()
}
/// Enter snapshot mode and return a guard that will call `end_snapshot` on drop.
///
/// Returns whether any shard has modifications. Per-shard counts are reset
/// in `take_snapshot` as each shard is processed, not here — resetting eagerly
/// would lose track of modifications for shards that haven't been persisted yet.
/// Returns whether any task is believed to have modifications. The count is reset only when
/// `take_snapshot` begins its protected scan.
///
/// Safety invariant: `start_snapshot` and `end_snapshot` are always called
/// sequentially within a single `snapshot_and_persist` invocation (the sole
/// caller). There is no concurrent snapshot lifecycle, so they cannot race.
pub fn start_snapshot(&self) -> (SnapshotGuard<'_>, bool) {
// Enter snapshot mode first so concurrent track_modification calls switch
// to the _during_snapshot path and stop incrementing shard_modified_counts.
self.snapshot_mode.store(true, Ordering::Release);
// Check if any shard has modifications. Don't reset counts here —
// take_snapshot resets per-shard counts as it processes each shard,
// which avoids losing track of modifications for shards that haven't
// been persisted yet.
let has_modifications = self
.shard_modified_counts
.iter()
.any(|c| c.load(Ordering::Relaxed) > 0);
// Enter snapshot mode first so concurrent modifications switch to the during-snapshot
// path and stop incrementing the pre-snapshot count.
self.snapshot_mode.store(true, Ordering::SeqCst);
let has_modifications = self.modified_count.load(Ordering::Relaxed) > 0;
(SnapshotGuard::new(self), has_modifications)
}
/// End snapshot mode.
///
/// Modified/new flags on tasks are cleared incrementally during snapshot iteration
/// (in `take_snapshot` for direct_snapshots, and in `SnapshotShardIter::next` for
/// modified tasks), so no full-map scan is needed here.
/// Modified/new flags are cleared incrementally in `SnapshotShardIter::next`, so no full-map
/// scan is needed here.
///
/// This method only needs to:
/// 1. Leave snapshot mode so new modifications go to the modified flags directly.
......@@ -447,102 +408,76 @@ impl Storage {
fn end_snapshot(&self) {
// Leave snapshot mode first. After this, concurrent track_modification calls
// will set modified flags directly instead of going through the snapshots map.
self.snapshot_mode.store(false, Ordering::Release);
// Promote modified_during_snapshot → modified for tasks that had snapshots.
// The snapshots map should be small (only tasks concurrently accessed during snapshot
// mode). Increment the per-shard modified counts for promoted tasks.
// Lock Ordering: we must acquire `map` shards BEFORE `snapshots` shards, matching the
// order used by `track_modification_internal` and `SnapshotShardIter::next`. The
// previous implementation drained `snapshots` first and then called `self.map.get_mut`,
// which is the opposite order — a concurrent `track_modification` (holding map[N], about
// to insert into snapshots[N]) could deadlock against it through the
// `snapshot_mode = false` race window.
//
// Shard pairing: `map` and `snapshots` are constructed with the same `shard_amount`,
// same `TaskId` keys, and the same stateless `FxBuildHasher`. Therefore shard `N` in
// `snapshots` pairs with shard `N` in `map`: every key drained from `snapshots[N]` (if
// it still exists in `map`) lives in `map[N]`. We zip them and lock each pair in order.
let map_shards = self.map.shards();
let snapshot_shards = self.snapshots.shards();
debug_assert_eq!(
map_shards.len(),
snapshot_shards.len(),
"map and snapshots must share shard count for zipped locking; see Shard Invariant on \
`snapshots` field"
);
let shard_indices: Vec<usize> = (0..map_shards.len()).collect();
parallel::for_each(&shard_indices, |&shard_idx| {
let map_shard = &map_shards[shard_idx];
let snap_shard = &snapshot_shards[shard_idx];
// Acquire in documented order: map first, snapshots second.
let mut map_guard = map_shard.write();
let mut snap_guard = snap_shard.write();
for (key, _) in snap_guard.drain() {
// The key is in this shard's `map` (or absent entirely), by the shard
// invariant above. Resolve directly in the held map guard rather than going
// through `self.map.get_mut`, which would attempt to re-acquire this shard's
// write lock and would also obscure the pairing.
let hash = self.map.hasher().hash_one(key);
if let Some((_, task)) = map_guard.find_mut(hash, |(k, _)| *k == key) {
self.promote_during_snapshot_flags(task.get_mut_exclusive(), shard_idx);
}
}
// If we are saving a non-trivial amount of memory just clear it out.
if snap_guard.capacity() > 1024 {
snap_guard.shrink_to(0, |_entry| {
unreachable!("nothing is hashed when resizing an empty shard to zero");
});
self.snapshot_mode.store(false, Ordering::SeqCst);
let mut spins = 0;
while self.snapshot_writers.load(Ordering::SeqCst) != 0 {
if spins < 64 {
std::hint::spin_loop();
spins += 1;
} else {
std::thread::yield_now();
spins = 0;
}
}
// First collect and detach snapshots without holding any task locks. All DashMap guards
// are dropped before resident tasks are resolved, so no reverse lock cycle is possible.
let keys: Vec<TaskId> = self.snapshots.iter().map(|entry| *entry.key()).collect();
self.snapshots.clear();
drop(snap_guard);
drop(map_guard);
parallel::for_each(&keys, |&key| {
if let Some(mut task) = self.access_existing_mut(key) {
self.promote_during_snapshot_flags(key, &mut task);
}
});
}
/// Returns true if actively snapshotting (modifications should go to snapshots map).
/// Returns false if inactive (modifications go to modified list).
fn snapshot_mode(&self) -> bool {
self.snapshot_mode.load(Ordering::Acquire)
self.snapshot_mode.load(Ordering::SeqCst)
}
fn try_begin_snapshot_write(&self) -> Option<SnapshotWriterGuard<'_>> {
self.snapshot_writers.fetch_add(1, Ordering::SeqCst);
if self.snapshot_mode() {
Some(SnapshotWriterGuard {
writers: &self.snapshot_writers,
})
} else {
self.snapshot_writers.fetch_sub(1, Ordering::SeqCst);
None
}
}
pub fn access_mut(&self, key: TaskId) -> StorageWriteGuard<'_> {
self.access_existing_mut(key).unwrap_or_else(|| {
let inner = match self.map.entry(key) {
dashmap::mapref::entry::Entry::Occupied(entry) => entry.into_ref(),
dashmap::mapref::entry::Entry::Vacant(entry) => {
entry.insert(Box::new(TaskSlot::new()))
}
};
StorageWriteGuard::new(self, inner.downgrade().into())
StorageWriteGuard {
storage: self,
inner: self.map.get_or_insert(key),
}
}
pub(crate) fn access_existing_mut(&self, key: TaskId) -> Option<StorageWriteGuard<'_>> {
Some(StorageWriteGuard {
storage: self,
inner: self.map.get(key)?,
})
}
/// Like [`Self::access_mut`], but keeps the map entry so the caller can still remove it.
/// Retains a locked task with the ability to detach its exact Papaya entry.
pub fn access_entry_mut(&self, key: TaskId) -> TaskEntryGuard<'_> {
let entry = match self.map.entry(key) {
dashmap::mapref::entry::Entry::Occupied(e) => e,
dashmap::mapref::entry::Entry::Vacant(e) => e.insert_entry(Box::new(TaskSlot::new())),
};
TaskEntryGuard {
storage: self,
entry,
inner: self.access_mut(key),
}
}
fn access_existing_mut(&self, key: TaskId) -> Option<StorageWriteGuard<'_>> {
Some(StorageWriteGuard::new(self, self.map.get(&key)?.into()))
}
/// Read-only access to an already resident task. Returns `None` if the task isn't memory
/// resident. The closure runs while the task lock and shard read lock are held, so it must be
/// resident. The closure runs while the task lock and Papaya protection are held, so it must be
/// cheap and must not re-enter this task or the map.
pub fn with_task<R>(&self, key: TaskId, f: impl FnOnce(&TaskStorage) -> R) -> Option<R> {
let task = StorageWriteGuard::new(self, self.map.get(&key)?.into());
let task = self.access_existing_mut(key)?;
Some(f(&task))
}
......@@ -552,39 +487,41 @@ impl Storage {
self.map.len()
}
/// The number of shards in the resident map. GC seeds one `ScanShard` job per index; the slice
/// returned by `map.shards()` is fixed for the map's lifetime, so an index is a stable handle
/// to one shard.
pub fn shard_count(&self) -> usize {
self.map.shards().len()
#[doc(hidden)]
pub fn resident_persistent_task_count_for_testing(&self) -> usize {
self.map
.task_ids()
.into_iter()
.filter(|task_id| !task_id.is_transient())
.count()
}
}
/// Snapshot the IDs used to seed GC's unbounded work scope. Workers independently pin, lock,
/// and revalidate each task before applying the cheap collectibility filter.
pub fn gc_task_ids(&self) -> Vec<TaskId> {
self.map.task_ids()
}
/// Scans a **single** shard by index, invoking `on_candidate` for each resident task whose
/// storage passes [`TaskStorage::gc_collectible`].
pub fn gc_scan_shard(&self, index: usize, mut on_candidate: impl FnMut(TaskId)) {
let shard = self.map.shards()[index].read();
for (task_id, task) in shard.iter() {
if task.with_lock(TaskStorage::gc_collectible) {
on_candidate(*task_id);
/// Scan a batch of resident task IDs under one Papaya protection guard.
pub fn gc_scan_batch(&self, task_ids: &[TaskId], mut on_candidate: impl FnMut(TaskId)) {
self.map.for_each_locked(task_ids, |task_id, task| {
if task.gc_collectible() {
on_candidate(task_id);
}
}
});
}
/// Return the set of all known live roots.
pub fn gc_scan_roots(&self) -> impl Iterator<Item = TaskId> {
let per_shard: Vec<Vec<TaskId>> =
parallel::map_collect(&(0..self.shard_count()).collect::<Vec<_>>(), |&index| {
let mut roots = Vec::new();
let shard = self.map.shards()[index].read();
for (task_id, task) in shard.iter() {
if !task_id.is_transient() && task.with_lock(TaskStorage::gc_is_root) {
roots.push(*task_id);
}
}
roots
});
per_shard.into_iter().flatten()
let task_ids = self.gc_task_ids();
let mut roots = Vec::new();
self.map.for_each_locked(&task_ids, |task_id, task| {
if task.gc_is_root() {
roots.push(task_id);
}
});
roots.into_iter()
}
pub fn access_pair_mut(
......@@ -593,31 +530,19 @@ impl Storage {
key2: TaskId,
) -> (StorageWriteGuard<'_>, StorageWriteGuard<'_>) {
assert_ne!(key1, key2, "cannot mutably access the same task twice");
let (lower_key, upper_key, reverse) = if key1 < key2 {
(key1, key2, false)
} else {
(key2, key1, true)
};
// `get_disjoint` obtains all shard guards in shard-index order (sharing one guard for a
// same-shard pair) before task locks are taken here in TaskId order.
let (lower, upper) =
get_disjoint(
&self.map,
lower_key,
upper_key,
|| Box::new(TaskSlot::new()),
);
let lower = StorageWriteGuard::new(self, lower);
let upper = StorageWriteGuard::new(self, upper);
if reverse {
(upper, lower)
if key1 < key2 {
let first = self.access_mut(key1);
let second = self.access_mut(key2);
(first, second)
} else {
(lower, upper)
let second = self.access_mut(key2);
let first = self.access_mut(key1);
(first, second)
}
}
pub fn drop_contents(&self) {
drop_contents(&self.map);
self.map.clear();
drop_contents(&self.snapshots);
}
......@@ -651,130 +576,81 @@ impl Storage {
"evict_after_snapshot must not be called during snapshot mode"
);
let counts: Vec<EvictionCounts> = parallel::map_collect(self.map.shards(), |shard| {
let mut shard = shard.write();
let mut evicted = EvictionCounts::default();
// task_cache removals that we couldn't perform inline because the target shard
// was contended. We defer them until after the map shard lock is released to
// avoid a lock cycle with get_or_create_persistent_task, which takes task_cache
// before map. Allocated lazily on first conflict.
let mut deferred_task_cache_removals: Vec<CachedTaskTypeArc> = Vec::new();
// Remove a task type from `task_cache`, deferring on contention. Shared by the
// GC-deleted path below and the ordinary key eviction.
let remove_from_task_cache =
|evicted: &mut EvictionCounts,
deferred: &mut Vec<CachedTaskTypeArc>,
task_type: &CachedTaskTypeArc| {
match try_lock_and_remove(&self.task_cache, task_type.as_ref()) {
TryLockAndRemove::Removed => {
evicted.key_evictions += 1;
}
TryLockAndRemove::NotFound => {
// Generally this should be rare, it more or less implies something
// else is concurrently holding the Arc
}
TryLockAndRemove::WouldBlock => {
// Contention, to avoid a deadlock just defer
deferred.push(task_type.clone());
}
}
let totals = turbo_tasks::scope_unbounded::scope_unbounded_with(
self.map.task_ids(),
EvictionCounts::default,
|_, task_id, evicted| {
let Some(mut task) = self.access_existing_mut(task_id) else {
return std::ops::ControlFlow::Continue(());
};
shard.retain(|(task_id, task)| {
let task = task.get_mut_exclusive();
// Transient tasks cannot be evicted unless the GC has deleted them.
// Transient tasks are retained unless GC has deleted them.
if task_id.is_transient() && !task.flags.deleted() {
evicted.unevictable_reasons[UnevictableReason::Transient.index()] += 1;
return true;
return std::ops::ControlFlow::Continue(());
}
// All GC'd tasks were tombstoned during the snapshot (or are not persisted) so we
// can drop them fully now.
// All GC'd tasks were tombstoned during the snapshot (or are not persisted), so
// they can be removed. A transient deleted task has no persistent task type.
let mut remove_task = false;
let mut task_type_to_remove = None;
if task.flags.deleted() {
if let Some(task_type) = task.get_persistent_task_type() {
remove_from_task_cache(
&mut evicted,
&mut deferred_task_cache_removals,
task_type,
);
}
task_type_to_remove = task.get_persistent_task_type().cloned();
evicted.full += 1;
return false;
}
let (key_evictability, value_evictability) = task.evictability();
match key_evictability {
KeyEvictability::Evictable => {
// The task type is persisted to backing storage (new_task = false),
// so task_cache is a pure perf cache. Remove it now; it will be
// re-populated by task_by_type() on the next cache miss.
let task_type = task.get_persistent_task_type().unwrap();
// Only try to acquire the lock, if we cannot just remove at the end
// Because `get_or_create_task` acquires 'task_cache' then `storage.map` and
// we do the opposite we need to be defensive here. Attempting here is just
// an optimization to avoid pushing into `deferred_task_cache_removals`
remove_from_task_cache(
&mut evicted,
&mut deferred_task_cache_removals,
task_type,
);
remove_task = true;
} else {
let (key_evictability, value_evictability) = task.evictability();
if key_evictability == KeyEvictability::Evictable {
task_type_to_remove =
Some(task.get_persistent_task_type().unwrap().clone());
}
KeyEvictability::AlreadyEvicted | KeyEvictability::Unevictable => {}
}
match value_evictability {
ValueEvictability::Evictable { meta, data } => {
match task.drop_partial(data, meta) {
DropPartialOutcome::Empty => {
evicted.full += 1;
return false;
}
DropPartialOutcome::HasResidue => {
if data && meta {
evicted.data_and_meta += 1;
} else if data {
evicted.data_only += 1;
} else {
debug_assert!(meta);
evicted.meta_only += 1;
match value_evictability {
ValueEvictability::Evictable { meta, data } => {
match task.drop_partial(data, meta) {
DropPartialOutcome::Empty => {
evicted.full += 1;
remove_task = true;
}
DropPartialOutcome::HasResidue => {
if data && meta {
evicted.data_and_meta += 1;
} else if data {
evicted.data_only += 1;
} else {
debug_assert!(meta);
evicted.meta_only += 1;
}
}
}
}
}
ValueEvictability::Unevictable(reason) => {
evicted.unevictable_reasons[reason.index()] += 1;
ValueEvictability::Unevictable(reason) => {
evicted.unevictable_reasons[reason.index()] += 1;
}
}
}
true
});
// Shrink the shard if it's less than half full, to reclaim slack capacity
// after bulk evictions. We already hold the write lock, so this is free
// from a locking perspective. TaskId hashing is cheap (it's just an integer).
let len = shard.len();
if shard.capacity() > len * 2 {
shard.shrink_to(len, |(k, _v)| self.map.hasher().hash_one(k));
}
// Release the map shard lock before draining deferred removals so that a thread
// holding a task_cache shard lock and waiting on this map shard can make progress.
drop(shard);
for task_type in deferred_task_cache_removals {
if self.task_cache.remove(task_type.as_ref()).is_some() {
if remove_task {
self.map.remove_locked(&task.inner);
}
// Persistent task creation takes task_cache before acquiring a task lock. Release
// the task lock before removing the inverse cache entry to preserve that order.
drop(task);
if let Some(task_type) = task_type_to_remove
&& self.task_cache.remove(task_type.as_ref()).is_some()
{
evicted.key_evictions += 1;
}
}
evicted
});
let mut totals = EvictionCounts::default();
for evicted in counts {
totals += evicted;
}
// Shrink task_cache only when we evicted more entries than remain — i.e. the map
// is less than half full. Rehashing each surviving CachedTaskType isn't free, so
// we gate it on meaningful slack. Within that, walk shards in parallel and shrink
// each one independently if it is itself less than half full.
std::ops::ControlFlow::Continue(())
},
|mut left, right| {
left += right;
left
},
);
// Reclaim task_cache table slack after broad key eviction.
if totals.key_evictions > self.task_cache.len() {
parallel::for_each(self.task_cache.shards(), |shard| {
let mut shard = shard.write();
let len = shard.len();
if shard.capacity() > len * 2 {
shard.shrink_to(len, |(k, _v)| self.task_cache.hasher().hash_one(k));
shard.shrink_to(len, |(key, _)| self.task_cache.hasher().hash_one(key));
}
});
}
......@@ -784,65 +660,49 @@ impl Storage {
}
}
/// A write guard that still owns its map entry, so the task can be removed under the lock that is
/// already held.
///
/// Use [`Storage::access_entry_mut`] to obtain one. Convert it with [`Self::into_write_guard`] once
/// removal is no longer a possibility, or call [`Self::discard`] to drop the entry outright.
/// A locked resident task that may be detached before returning its ordinary write guard.
/// Papaya protection keeps the old node allocated until this guard drops after removal.
pub struct TaskEntryGuard<'a> {
storage: &'a Storage,
entry: dashmap::mapref::entry::OccupiedEntry<'a, TaskId, Box<TaskSlot>>,
inner: StorageWriteGuard<'a>,
}
impl<'a> TaskEntryGuard<'a> {
/// Removes this task's entry.
pub fn discard(self) {
self.entry.remove();
self.storage.map.remove_locked(&self.inner.inner);
}
/// Gives up the ability to remove the entry, yielding an ordinary write guard.
pub fn into_write_guard(self) -> StorageWriteGuard<'a> {
StorageWriteGuard::new(self.storage, self.entry.into_ref().downgrade().into())
self.inner
}
}
impl Deref for TaskEntryGuard<'_> {
type Target = TaskStorage;
fn deref(&self) -> &Self::Target {
// SAFETY: the entry guard holds the shard write lock, so no other task guard can access
// this slot while it is borrowed here.
unsafe { self.entry.get().get() }
&self.inner
}
}
impl DerefMut for TaskEntryGuard<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.entry.get_mut().get_mut_exclusive()
&mut self.inner
}
}
pub struct StorageWriteGuard<'a> {
storage: &'a Storage,
inner: Ref<'a, TaskId, Box<TaskSlot>>,
// Match parking_lot's default guard behavior: task guards must not cross `.await`.
_not_send: PhantomData<*const ()>,
struct SnapshotWriterGuard<'a> {
writers: &'a AtomicUsize,
}
impl<'a> StorageWriteGuard<'a> {
fn new(storage: &'a Storage, inner: Ref<'a, TaskId, Box<TaskSlot>>) -> Self {
// The map guard keeps the opaque slot alive while its raw lock is acquired.
inner.value().lock();
Self {
storage,
inner,
_not_send: PhantomData,
}
impl Drop for SnapshotWriterGuard<'_> {
fn drop(&mut self) {
self.writers.fetch_sub(1, Ordering::SeqCst);
}
}
fn task(&self) -> &TaskStorage {
// SAFETY: `new` acquired this slot's lock, and `inner` keeps it alive.
unsafe { self.inner.value().get() }
}
pub struct StorageWriteGuard<'a> {
storage: &'a Storage,
inner: TaskMapGuard<'a>,
}
impl StorageWriteGuard<'_> {
......@@ -885,59 +745,44 @@ impl StorageWriteGuard<'_> {
let modified = flags.is_modified(category);
#[cfg(feature = "trace_task_modification")]
let _span = (!modified).then(|| tracing::trace_span!("mark_modified", name).entered());
match (self.storage.snapshot_mode(), modified) {
(false, false) => {
// Not in snapshot mode and item is unmodified
let bumped = !flags.any_modified();
if bumped {
let shard_idx = self.storage.shard_index(self.inner.key());
self.storage.shard_modified_counts[shard_idx].fetch_add(1, Ordering::Relaxed);
}
self.flags.set_modified(category, true);
TrackOutcome::Tracked { category, bumped }
}
(false, true) => {
// Not in snapshot mode and item is already modified
// Do nothing
TrackOutcome::NoChange
}
(true, false) => {
// In snapshot mode and item is unmodified (so it's not part of the snapshot)
// Mark it so it gets re-added as Modified after this snapshot completes.
// Insert a None entry into snapshots so end_snapshot discovers this task
// and promotes its _during_snapshot flags.
let inserted_snapshot = !flags.any_modified_during_snapshot();
if inserted_snapshot {
self.storage.snapshots.insert(*self.inner.key(), None);
}
self.flags.set_modified_during_snapshot(category, true);
TrackOutcome::TrackedDuringSnapshot {
category,
inserted_snapshot,
}
}
(true, true) => {
// In snapshot mode and item is modified (so it's part of the snapshot)
// We need to store the original version that is part of the snapshot
let inserted_snapshot = !flags.any_modified_during_snapshot();
if inserted_snapshot {
// Snapshot all non-transient fields, carrying the modified bits into
// the copy so the iterator knows which categories to persist.
if self.storage.snapshot_mode()
&& let Some(_writer) = self.storage.try_begin_snapshot_write()
{
// Registration plus the SeqCst mode recheck guarantees end_snapshot cannot drain the
// marker map until this publication is complete.
let inserted_snapshot = !flags.any_modified_during_snapshot();
if inserted_snapshot {
let snapshot = if modified {
// Snapshot all non-transient fields, carrying the modified bits into the copy
// so the iterator knows which categories to persist.
let mut snapshot = self.clone_snapshot();
snapshot.flags.set_data_modified(flags.data_modified());
snapshot.flags.set_meta_modified(flags.meta_modified());
snapshot.flags.set_new_task(flags.new_task());
self.storage
.snapshots
.insert(*self.inner.key(), Some(Box::new(snapshot)));
}
self.flags.set_modified_during_snapshot(category, true);
TrackOutcome::TrackedDuringSnapshot {
category,
inserted_snapshot,
}
Some(Box::new(snapshot))
} else {
None
};
self.storage.snapshots.insert(*self.inner.key(), snapshot);
}
self.flags.set_modified_during_snapshot(category, true);
return TrackOutcome::TrackedDuringSnapshot {
category,
inserted_snapshot,
};
}
if modified {
return TrackOutcome::NoChange;
}
let bumped = !flags.any_modified();
self.flags.set_modified(category, true);
if bumped {
// Publish work only after the protected state is visible. A racing snapshot can then
// at worst defer this task to its next cycle; it cannot consume an unmarked task.
self.storage.mark_dirty(*self.inner.key());
}
TrackOutcome::Tracked { category, bumped }
}
/// Reverse a [`TrackOutcome`] produced by [`Self::track_modification`] when the mutation it
......@@ -958,8 +803,7 @@ impl StorageWriteGuard<'_> {
TrackOutcome::Tracked { category, bumped } => {
self.flags.set_modified(category, false);
if bumped {
let shard_idx = self.storage.shard_index(self.inner.key());
self.storage.shard_modified_counts[shard_idx].fetch_sub(1, Ordering::Relaxed);
self.storage.unmark_dirty();
}
}
TrackOutcome::TrackedDuringSnapshot {
......@@ -986,8 +830,7 @@ impl StorageWriteGuard<'_> {
"only a never-persisted (new_task) collected task may be discarded this way"
);
if self.flags.any_modified() {
let shard_idx = self.storage.shard_index(self.inner.key());
self.storage.shard_modified_counts[shard_idx].fetch_sub(1, Ordering::Relaxed);
self.storage.unmark_dirty();
}
self.flags.set_meta_modified(false);
self.flags.set_data_modified(false);
......@@ -999,23 +842,13 @@ impl Deref for StorageWriteGuard<'_> {
type Target = TaskStorage;
fn deref(&self) -> &Self::Target {
self.task()
&self.inner
}
}
impl DerefMut for StorageWriteGuard<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: This guard owns the slot's task lock, and `inner` keeps it alive.
unsafe { &mut *self.inner.value().as_ptr() }
}
}
impl Drop for StorageWriteGuard<'_> {
fn drop(&mut self) {
// SAFETY: This guard acquired the lock in `new`, still owns it, and performs no task
// access after unlocking. Rust drops `inner` only after this method returns, so the Box
// remains alive through the unlock.
unsafe { self.inner.value().unlock() };
&mut self.inner
}
}
......@@ -1097,21 +930,15 @@ impl Drop for SnapshotGuard<'_> {
}
}
/// The work a single shard's iterator performs, with the snapshot mode encoded in the data rather
/// than a runtime flag re-checked per item. Built by `take_snapshot`'s scan.
/// A snapshot batch with its structural-removal mode encoded in the data.
enum ShardWork {
/// Normal snapshot: look each task up in the map while iterating, serialize it, then clear and
/// promote its modified flags so it stays dirty for the next snapshot cycle.
/// Normal snapshot: serialize each still-resident task, then clear/promote its flags.
Keep(Vec<TaskId>),
/// Shutdown drain: the scan already erased the unmodified entries and moved the remaining
/// (modified-only) shard table out of the map. The iterator owns that table and drains it
/// directly, freeing each task box as it is serialized. No second map lookup, no flag
/// bookkeeping (the whole map is discarded right after this snapshot).
Drain(hash_table::IntoIter<(TaskId, Box<TaskSlot>)>),
/// Shutdown drain: serialize each still-resident modified task and remove that exact entry.
Drain(Vec<TaskId>),
}
pub struct SnapshotShard<'l, P> {
shard_idx: usize,
work: ShardWork,
storage: &'l Storage,
process: &'l P,
......@@ -1167,44 +994,56 @@ where
}
};
match &mut self.shard.work {
ShardWork::Keep(modified) => {
let task_id = modified.pop()?;
let mut inner = self
.shard
.storage
.access_existing_mut(task_id)
.expect("snapshot task must remain resident while snapshot mode is active");
let item = serialize_task(task_id, &inner);
// Clear the modified flags that were captured into the snapshot copy,
// then promote modified_during_snapshot → modified so the task stays
// dirty for the next snapshot cycle.
loop {
let (task_id, drain) = match &mut self.shard.work {
ShardWork::Keep(modified) => (modified.pop()?, false),
ShardWork::Drain(modified) => (modified.pop()?, true),
};
let Some(mut inner) = self.shard.storage.access_existing_mut(task_id) else {
continue;
};
let item = serialize_task(task_id, &inner);
if drain {
// Remove only the exact entry protected and locked by this guard. A concurrent
// reinsertion for the same TaskId must not be removed.
self.shard.storage.map.remove_locked(&inner.inner);
} else {
// Clear the modified flags captured into the snapshot, then promote modifications
// that raced the snapshot so the task remains dirty for the next cycle.
inner.flags.set_data_modified(false);
inner.flags.set_meta_modified(false);
inner.flags.set_new_task(false);
self.shard
.storage
.promote_during_snapshot_flags(&mut inner, self.shard.shard_idx);
Some(item)
}
ShardWork::Drain(entries) => {
// Shutdown only: the scan already moved this shard's modified entries out of the
// map, so we own each `Box<TaskSlot>` here. Move out the storage, serialize it, and
// let it drop at the end of this branch — freeing the task's memory as it
// is persisted rather than after the whole batch is written. We skip the flag
// bookkeeping the normal path does, since the entire map is discarded right after
// this snapshot.
let (task_id, inner) = entries.next()?;
let inner = (*inner).into_inner();
Some(serialize_task(task_id, &inner))
// we don't need to update any bits because everything is getting dropped.
.promote_during_snapshot_flags(task_id, &mut inner);
}
return Some(item);
}
}
}
impl<P> Drop for SnapshotShardIter<'_, P> {
fn drop(&mut self) {
match &mut self.shard.work {
ShardWork::Keep(task_ids) => {
// take_snapshot claimed the original dirty work before producing this iterator.
// Re-publish unconsumed tasks so an early persistence error cannot lose them.
for task_id in task_ids.drain(..) {
if let Some(task) = self.shard.storage.access_existing_mut(task_id)
&& task.flags.any_modified()
{
self.shard.storage.mark_dirty(task_id);
}
}
}
ShardWork::Drain(task_ids) => {
for task_id in task_ids.drain(..) {
if let Some(task) = self.shard.storage.access_existing_mut(task_id) {
self.shard.storage.map.remove_locked(&task.inner);
}
}
}
}
self.shard
._guard
.return_scratch_buffer(std::mem::take(&mut self.buffer));
......@@ -1214,7 +1053,7 @@ impl<P> Drop for SnapshotShardIter<'_, P> {
#[cfg(test)]
mod tests {
use std::{
sync::{Arc, Barrier, mpsc},
sync::{Arc, Barrier, atomic::Ordering, mpsc},
thread,
time::Duration,
};
......@@ -1222,7 +1061,7 @@ mod tests {
use turbo_bincode::TurboBincodeBuffer;
use turbo_tasks::TaskId;
use super::{SpecificTaskDataCategory, Storage, TrackOutcome};
use super::{DIRTY_QUEUE_LIMIT, SpecificTaskDataCategory, Storage, TrackOutcome};
use crate::backing_storage::SnapshotItem;
fn non_transient_task(id: u32) -> TaskId {
......@@ -1232,30 +1071,27 @@ mod tests {
#[test]
fn new_task_is_pinned_during_construction() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let task_id = non_transient_task(1);
storage.initialize_new_task(task_id, None);
let task = storage.access_mut(task_id);
assert_eq!(task.gc_transient_ref_count(), 1);
assert!(!task.gc_collectible());
}
fn task_pair(storage: &Storage, same_shard: bool) -> (TaskId, TaskId) {
let first = non_transient_task(1);
let first_shard = storage.shard_index(&first);
let second = (2..10_000)
.map(non_transient_task)
.find(|task| (storage.shard_index(task) == first_shard) == same_shard)
.expect("the test map should expose both same- and cross-shard task pairs");
(first, second)
fn task_pair() -> (TaskId, TaskId) {
(non_transient_task(1), non_transient_task(2))
}
fn snapshot_value(storage: &Storage, task_id: TaskId) -> Option<bool> {
storage.snapshots.get(&task_id).map(|value| value.is_some())
}
}
#[test]
fn unrelated_tasks_in_one_shard_lock_independently() {
let storage = Arc::new(Storage::new(2, true));
let (task1, task2) = task_pair(&storage, true);
fn unrelated_tasks_lock_independently() {
let storage = Arc::new(Storage::new(true));
let (task1, task2) = task_pair();
drop(storage.access_mut(task2));
let task1_guard = storage.access_mut(task1);
let (tx, rx) = mpsc::sync_channel(1);
......@@ -1272,7 +1108,7 @@ mod tests {
#[test]
fn same_task_lock_excludes_another_accessor() {
let storage = Arc::new(Storage::new(2, true));
let storage = Arc::new(Storage::new(true));
let task = non_transient_task(1);
let guard = storage.access_mut(task);
let (tx, rx) = mpsc::sync_channel(1);
......@@ -1289,7 +1125,7 @@ mod tests {
#[test]
fn concurrent_first_access_inserts_one_task() {
let storage = Arc::new(Storage::new(2, true));
let storage = Arc::new(Storage::new(true));
let task = non_transient_task(1);
let barrier = Arc::new(Barrier::new(8));
let joins: Vec<_> = (0..8)
......@@ -1310,13 +1146,13 @@ mod tests {
#[test]
fn structural_remove_waits_for_task_guard() {
let storage = Arc::new(Storage::new(2, true));
let storage = Arc::new(Storage::new(true));
let task = non_transient_task(1);
let guard = storage.access_mut(task);
let (tx, rx) = mpsc::sync_channel(1);
let other = storage.clone();
let join = thread::spawn(move || {
let removed = other.map.remove(&task).is_some();
let removed = other.map.remove(task);
tx.send(removed).unwrap();
});
assert!(rx.recv_timeout(Duration::from_millis(50)).is_err());
......@@ -1326,34 +1162,32 @@ mod tests {
}
#[test]
fn pair_access_supports_same_and_cross_shard_opposing_order() {
for same_shard in [true, false] {
let storage = Arc::new(Storage::new(2, true));
let (task1, task2) = task_pair(&storage, same_shard);
let barrier = Arc::new(Barrier::new(2));
let (tx, rx) = mpsc::sync_channel(2);
let joins: Vec<_> = [(task1, task2), (task2, task1)]
.into_iter()
.map(|(first, second)| {
let storage = storage.clone();
let barrier = barrier.clone();
let tx = tx.clone();
thread::spawn(move || {
barrier.wait();
let (first_guard, second_guard) = storage.access_pair_mut(first, second);
assert_eq!(*first_guard.inner.key(), first);
assert_eq!(*second_guard.inner.key(), second);
drop((first_guard, second_guard));
tx.send(()).unwrap();
})
fn pair_access_supports_opposing_order() {
let storage = Arc::new(Storage::new(true));
let (task1, task2) = task_pair();
let barrier = Arc::new(Barrier::new(2));
let (tx, rx) = mpsc::sync_channel(2);
let joins: Vec<_> = [(task1, task2), (task2, task1)]
.into_iter()
.map(|(first, second)| {
let storage = storage.clone();
let barrier = barrier.clone();
let tx = tx.clone();
thread::spawn(move || {
barrier.wait();
let (first_guard, second_guard) = storage.access_pair_mut(first, second);
assert_eq!(*first_guard.inner.key(), first);
assert_eq!(*second_guard.inner.key(), second);
drop((first_guard, second_guard));
tx.send(()).unwrap();
})
.collect();
drop(tx);
rx.recv_timeout(Duration::from_secs(2)).unwrap();
rx.recv_timeout(Duration::from_secs(2)).unwrap();
for join in joins {
join.join().unwrap();
}
})
.collect();
drop(tx);
rx.recv_timeout(Duration::from_secs(2)).unwrap();
rx.recv_timeout(Duration::from_secs(2)).unwrap();
for join in joins {
join.join().unwrap();
}
}
......@@ -1377,7 +1211,7 @@ mod tests {
/// modification forward to the next cycle.
///
/// Sequence of events:
/// 1. Task is modified (data_modified = true) → added to shard_modified_counts.
/// 1. Task is modified (data_modified = true) → increments modified_count.
/// 2. `start_snapshot` puts us in snapshot mode.
/// 3. `take_snapshot` scans the shard: task has `any_modified()=true` → goes into the
/// `modified` list.
......@@ -1393,7 +1227,7 @@ mod tests {
// requiring a multi-threaded Tokio runtime.
#[tokio::test(flavor = "multi_thread")]
async fn modify_during_snapshot_clears_live_modified_flags() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let task_id = non_transient_task(1);
// Step 1: modify the task outside snapshot mode (data_modified = true).
......@@ -1440,12 +1274,12 @@ mod tests {
assert!(guard.flags.data_modified());
}
// The during-snapshot modification must be reflected in shard_modified_counts so
// The during-snapshot modification must be reflected in modified_count so
// the next snapshot cycle picks it up. Verify by starting another snapshot.
let (_guard2, has_modifications) = storage.start_snapshot();
assert!(
has_modifications,
"shard_modified_counts must be non-zero after promoting modified_during_snapshot"
"modified_count must be non-zero after promoting modified_during_snapshot"
);
}
......@@ -1465,7 +1299,7 @@ mod tests {
/// flags, and promotes `data_modified_during_snapshot → data_modified`.
#[tokio::test(flavor = "multi_thread")]
async fn modify_different_category_during_snapshot() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let task_id = non_transient_task(1);
// Step 1: modify meta only, outside snapshot mode.
......@@ -1514,7 +1348,7 @@ mod tests {
let (_guard2, has_modifications) = storage.start_snapshot();
assert!(
has_modifications,
"shard_modified_counts must be non-zero after promoting data_modified_during_snapshot"
"modified_count must be non-zero after promoting data_modified_during_snapshot"
);
}
......@@ -1524,7 +1358,7 @@ mod tests {
/// entry must be gone from the map by the time the snapshot is consumed.
#[tokio::test(flavor = "multi_thread")]
async fn drain_entries_removes_entry_from_map() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let task_id = non_transient_task(1);
// Modify the task outside snapshot mode so it lands in the modified list.
......@@ -1532,7 +1366,7 @@ mod tests {
let mut guard = storage.access_mut(task_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
}
assert!(storage.map.get(&task_id).is_some());
assert!(storage.map.contains(task_id));
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
......@@ -1551,32 +1385,22 @@ mod tests {
// The entry must be gone from the map now that it has been persisted.
assert!(
storage.map.get(&task_id).is_none(),
!storage.map.contains(task_id),
"task entry should be removed from the map after being persisted in drain mode"
);
}
/// In drain mode, fully consuming the iterators should release each drained shard's table
/// allocation entirely (reset-to-empty in `SnapshotShardIter::drop`), not just shrink it.
/// In drain mode, fully consuming the iterators removes every Papaya entry. Reclamation of
/// retired nodes is deferred until protection guards have advanced.
#[tokio::test(flavor = "multi_thread")]
async fn drain_entries_releases_drained_shards() {
// dashmap requires at least 2 shards.
let storage = Storage::new(2, true);
async fn drain_entries_removes_all_entries() {
let storage = Storage::new(true);
// Insert and modify enough tasks to grow the shards' tables beyond their minimum.
let task_ids: Vec<_> = (1..=256).map(non_transient_task).collect();
for &task_id in &task_ids {
let mut guard = storage.access_mut(task_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
}
let grown_capacity: usize = storage
.map
.shards()
.iter()
.map(|s| s.read().capacity())
.sum();
assert!(grown_capacity >= task_ids.len());
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
......@@ -1587,27 +1411,15 @@ mod tests {
.collect();
assert_eq!(items.len(), task_ids.len());
// Every shard is now empty and its table allocation has been released (capacity 0),
// since the reset swaps in the allocation-free default table.
for shard in storage.map.shards() {
let shard = shard.read();
assert_eq!(shard.len(), 0);
assert_eq!(
shard.capacity(),
0,
"drained shard should have released its table allocation"
);
}
assert_eq!(storage.map.len(), 0);
}
/// In drain mode, `take_snapshot`'s scan removes *both* kinds of entry from the map: unmodified
/// entries are erased and freed (never serialized), and the remaining modified-only table is
/// moved out into the shard iterators (to be serialized, then freed as each is consumed). So
/// the map is already empty when `take_snapshot` returns, and only the modified task is
/// yielded.
/// In drain mode, `take_snapshot` removes unmodified tasks immediately and leaves modified
/// tasks protected in the map until their snapshot batch serializes and removes the exact
/// entry.
#[tokio::test(flavor = "multi_thread")]
async fn drain_entries_removes_unmodified_during_take_snapshot() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let modified_id = non_transient_task(1);
let unmodified_id = non_transient_task(2);
......@@ -1619,22 +1431,21 @@ mod tests {
}
// `access_mut` inserts an entry; leaving it without track_modification keeps it unmodified.
let _ = storage.access_mut(unmodified_id);
assert!(storage.map.get(&unmodified_id).is_some());
assert!(storage.map.contains(unmodified_id));
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, true);
// The scan moved the modified table out and freed the unmodified entry, so both ids are
// already absent from the map before any iterator is consumed.
// Unmodified work is removed during the scan; modified work remains until serialized.
assert!(
storage.map.get(&unmodified_id).is_none(),
!storage.map.contains(unmodified_id),
"unmodified entry should be removed during take_snapshot in drain mode"
);
assert!(
storage.map.get(&modified_id).is_none(),
"modified entry should be moved out of the map during take_snapshot in drain mode"
storage.map.contains(modified_id),
"modified entry must remain protected until its snapshot item is serialized"
);
// Consuming the iterators yields only the modified task (the unmodified one was never part
......@@ -1645,11 +1456,97 @@ mod tests {
.collect();
assert_eq!(items.len(), 1);
assert_eq!(items[0].task_id(), modified_id);
assert!(!storage.map.contains(modified_id));
}
#[tokio::test(flavor = "multi_thread")]
async fn clean_snapshot_skips_resident_map_scan() {
let storage = Storage::new(true);
drop(storage.access_mut(non_transient_task(1)));
let scans = storage.map.task_id_scan_count();
let (guard, has_modifications) = storage.start_snapshot();
assert!(!has_modifications);
assert!(
storage
.take_snapshot(guard, &dummy_process, false)
.is_empty()
);
assert_eq!(storage.map.task_id_scan_count(), scans);
}
#[tokio::test(flavor = "multi_thread")]
async fn stale_dirty_queue_entries_are_deduplicated() {
let storage = Storage::new(true);
let task_id = non_transient_task(1);
{
let mut task = storage.access_mut(task_id);
let outcome = task.track_modification(SpecificTaskDataCategory::Data, "first");
task.undo_track_modification(outcome);
let _ = task.track_modification(SpecificTaskDataCategory::Data, "second");
}
let (guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let items: Vec<_> = storage
.take_snapshot(guard, &dummy_process, false)
.into_iter()
.flat_map(IntoIterator::into_iter)
.collect();
assert_eq!(items.len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn dirty_queue_overflow_falls_back_to_full_scan() {
let storage = Storage::new(true);
for id in 1..=(DIRTY_QUEUE_LIMIT as u32 + 1) {
let mut task = storage.access_mut(non_transient_task(id));
let _ = task.track_modification(SpecificTaskDataCategory::Data, "overflow");
}
let scans = storage.map.task_id_scan_count();
let (guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let items: Vec<_> = storage
.take_snapshot(guard, &dummy_process, false)
.into_iter()
.flat_map(IntoIterator::into_iter)
.collect();
assert_eq!(items.len(), DIRTY_QUEUE_LIMIT + 1);
assert_eq!(storage.map.task_id_scan_count(), scans + 1);
}
#[test]
fn dirty_counter_decrement_saturates_at_zero() {
let storage = Storage::new(true);
storage.unmark_dirty();
assert_eq!(storage.modified_count.load(Ordering::Relaxed), 0);
}
#[tokio::test(flavor = "multi_thread")]
async fn dropping_keep_iterator_requeues_unconsumed_tasks() {
let storage = Storage::new(true);
for id in 1..=2 {
let mut task = storage.access_mut(non_transient_task(id));
let _ = task.track_modification(SpecificTaskDataCategory::Data, "drop");
}
let (guard, _) = storage.start_snapshot();
let mut batches = storage.take_snapshot(guard, &dummy_process, false);
let mut iter = batches.pop().unwrap().into_iter();
assert!(iter.next().is_some());
drop(iter);
drop(batches);
let (guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let remaining: Vec<_> = storage
.take_snapshot(guard, &dummy_process, false)
.into_iter()
.flat_map(IntoIterator::into_iter)
.collect();
assert_eq!(remaining.len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn undo_non_snapshot_reverses_flag_and_counter() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let task_id = non_transient_task(1);
{
......@@ -1665,7 +1562,7 @@ mod tests {
let (_guard, has_modifications) = storage.start_snapshot();
assert!(
!has_modifications,
"undo must decrement the shard counter so no modifications remain"
"undo must decrement the dirty counter so no modifications remain"
);
}
......@@ -1673,7 +1570,7 @@ mod tests {
/// must NOT clear the real modification recorded by the first track.
#[tokio::test(flavor = "multi_thread")]
async fn undo_nochange_preserves_prior_modification() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let task_id = non_transient_task(1);
let mut guard = storage.access_mut(task_id);
......@@ -1694,7 +1591,7 @@ mod tests {
/// outcome must leave Data modified and the shard counter still non-zero.
#[tokio::test(flavor = "multi_thread")]
async fn undo_only_reverses_its_own_category() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let task_id = non_transient_task(1);
{
......@@ -1717,7 +1614,7 @@ mod tests {
/// Undo must remove the marker and clear the bit.
#[tokio::test(flavor = "multi_thread")]
async fn undo_during_snapshot_true_false_removes_marker() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let task_id = non_transient_task(1);
// Insert the task (unmodified) so it exists in the map.
let _ = storage.access_mut(task_id);
......@@ -1734,12 +1631,12 @@ mod tests {
}
));
assert!(guard.flags.data_modified_during_snapshot());
assert!(storage.snapshots.get(&task_id).is_some());
assert!(snapshot_value(&storage, task_id).is_some());
guard.undo_track_modification(outcome);
assert!(!guard.flags.data_modified_during_snapshot());
assert!(
storage.snapshots.get(&task_id).is_none(),
snapshot_value(&storage, task_id).is_none(),
"undo must remove the snapshots marker it inserted"
);
}
......@@ -1750,7 +1647,7 @@ mod tests {
/// belongs to the snapshot, not to this call).
#[tokio::test(flavor = "multi_thread")]
async fn undo_during_snapshot_true_true_removes_copy_preserves_modified() {
let storage = Storage::new(2, true);
let storage = Storage::new(true);
let task_id = non_transient_task(1);
// Modify before snapshot so the category is part of the snapshot.
......@@ -1770,10 +1667,7 @@ mod tests {
..
}
));
assert!(matches!(
storage.snapshots.get(&task_id).as_deref(),
Some(Some(_))
));
assert_eq!(snapshot_value(&storage, task_id), Some(true));
guard.undo_track_modification(outcome);
assert!(!guard.flags.data_modified_during_snapshot());
......@@ -1782,7 +1676,7 @@ mod tests {
"the pre-snapshot modification belongs to the snapshot and must survive undo"
);
assert!(
storage.snapshots.get(&task_id).is_none(),
snapshot_value(&storage, task_id).is_none(),
"undo must remove the pre-mutation copy it inserted"
);
}
......
......@@ -97,16 +97,20 @@ impl fmt::Debug for IntrusiveTaskLock {
///
/// - An unlocked slot never exposes a `TaskStorage` reference.
/// - `lock` acquires the embedded task lock through the raw slot pointer before references exist.
/// - Only a lock-owning storage guard may call `get` or materialize a mutable reference from
/// `as_ptr`.
/// - A structural map write guard may call `get_mut_exclusive` because it excludes all map readers.
/// - After locking, a reader checks `present`; a stale Papaya reader retries when removal cleared
/// it.
/// - Only a lock-owning storage guard that observed `present` may call `get` or materialize a
/// mutable reference from `as_ptr`.
/// - Structural removal detaches the exact entry and clears `present` before unlocking.
/// - The task lock is released before the map guard that keeps this allocation alive.
#[repr(transparent)]
pub(crate) struct TaskSlot(UnsafeCell<TaskStorage>);
impl TaskSlot {
pub(crate) fn new() -> Self {
Self(UnsafeCell::new(TaskStorage::new()))
let mut task = TaskStorage::new();
task.present = true;
Self(UnsafeCell::new(task))
}
pub(crate) fn as_ptr(&self) -> *mut TaskStorage {
......@@ -126,20 +130,29 @@ impl TaskSlot {
unsafe { (&*std::ptr::addr_of!((*self.as_ptr()).lock)).unlock() };
}
/// Whether this slot is still published as the resident value for its TaskId.
///
/// # Safety
/// The caller must own this slot's task lock, or hold an exclusive shard write guard that
/// prevents every concurrent access to this slot.
pub(crate) unsafe fn get(&self) -> &TaskStorage {
// SAFETY: Forwarded from the caller.
unsafe { &*self.as_ptr() }
/// The caller must own this slot's task lock.
pub(crate) unsafe fn is_present(&self) -> bool {
// SAFETY: Forwarded from the caller; projection does not materialize TaskStorage.
unsafe { std::ptr::addr_of!((*self.as_ptr()).present).read() }
}
pub(crate) fn get_mut_exclusive(&mut self) -> &mut TaskStorage {
self.0.get_mut()
/// Marks a detached resident-map value so stale protected readers retry their lookup.
///
/// # Safety
/// The caller must own this slot's task lock and must have detached this exact map value.
pub(crate) unsafe fn mark_removed(&self) {
// SAFETY: Forwarded from the caller; projection does not materialize TaskStorage.
unsafe { std::ptr::addr_of_mut!((*self.as_ptr()).present).write(false) };
}
pub(crate) fn into_inner(self) -> TaskStorage {
self.0.into_inner()
/// # Safety
/// The caller must own this slot's task lock and have observed `is_present()`.
pub(crate) unsafe fn get(&self) -> &TaskStorage {
// SAFETY: Forwarded from the caller.
unsafe { &*self.as_ptr() }
}
#[cfg(test)]
......@@ -147,24 +160,10 @@ impl TaskSlot {
// SAFETY: Reading the raw lock state does not expose the task payload.
unsafe { (&*std::ptr::addr_of!((*self.as_ptr()).lock)).is_locked() }
}
pub(crate) fn with_lock<R>(&self, f: impl FnOnce(&TaskStorage) -> R) -> R {
self.lock();
struct Unlock<'a>(&'a TaskSlot);
impl Drop for Unlock<'_> {
fn drop(&mut self) {
// SAFETY: `with_lock` acquired this lock and the closure has returned/unwound.
unsafe { self.0.unlock() };
}
}
let _unlock = Unlock(self);
// SAFETY: The lock-owning lexical guard remains alive through the closure.
f(unsafe { self.get() })
}
}
// SAFETY: all shared payload access is governed by the protocol above. Structural mutation uses
// `&mut TaskSlot`, while ordinary mutation owns the embedded task lock.
// SAFETY: all shared payload access is governed by the protocol above and owns the embedded task
// lock.
unsafe impl Sync for TaskSlot {}
/// The complete task storage schema.
......@@ -1967,9 +1966,14 @@ mod tests {
slot.lock();
assert!(slot.is_locked());
// SAFETY: This test holds the slot lock until after cloning.
assert!(unsafe { slot.is_present() });
let snapshot = unsafe { slot.get() }.clone_snapshot();
assert!(slot.is_locked());
assert!(!snapshot.lock.is_locked());
assert!(
!snapshot.present,
"snapshot copies are not resident map slots"
);
// SAFETY: This test acquired the source lock above and accesses it no further.
unsafe { slot.unlock() };
}
......
#[cfg(test)]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::{
marker::PhantomData,
ops::{Deref, DerefMut},
ptr,
};
use papaya::{HashMap, LocalGuard};
use rustc_hash::FxBuildHasher;
use turbo_tasks::TaskId;
use crate::backend::storage_schema::{TaskSlot, TaskStorage};
/// Sparse resident task map backed by Papaya.
///
/// Papaya pins keep entries alive across concurrent removal. `TaskSlot`'s intrusive lock provides
/// payload exclusion. A lookup that loaded a value before removal locks it and observes its
/// lock-protected `present` byte; removal clears that byte before unlock, so the stale reader
/// retries without a second map probe.
pub(crate) struct TaskMap {
map: HashMap<TaskId, TaskSlot, FxBuildHasher>,
#[cfg(test)]
task_id_scans: AtomicUsize,
}
impl TaskMap {
pub(crate) fn new(capacity: usize) -> Self {
// DashMap's million-entry preallocation is split across many shards. Applying it to one
// contiguous Papaya table hurts small working sets; start modestly and let Papaya resize.
let capacity = capacity.min(16 * 1024);
Self {
map: HashMap::with_capacity_and_hasher(capacity, FxBuildHasher),
#[cfg(test)]
task_id_scans: AtomicUsize::new(0),
}
}
pub(crate) fn len(&self) -> usize {
self.map.len()
}
pub(crate) fn get(&self, task_id: TaskId) -> Option<TaskMapGuard<'_>> {
self.get_inner(task_id, false)
}
pub(crate) fn get_or_insert(&self, task_id: TaskId) -> TaskMapGuard<'_> {
self.get(task_id).unwrap_or_else(|| {
self.get_inner(task_id, true)
.expect("get-or-insert must return the inserted task")
})
}
fn get_inner(&self, task_id: TaskId, insert: bool) -> Option<TaskMapGuard<'_>> {
loop {
let guard = self.map.guard();
let slot = if insert {
self.map.get_or_insert_with(task_id, TaskSlot::new, &guard)
} else {
self.map.get(&task_id, &guard)?
} as *const TaskSlot;
// The Papaya guard keeps this slot allocated while its task lock is acquired.
unsafe { &*slot }.lock();
// Removal may have detached this slot while we waited. It clears `present` under this
// same lock before releasing it, so a stale reader can retry without another hash
// probe.
if unsafe { (&*slot).is_present() } {
return Some(TaskMapGuard {
map: self,
guard,
task_id,
slot,
_not_send: PhantomData,
});
}
// SAFETY: We acquired this exact slot's task lock above and expose no task reference.
unsafe { (&*slot).unlock() };
}
}
pub(crate) fn task_ids(&self) -> Vec<TaskId> {
#[cfg(test)]
self.task_id_scans.fetch_add(1, Ordering::Relaxed);
let guard = self.map.guard();
self.map.iter(&guard).map(|(key, _)| *key).collect()
}
/// Process a batch of still-present tasks with one Papaya protection guard. Each callback owns
/// only the current task's intrusive lock; no task reference escapes the call.
pub(crate) fn for_each_locked(
&self,
task_ids: &[TaskId],
mut process: impl FnMut(TaskId, &TaskStorage),
) {
struct Unlock<'a>(&'a TaskSlot);
impl Drop for Unlock<'_> {
fn drop(&mut self) {
// SAFETY: The loop acquired this exact slot lock before constructing the guard.
unsafe { self.0.unlock() };
}
}
let guard = self.map.guard();
for &task_id in task_ids {
let Some(slot) = self.map.get(&task_id, &guard) else {
continue;
};
slot.lock();
let _unlock = Unlock(slot);
// SAFETY: `_unlock` owns the slot lock. Removed entries have `present` cleared before
// unlock, so stale protected values are skipped.
if unsafe { slot.is_present() } {
process(task_id, unsafe { slot.get() });
}
}
}
#[cfg(test)]
pub(crate) fn task_id_scan_count(&self) -> usize {
self.task_id_scans.load(Ordering::Relaxed)
}
#[cfg(test)]
pub(crate) fn contains(&self, task_id: TaskId) -> bool {
let guard = self.map.guard();
self.map.get(&task_id, &guard).is_some()
}
#[cfg(test)]
pub(crate) fn remove(&self, task_id: TaskId) -> bool {
self.get(task_id)
.is_some_and(|task| self.remove_locked(&task))
}
pub(crate) fn remove_locked(&self, task: &TaskMapGuard<'_>) -> bool {
debug_assert!(ptr::eq(self, task.map));
let removed = self
.map
.remove_if(
&task.task_id,
|_, current| ptr::eq(current, task.slot),
&task.guard,
)
.is_ok_and(|removed| removed.is_some());
if removed {
// SAFETY: `task` owns this exact slot's lock, and remove_if detached this exact value.
unsafe { (&*task.slot).mark_removed() };
}
removed
}
pub(crate) fn clear(&self) {
for task_id in self.task_ids() {
if let Some(task) = self.get(task_id) {
self.remove_locked(&task);
}
}
}
}
/// Owns both Papaya's lifetime protection and one task's intrusive lock.
pub(crate) struct TaskMapGuard<'a> {
map: &'a TaskMap,
// Declared before `slot` only for clarity; `Drop` releases the task lock explicitly before
// Papaya protection is dropped.
guard: LocalGuard<'a>,
task_id: TaskId,
slot: *const TaskSlot,
// Task guards must not cross `.await`, even if Papaya changes LocalGuard's auto traits.
_not_send: PhantomData<*const ()>,
}
impl TaskMapGuard<'_> {
pub(crate) fn key(&self) -> &TaskId {
&self.task_id
}
}
impl Deref for TaskMapGuard<'_> {
type Target = TaskStorage;
fn deref(&self) -> &Self::Target {
// SAFETY: TaskMapGuard owns this slot's task lock and observed it present.
unsafe { (&*self.slot).get() }
}
}
impl DerefMut for TaskMapGuard<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: TaskMapGuard exclusively owns this slot's task lock and observed it present.
unsafe { &mut *(&*self.slot).as_ptr() }
}
}
impl Drop for TaskMapGuard<'_> {
fn drop(&mut self) {
// SAFETY: This guard acquired this slot's task lock and performs no payload access after
// unlocking. `guard` remains alive until after this Drop body, so the slot cannot be freed.
unsafe { (&*self.slot).unlock() };
}
}
#[cfg(test)]
mod tests {
use turbo_tasks::TaskId;
use super::{TaskMap, TaskSlot};
fn task_id(id: u32) -> TaskId {
TaskId::new(id).unwrap()
}
#[test]
fn removed_guard_stays_alive_but_cannot_replace_reinserted_task() {
let map = TaskMap::new(16);
let id = task_id(1);
let old = map.get_or_insert(id);
let stale_guard = map.map.guard();
let stale_slot = map.map.get(&id, &stale_guard).unwrap() as *const TaskSlot;
assert_eq!(stale_slot, old.slot);
assert!(map.remove_locked(&old));
let replacement = map.get_or_insert(id);
assert_ne!(stale_slot, replacement.slot);
assert_eq!(*old.key(), id);
assert_eq!(*replacement.key(), id);
assert!(!map.remove_locked(&old));
drop(old);
// This simulates a reader that protected the old entry before removal but reached its task
// lock only after the replacement was published.
unsafe { &*stale_slot }.lock();
// SAFETY: This test owns the stale slot's lock, and stale_guard keeps it allocated.
assert!(!unsafe { (&*stale_slot).is_present() });
// SAFETY: This test acquired the stale slot lock above.
unsafe { (&*stale_slot).unlock() };
drop(stale_guard);
assert!(map.remove_locked(&replacement));
assert_eq!(map.len(), 0);
}
}
......@@ -55,43 +55,3 @@ pub fn with_entry_in_shard<K: Eq + Hash, V, S: BuildHasher + Clone, Q: ?Sized, R
);
then(entry, query)
}
/// Outcome of [`try_lock_and_remove`].
pub enum TryLockAndRemove {
/// The shard lock was acquired and a matching entry was removed.
Removed,
/// The shard lock was acquired but no matching entry was present.
NotFound,
/// The shard lock was contended; the caller should retry later after releasing
/// any other locks they are holding.
WouldBlock,
}
/// Remove `key` from `map` without blocking on shard contention.
///
/// Intended for call sites that already hold another lock and want to avoid a
/// cyclic wait. On contention (`WouldBlock`), the caller is expected to defer the
/// removal and retry after dropping the other lock.
pub fn try_lock_and_remove<
K: Eq + Hash + AsRef<Q>,
V,
Q: Eq + Hash + ?Sized,
S: BuildHasher + Clone,
>(
map: &DashMap<K, V, S>,
key: &Q,
) -> TryLockAndRemove {
let hasher = map.hasher();
let hash = hasher.hash_one(key);
let shard_idx = map.determine_shard(hash as usize);
let Some(mut shard) = map.shards()[shard_idx].try_write() else {
return TryLockAndRemove::WouldBlock;
};
match shard.find_entry(hash, |(k, _v)| k.as_ref() == key) {
Ok(entry) => {
entry.remove();
TryLockAndRemove::Removed
}
Err(_) => TryLockAndRemove::NotFound,
}
}
use std::{
hash::{BuildHasher, Hash},
ops::Deref,
ptr::NonNull,
sync::Arc,
};
use dashmap::{DashMap, RawRwLock};
use hashbrown::HashTable;
use parking_lot::lock_api::{RwLockReadGuard, RwLockWriteGuard};
type ReadTableGuard<'a, K, V> = RwLockReadGuard<'a, RawRwLock, HashTable<(K, V)>>;
/// A read reference to one DashMap entry.
///
/// The shared variant lets two disjoint entries in the same shard share one read guard. This
/// avoids recursively acquiring a writer-preferring shard lock while retaining stable entry
/// addresses for each task's intrusive lock.
pub enum Ref<'a, K, V> {
Base(dashmap::mapref::one::Ref<'a, K, V>),
Simple {
_guard: ReadTableGuard<'a, K, V>,
entry: NonNull<(K, V)>,
},
Shared {
_guard: Arc<ReadTableGuard<'a, K, V>>,
entry: NonNull<(K, V)>,
},
}
// SAFETY: Each entry pointer remains valid under its shard read guard. Shared references never
// mutate the HashTable entry; payload mutation is independently synchronized by its intrusive
// lock. `K: Sync + V: Sync` makes shared references safe across threads.
unsafe impl<K: Eq + Hash + Sync, V: Sync> Sync for Ref<'_, K, V> {}
impl<K: Eq + Hash, V> Ref<'_, K, V> {
pub fn key(&self) -> &K {
self.pair().0
}
pub fn value(&self) -> &V {
self.pair().1
}
fn pair(&self) -> (&K, &V) {
match self {
Self::Base(reference) => reference.pair(),
Self::Simple { entry, .. } | Self::Shared { entry, .. } => {
// SAFETY: The entry remains valid while the corresponding shard read guard lives.
let entry = unsafe { entry.as_ref() };
(&entry.0, &entry.1)
}
}
}
}
impl<K: Eq + Hash, V> Deref for Ref<'_, K, V> {
type Target = V;
fn deref(&self) -> &Self::Target {
self.value()
}
}
impl<'a, K, V> From<dashmap::mapref::one::Ref<'a, K, V>> for Ref<'a, K, V>
where
K: Hash + Eq,
{
fn from(reference: dashmap::mapref::one::Ref<'a, K, V>) -> Self {
Self::Base(reference)
}
}
/// Get two disjoint read references, inserting missing values under shard write locks.
///
/// The caller must order calls to this function consistently when composing it with other locks.
pub fn get_disjoint<K, V>(
map: &DashMap<K, V, impl BuildHasher + Clone>,
key1: K,
key2: K,
insert_with: impl Fn() -> V,
) -> (Ref<'_, K, V>, Ref<'_, K, V>)
where
K: Hash + Eq + Clone,
{
assert!(
key1 != key2,
"`get_disjoint` was called with equal keys, which cannot produce disjoint task guards"
);
let hasher = map.hasher();
let hash_entry = |entry: &(K, _)| hasher.hash_one(&entry.0);
let hash1 = hasher.hash_one(&key1);
let hash2 = hasher.hash_one(&key2);
let shard1 = map.determine_shard(hash1 as usize);
let shard2 = map.determine_shard(hash2 as usize);
let shards = map.shards();
let find1 = |entry: &(K, _)| key1.eq(&entry.0);
let find2 = |entry: &(K, _)| key2.eq(&entry.0);
if shard1 == shard2 {
let guard = shards[shard1].read();
let entry1 = guard.find(hash1, find1).map(NonNull::from);
let entry2 = guard.find(hash2, find2).map(NonNull::from);
if let (Some(entry1), Some(entry2)) = (entry1, entry2) {
return shared_pair(guard, entry1, entry2);
}
drop(guard);
let mut guard = shards[shard1].write();
if guard.find(hash1, find1).is_none() {
guard.insert_unique(hash1, (key1.clone(), insert_with()), hash_entry);
}
if guard.find(hash2, find2).is_none() {
guard.insert_unique(hash2, (key2.clone(), insert_with()), hash_entry);
}
let entry1 = NonNull::from(guard.find(hash1, find1).expect("first entry was inserted"));
let entry2 = NonNull::from(guard.find(hash2, find2).expect("second entry was inserted"));
return shared_pair(RwLockWriteGuard::downgrade(guard), entry1, entry2);
}
let (first_shard, second_shard, first_is_key1) = if shard1 < shard2 {
(shard1, shard2, true)
} else {
(shard2, shard1, false)
};
let first_guard = shards[first_shard].read();
let second_guard = shards[second_shard].read();
let (guard1, guard2) = if first_is_key1 {
(first_guard, second_guard)
} else {
(second_guard, first_guard)
};
let entry1 = guard1.find(hash1, find1).map(NonNull::from);
let entry2 = guard2.find(hash2, find2).map(NonNull::from);
if let (Some(entry1), Some(entry2)) = (entry1, entry2) {
return (
Ref::Simple {
_guard: guard1,
entry: entry1,
},
Ref::Simple {
_guard: guard2,
entry: entry2,
},
);
}
drop(guard2);
drop(guard1);
let (mut guard1, mut guard2) = loop {
{
let guard1 = shards[shard1].write();
if let Some(guard2) = shards[shard2].try_write() {
break (guard1, guard2);
}
}
{
let guard2 = shards[shard2].write();
if let Some(guard1) = shards[shard1].try_write() {
break (guard1, guard2);
}
}
};
if guard1.find(hash1, find1).is_none() {
guard1.insert_unique(hash1, (key1.clone(), insert_with()), hash_entry);
}
if guard2.find(hash2, find2).is_none() {
guard2.insert_unique(hash2, (key2.clone(), insert_with()), hash_entry);
}
let entry1 = NonNull::from(guard1.find(hash1, find1).expect("first entry was inserted"));
let entry2 = NonNull::from(
guard2
.find(hash2, find2)
.expect("second entry was inserted"),
);
(
Ref::Simple {
_guard: RwLockWriteGuard::downgrade(guard1),
entry: entry1,
},
Ref::Simple {
_guard: RwLockWriteGuard::downgrade(guard2),
entry: entry2,
},
)
}
fn shared_pair<'a, K, V>(
guard: ReadTableGuard<'a, K, V>,
entry1: NonNull<(K, V)>,
entry2: NonNull<(K, V)>,
) -> (Ref<'a, K, V>, Ref<'a, K, V>) {
let guard = Arc::new(guard);
(
Ref::Shared {
_guard: guard.clone(),
entry: entry1,
},
Ref::Shared {
_guard: guard,
entry: entry2,
},
)
}
#[cfg(test)]
mod tests {
use std::thread::scope;
use rand::prelude::SliceRandom;
use turbo_tasks::FxDashMap;
use super::get_disjoint;
// The old writer-guard stress test is still useful as a check for concurrent insertions and
// same-shard pairs, but the shared-reference API no longer mutates the values it returns.
#[cfg(not(miri))]
#[test]
#[cfg_attr(
target_family = "wasm",
ignore = "stalls indefinitely under the Worker-based WASI host; tracked separately"
)]
fn stress_deadlock() {
const N: usize = 100_000;
const THREADS: usize = 20;
let map = FxDashMap::with_hasher_and_shard_amount(Default::default(), 4);
let indices = (0..THREADS)
.map(|_| {
let mut values = (0..N).collect::<Vec<_>>();
values.shuffle(&mut rand::rng());
values
})
.collect::<Vec<_>>();
scope(|scope| {
for indices in indices {
let map = &map;
scope.spawn(move || {
for i in indices {
let (a, b) = get_disjoint(map, i, i + 1, || 0);
assert_eq!(*a, 0);
assert_eq!(*b, 0);
}
});
}
});
assert_eq!(map.len(), N + 1);
}
}
pub mod dash_map_drop_contents;
pub mod dash_map_entry;
pub mod dash_map_multi;
pub mod markdown_table;
pub mod ptr_eq_arc;
pub mod shard_amount;
pub mod stopwatch;
pub mod swap_retain;
#[cfg(test)]
......
use turbo_tasks::parallel::available_parallelism;
/// Compute a good number of shards to use for sharded data structures.
/// The number of shards is computed based on the number of worker threads
/// and whether a small preallocation is requested.
/// A small preallocation is useful for tests where performance is not
/// critical and we want to reduce memory usage and startup time.
/// The number of shards is chosen to minimize the probability of shard
/// collisions (which can lead to false sharing) while keeping memory
/// usage reasonable.
/// The returned number is always a power of two as this is often required
/// by sharded data structures. The maximum shard amount is capped at 1 << 16 (65536).
pub fn compute_shard_amount(num_workers: Option<usize>, small_preallocation: bool) -> usize {
let num_workers = num_workers
.unwrap_or_else(|| available_parallelism().map_or(4, |v| v.get()))
.max(4);
// Once can compute the probability of a shard collision (which leads to false sharing) using
// the birthday paradox formula. It's notable that the probability of collisions increases
// with more worker threads. To mitigate this effect, the number of shards need to grow
// quadratically with the number of worker threads. This way the probability of at least one
// collision remains constant.
//
// Lets call the worker thread count `N` and the number of shards `S`. When using `S = k * N^2`
// for some constant `k` the probability of at least one collision for large `N` can be
// approximated as: P = 1 - exp(-N^2 / (2*S)) = 1 - exp(-1/(2*k))
//
// For `k = 2` this results in a collision probability of about 22%. Fine-grained task locks
// keep a shard collision from serializing independent task mutations, so the lower shard count
// saves memory without recreating the old shard-write-lock bottleneck.
//
// We clamp the number of shards to 1 << 16 to avoid excessive memory usage in case of a very
// high number of worker threads. With `k = 2`, this case is hit above roughly 181 workers.
if small_preallocation {
// We also clamp the maximum number of workers to 256 so all following multiplications can't
// overflow.
let num_workers = num_workers.min(256);
(num_workers * num_workers).next_power_of_two()
} else {
// Clamp the worker count so the shard total stays at or below 1 << 16.
let num_workers = num_workers.min(181);
(num_workers * num_workers * 2).next_power_of_two()
}
}
......@@ -1408,6 +1408,8 @@ fn generate_typed_storage_struct(grouped_fields: &GroupedFields) -> TokenStream
#lazy_field
#[doc = "Per-task lock used with a shared resident-map guard."]
lock: IntrusiveTaskLock,
#[doc = "Whether this allocation is still the resident-map value for its TaskId."]
present: bool,
}
#[automatically_derived]
......
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