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

Use sparse pointer pages for task storage

Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 7f97a3e7
......@@ -3489,16 +3489,6 @@ dependencies = [
"serde_json",
]
[[package]]
name = "kovan"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "069314825b47e60f2882bf6fc90ab66e3eb37ee5e4407de6357a124842fc3b26"
dependencies = [
"once_cell",
"portable-atomic",
]
[[package]]
name = "kqueue"
version = "1.2.1"
......@@ -9234,7 +9224,6 @@ dependencies = [
"indexmap 2.14.0",
"indoc",
"jiff",
"kovan",
"lz4_flex",
"parking_lot",
"rand 0.10.1",
......@@ -9246,6 +9235,7 @@ dependencies = [
"serde_json",
"serde_path_to_error",
"smallvec",
"static_assertions",
"tempfile",
"thiserror 1.0.69",
"thread_local",
......
......@@ -286,7 +286,6 @@ image = { version = "0.25.8", default-features = false }
indexmap = "2.14.0"
indoc = "2.0.0"
itertools = "0.10.5"
kovan = "0.1.20"
lightningcss = { version = "1.0.0-alpha.72", features = [
"serde",
"visitor",
......@@ -348,6 +347,7 @@ smallvec = { version = "1.15.1", features = [
"const_new",
] }
shrink-to-fit = "0.2.10"
static_assertions = "1.1.0"
strsim = "0.11.1"
swc_sourcemap = "10.0.2"
syn = "2.0.100"
......
......@@ -48,7 +48,6 @@ fs-err = { workspace = true }
hashbrown = { workspace = true }
indexmap = { workspace = true }
jiff = "0.2.10"
kovan = { workspace = true }
lz4_flex = { workspace = true, optional = true }
parking_lot = { workspace = true }
rand = { workspace = true }
......@@ -83,6 +82,7 @@ triomphe = { workspace = true }
thiserror = { workspace = true }
turbo-tasks-malloc = { workspace = true , features = ["custom_allocator"]}
rstest = { workspace = true }
static_assertions = { workspace = true }
turbo-tasks-testing = { workspace = true }
# The read-outcome tests assert on the counters, so they need them compiled in. Only for tests —
# normal builds of this crate get the default (disabled) turbo-tasks.
......
......@@ -3,7 +3,7 @@ use std::{
num::NonZeroU64,
sync::{
Arc, OnceLock,
atomic::{AtomicUsize, Ordering},
atomic::{AtomicU8, AtomicUsize, Ordering},
},
thread,
time::Instant,
......@@ -15,10 +15,18 @@ use turbo_tasks::{FxDashMap, TaskId};
use turbo_tasks_malloc::TurboMalloc;
#[allow(dead_code, unused_imports)]
#[path = "../src/backend/dense_task_map.rs"]
mod dense_task_map;
#[path = "../src/backend/task_page_map.rs"]
mod task_page_map;
use dense_task_map::{TaskMap, TaskSlotValue};
use task_page_map::{StorageAccessToken, TaskMap, TaskSlotValue};
fn operation() -> StorageAccessToken<'static> {
StorageAccessToken::operation()
}
fn exclusive() -> StorageAccessToken<'static> {
StorageAccessToken::exclusive()
}
const LOOKUP_TASKS: u32 = 64 * 1024;
const BUILD_TASKS: u32 = 8 * 1024;
......@@ -28,7 +36,6 @@ struct Payload {
niche: NonZeroU64,
data: [u64; 14],
lock: Mutex<()>,
occupied: bool,
}
impl Payload {
......@@ -37,7 +44,6 @@ impl Payload {
niche: NonZeroU64::new(id as u64).unwrap(),
data: [0; 14],
lock: Mutex::new(()),
occupied: false,
}
}
......@@ -51,15 +57,12 @@ impl Payload {
}
}
// SAFETY: Benchmark payload follows the same stable intrusive-lock/presence contract as
// SAFETY: Benchmark payload follows the same stable boxed intrusive-lock contract as
// TaskStorage. All access through TaskMap is guarded.
unsafe impl TaskSlotValue for Payload {
const EMPTY: Self = Self {
niche: NonZeroU64::MIN,
data: [0; 14],
lock: Mutex::new(()),
occupied: false,
};
fn new() -> Self {
Self::new(1)
}
unsafe fn lock_raw(value: *const Self) {
// SAFETY: TaskMap provides a live, stable benchmark payload pointer.
......@@ -73,43 +76,16 @@ unsafe impl TaskSlotValue for Payload {
let raw = unsafe { lock.raw() };
unsafe { raw.unlock() };
}
fn is_occupied(&self) -> bool {
self.occupied
}
fn occupy(&mut self) {
self.occupied = true;
}
fn take_and_vacate(&mut self) -> Self {
let detached = Self {
niche: self.niche,
data: self.data,
lock: Mutex::new(()),
occupied: false,
};
self.niche = NonZeroU64::MIN;
self.data = [0; 14];
self.occupied = false;
detached
}
fn vacate_in_place(&mut self) {
self.niche = NonZeroU64::MIN;
self.data = [0; 14];
self.occupied = false;
}
}
const CHUNK_SIZE: usize = dense_task_map::CHUNK_SIZE;
const CHUNK_SHIFT: usize = dense_task_map::CHUNK_SHIFT;
const CHUNK_MASK: usize = CHUNK_SIZE - 1;
const PAGE_SIZE: usize = task_page_map::PAGE_SIZE;
const PAGE_SHIFT: usize = task_page_map::PAGE_SHIFT;
const PAGE_MASK: usize = PAGE_SIZE - 1;
type ExternalSlot = Mutex<Option<Payload>>;
struct ExternalChunk {
slots: Box<[ExternalSlot; CHUNK_SIZE]>,
slots: Box<[ExternalSlot; PAGE_SIZE]>,
}
impl ExternalChunk {
......@@ -134,14 +110,11 @@ impl ExternalMap {
}
fn chunk(&self, index: usize) -> Option<&ExternalChunk> {
self.chunks
.get(index >> CHUNK_SHIFT)?
.get()
.map(Box::as_ref)
self.chunks.get(index >> PAGE_SHIFT)?.get().map(Box::as_ref)
}
fn get_or_create_chunk(&self, index: usize) -> &ExternalChunk {
let chunk_index = index >> CHUNK_SHIFT;
let chunk_index = index >> PAGE_SHIFT;
loop {
if let Some(chunk) = self.chunks.get(chunk_index) {
return chunk.get_or_init(|| Box::new(ExternalChunk::new()));
......@@ -157,13 +130,13 @@ impl ExternalMap {
fn get(&self, id: TaskId) -> Option<MappedMutexGuard<'_, Payload>> {
let index = *id as usize;
let chunk = self.chunk(index)?;
MutexGuard::try_map(chunk.slots[index & CHUNK_MASK].lock(), Option::as_mut).ok()
MutexGuard::try_map(chunk.slots[index & PAGE_MASK].lock(), Option::as_mut).ok()
}
fn get_or_insert(&self, id: TaskId) -> MappedMutexGuard<'_, Payload> {
let index = *id as usize;
let chunk = self.get_or_create_chunk(index);
let mut slot = chunk.slots[index & CHUNK_MASK].lock();
let mut slot = chunk.slots[index & PAGE_MASK].lock();
if slot.is_none() {
*slot = Some(Payload::new(*id));
self.len.fetch_add(1, Ordering::Relaxed);
......@@ -173,7 +146,7 @@ impl ExternalMap {
fn remove(&self, id: TaskId) -> Option<Payload> {
let index = *id as usize;
let value = self.chunk(index)?.slots[index & CHUNK_MASK].lock().take();
let value = self.chunk(index)?.slots[index & PAGE_MASK].lock().take();
if value.is_some() {
self.len.fetch_sub(1, Ordering::Relaxed);
}
......@@ -213,17 +186,17 @@ fn dense_map(count: u32, stride: u32) -> TaskMap<Payload> {
let map = TaskMap::<Payload>::new(true);
for i in 1..=count {
let raw = i * stride;
map.get_or_insert(task_id(raw)).set(raw);
map.get_or_insert(task_id(raw), operation()).set(raw);
}
map
}
fn dense_remove(map: &TaskMap<Payload>, id: TaskId) -> Option<Payload> {
map.get(id).map(|task| task.take_and_vacate())
map.get(id, exclusive()).map(|task| task.take_and_vacate())
}
fn dense_remove_discard(map: &TaskMap<Payload>, id: TaskId) -> bool {
let Some(task) = map.get(id) else {
let Some(task) = map.get(id, exclusive()) else {
return false;
};
task.vacate();
......@@ -232,7 +205,7 @@ fn dense_remove_discard(map: &TaskMap<Payload>, id: TaskId) -> bool {
fn scan_dense(map: &TaskMap<Payload>, use_bitmap: bool) -> u64 {
let mut sum = 0;
for chunk in map.chunks() {
for chunk in map.pages(operation()) {
if use_bitmap {
chunk.for_each_mut(|value| sum ^= value.value());
} else {
......@@ -247,7 +220,7 @@ fn scan_dense_parallel(
map: &TaskMap<Payload>,
use_bitmap: bool,
) -> u64 {
let chunks = map.chunks();
let chunks = map.pages(operation());
runtime.block_on(async {
let sums: Vec<u64> = turbo_tasks::parallel::map_collect(&chunks, |chunk| {
let mut sum = 0;
......@@ -318,16 +291,16 @@ fn report_isolated_memory(mode: &str, count: u32, stride: u32) {
}
}
fn report_reclamation(count: u32) {
fn report_reclamation(count: u32, stride: u32) {
TurboMalloc::collect(true);
let before = TurboMalloc::allocation_counters();
let dense = dense_map(count, 1);
let dense = dense_map(count, stride);
let live = TurboMalloc::allocation_counters();
let loaded_before = dense.loaded_chunk_count();
for raw in 1..=count {
assert!(dense_remove_discard(&dense, task_id(raw)));
let loaded_before = dense.loaded_page_count();
for i in 1..=count {
assert!(dense_remove_discard(&dense, task_id(i * stride)));
}
let retired = dense.retire_empty_chunks();
let reclaimed = dense.reclaim_empty_pages(exclusive());
TurboMalloc::collect(true);
let after = TurboMalloc::allocation_counters();
let live_delta = (live.allocations - before.allocations) as i128
......@@ -335,13 +308,15 @@ fn report_reclamation(count: u32) {
let after_delta = (after.allocations - before.allocations) as i128
- (after.deallocations - before.deallocations) as i128;
println!(
"resident_storage_reclamation tasks={count} chunk_size={} directory_entry_size={} \
directory_entries={} loaded_before={loaded_before} retired={retired} loaded_after={} \
live_counter_delta={live_delta} after_counter_delta={after_delta}",
dense_task_map::CHUNK_SIZE,
"resident_storage_reclamation tasks={count} high_water={} chunk_size={} \
directory_entry_size={} directory_entries={} loaded_before={loaded_before} \
reclaimed={reclaimed} loaded_after={} live_counter_delta={live_delta} \
after_counter_delta={after_delta}",
count * stride,
task_page_map::PAGE_SIZE,
TaskMap::<Payload>::directory_entry_size(),
dense.directory_entry_count(),
dense.loaded_chunk_count(),
dense.loaded_page_count(),
);
black_box(dense);
}
......@@ -360,9 +335,37 @@ pub fn resident_storage(c: &mut Criterion) {
return;
}
report_reclamation(100_000);
report_reclamation(100_000, 1);
report_reclamation(1, 8_000_000);
report_memory(100_000, 1, "dense");
report_memory(50_000, 2, "half_sparse");
report_memory(10_000, 10, "warm_sparse");
report_memory(1_000, 100, "one_percent_sparse");
report_memory(1, 8_000_000, "isolated_high_id");
let mut epoch_counter = c.benchmark_group("resident_storage_epoch_counter");
epoch_counter.throughput(Throughput::Elements(1));
let active_guards = AtomicU8::new(0);
epoch_counter.bench_function("active_guard_rmw_pair", |b| {
b.iter(|| {
active_guards.fetch_add(1, Ordering::AcqRel);
active_guards.fetch_sub(1, Ordering::AcqRel);
})
});
epoch_counter.bench_function("active_guard_load_store_pair", |b| {
b.iter(|| {
let previous = active_guards.load(Ordering::Relaxed);
debug_assert_eq!(previous, 0);
active_guards.store(1, Ordering::Relaxed);
let previous = active_guards.load(Ordering::Relaxed);
debug_assert_eq!(previous, 1);
active_guards.store(0, Ordering::Relaxed);
})
});
epoch_counter.bench_function("active_guard_acquire_load", |b| {
b.iter(|| black_box(active_guards.load(Ordering::Acquire)))
});
epoch_counter.finish();
let dash = dash_map(LOOKUP_TASKS, 1);
let external = external_map(LOOKUP_TASKS, 1);
......@@ -389,7 +392,7 @@ pub fn resident_storage(c: &mut Criterion) {
lookup.bench_function("dense", |b| {
b.iter(|| {
next = next % LOOKUP_TASKS + 1;
black_box(dense.get(task_id(next)).unwrap().value())
black_box(dense.get(task_id(next), operation()).unwrap().value())
})
});
let mut next = 1_u32;
......@@ -414,7 +417,9 @@ pub fn resident_storage(c: &mut Criterion) {
b.iter(|| {
next = next % LOOKUP_TASKS + 1;
let id = task_id(next);
let item = dense.get(id).unwrap_or_else(|| dense.get_or_insert(id));
let item = dense
.get(id, operation())
.unwrap_or_else(|| dense.get_or_insert(id, operation()));
black_box(item.value())
})
});
......@@ -468,7 +473,7 @@ pub fn resident_storage(c: &mut Criterion) {
next = next % LOOKUP_TASKS + 1;
let id = task_id(next);
black_box(dense_remove(&dense, id));
let mut item = dense.get_or_insert(id);
let mut item = dense.get_or_insert(id, operation());
item.set(next);
black_box(item.value());
})
......@@ -493,7 +498,7 @@ pub fn resident_storage(c: &mut Criterion) {
next = next % LOOKUP_TASKS + 1;
let id = task_id(next);
black_box(dense_remove_discard(&dense, id));
dense.get_or_insert(id).set(next);
dense.get_or_insert(id, operation()).set(next);
})
});
discard_reuse.finish();
......@@ -511,7 +516,7 @@ pub fn resident_storage(c: &mut Criterion) {
scope.spawn(move || {
for _ in 0..per_thread {
black_box(dense_remove_discard(&dense, id));
dense.get_or_insert(id).set(*id);
dense.get_or_insert(id, operation()).set(*id);
}
});
}
......@@ -537,7 +542,7 @@ pub fn resident_storage(c: &mut Criterion) {
for &id in &colliding_ids {
dash.insert(id, Box::new(Payload::new(*id)));
external.get_or_insert(id).set(*id);
dense.get_or_insert(id).set(*id);
dense.get_or_insert(id, operation()).set(*id);
}
let mut contention = c.benchmark_group("resident_storage_independent_task_contention");
contention.bench_function("dash_map_same_shard", |b| {
......@@ -583,7 +588,7 @@ pub fn resident_storage(c: &mut Criterion) {
let dense = dense.clone();
scope.spawn(move || {
for _ in 0..per_thread {
dense.get(id).unwrap().data[0] ^= 1;
dense.get(id, operation()).unwrap().data[0] ^= 1;
}
});
}
......@@ -622,7 +627,7 @@ pub fn resident_storage(c: &mut Criterion) {
iteration.bench_function("dense", |b| {
b.iter(|| {
let mut sum = 0_u64;
for chunk in dense.chunks() {
for chunk in dense.pages(operation()) {
chunk.for_each_mut(|value| sum ^= value.value());
}
black_box(sum)
......@@ -647,7 +652,7 @@ pub fn resident_storage(c: &mut Criterion) {
})
});
iteration.bench_function("dense_parallel", |b| {
let chunks = dense.chunks();
let chunks = dense.pages(operation());
b.iter(|| {
runtime.block_on(async {
let sums: Vec<u64> = turbo_tasks::parallel::map_collect(&chunks, |chunk| {
......@@ -663,17 +668,6 @@ pub fn resident_storage(c: &mut Criterion) {
let dash = dash_map(SPARSE_TASKS, 10);
let dense = dense_map(SPARSE_TASKS, 10);
// The first scan cleans the conservatively-set bitmap bits for never-occupied slots. This
// models incremental scans after the first eviction/restoration pass established sparsity.
for chunk in dense.chunks() {
for offset in chunk.probably_occupied_offsets() {
// TaskId zero is reserved; the all-true first bitmap contains it as a stale hint.
if !chunk.transient && chunk.base_id + offset == 0 {
continue;
}
drop(chunk.get(offset));
}
}
let mut sparse_iteration = c.benchmark_group("resident_storage_sparse_iteration");
sparse_iteration.throughput(Throughput::Elements(SPARSE_TASKS as u64));
sparse_iteration.bench_function("dash_map", |b| {
......@@ -687,7 +681,7 @@ pub fn resident_storage(c: &mut Criterion) {
sparse_iteration.bench_function("dense_bitmap", |b| {
b.iter(|| {
let mut sum = 0_u64;
for chunk in dense.chunks() {
for chunk in dense.pages(operation()) {
chunk.for_each_mut(|value| sum ^= value.value());
}
black_box(sum)
......
//! Dense, independently locked task storage.
//!
//! `boxcar::Vec` is an append-only directory of permanent chunk entries. Each entry uses Kovan to
//! publish and reclaim its large task chunk while retaining a stable location for later
//! replacement. Missing intermediate chunks cost one small empty directory entry, not `CHUNK_SIZE`
//! task slots.
//!
//! Kovan requires lock-free 128-bit atomics on its native x86-64/aarch64/s390x paths. In
//! particular, x86-64 CPUs must support `CMPXCHG16B`; Kovan runtime-detects this and panics during
//! global-state initialization when unavailable.
use std::{
cell::UnsafeCell,
marker::PhantomData,
ops::{Deref, DerefMut},
rc::Rc,
sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
};
use kovan::{AtomGuard, AtomOption};
use parking_lot::Mutex;
use turbo_tasks::{TRANSIENT_TASK_BIT, TaskId, parallel};
/// 128 slots balances GC scan work, sparse reclamation granularity, construction cost, and
/// concurrent metadata contention in the 64/128/256/1024 block-size matrix.
pub(crate) const CHUNK_SHIFT: usize = 7;
pub(crate) const CHUNK_SIZE: usize = 1 << CHUNK_SHIFT;
const CHUNK_MASK: usize = CHUNK_SIZE - 1;
const BITMAP_WORD_BITS: usize = u64::BITS as usize;
pub(crate) const BITMAP_WORDS: usize = CHUNK_SIZE / BITMAP_WORD_BITS;
const _: () = assert!(CHUNK_SIZE <= u8::MAX as usize);
/// Value stored in an always-initialized intrusive task slot.
///
/// This small abstraction lets the container's concurrency invariants be tested with a minimal
/// value and lets the benchmark compare the exact container using a representative 128-byte value.
/// Production has a single implementation for `TaskStorage`.
///
/// # Safety
///
/// Implementations must keep the lock at a stable address, initialize it in `EMPTY`, require the
/// lock for every payload/presence access, and leave the source lock untouched when vacating.
pub(crate) unsafe trait TaskSlotValue: Sized {
const EMPTY: Self;
/// Locks the intrusive mutex reached through a stable raw value pointer.
///
/// # Safety
/// `value` must point to a live, stably-addressed slot value.
unsafe fn lock_raw(value: *const Self);
/// Unlocks the mutex previously acquired through `lock_raw`.
///
/// # Safety
/// The current thread must own this value's intrusive mutex.
unsafe fn unlock_raw(value: *const Self);
fn is_occupied(&self) -> bool;
fn occupy(&mut self);
fn take_and_vacate(&mut self) -> Self;
fn vacate_in_place(&mut self);
}
/// Stable storage for a value whose mutex is embedded inside the value itself.
#[repr(transparent)]
pub(crate) struct TaskSlot<T: TaskSlotValue>(UnsafeCell<T>);
impl<T: TaskSlotValue> TaskSlot<T> {
pub(crate) const fn empty() -> Self {
Self(UnsafeCell::new(T::EMPTY))
}
fn lock(&self) -> TaskSlotGuard<'_, T> {
// SAFETY: The value is initialized by `empty` and never moved after its chunk is published.
unsafe { T::lock_raw(self.0.get()) };
TaskSlotGuard {
value: self.0.get(),
_lifetime: PhantomData,
_not_send: PhantomData,
}
}
fn as_ptr(&self) -> *mut T {
self.0.get()
}
}
// SAFETY: `TaskSlotValue` requires all shared payload access to be protected by its embedded lock.
// `T: Send` allows ownership of protected values to move between threads when detached.
unsafe impl<T: TaskSlotValue + Send> Sync for TaskSlot<T> {}
struct TaskSlotGuard<'a, T: TaskSlotValue> {
value: *mut T,
_lifetime: PhantomData<&'a TaskSlot<T>>,
_not_send: PhantomData<Rc<()>>,
}
impl<T: TaskSlotValue> Deref for TaskSlotGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// SAFETY: This guard owns the slot's intrusive lock.
unsafe { &*self.value }
}
}
impl<T: TaskSlotValue> DerefMut for TaskSlotGuard<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: This guard exclusively owns the slot's intrusive lock.
unsafe { &mut *self.value }
}
}
impl<T: TaskSlotValue> Drop for TaskSlotGuard<'_, T> {
fn drop(&mut self) {
// SAFETY: construction acquires this same value's lock and the guard is !Send.
unsafe { T::unlock_raw(self.value) };
}
}
pub(crate) struct TaskChunk<T: TaskSlotValue> {
// Each occupied task contributes at most one to either counter, so 128 slots fit in u8.
pub(crate) modified_count: AtomicU8,
occupied_count: AtomicU8,
probably_occupied: [AtomicU64; BITMAP_WORDS],
slots: Box<[TaskSlot<T>; CHUNK_SIZE]>,
}
impl<T: TaskSlotValue> TaskChunk<T> {
fn new() -> Self {
Self {
modified_count: AtomicU8::new(0),
occupied_count: AtomicU8::new(0),
// Start conservatively set so chunk construction and dense first insertion need no
// atomic read-modify-write per slot. The first scan locks/rechecks vacant slots and
// clears their stale hints; subsequent sparse scans skip them.
probably_occupied: [const { AtomicU64::new(u64::MAX) }; BITMAP_WORDS],
slots: Box::new([const { TaskSlot::empty() }; CHUNK_SIZE]),
}
}
fn word_and_mask(offset: usize) -> (usize, u64) {
(offset / BITMAP_WORD_BITS, 1 << (offset % BITMAP_WORD_BITS))
}
fn mark_probably_occupied(&self, offset: usize) {
let (word, mask) = Self::word_and_mask(offset);
self.probably_occupied[word].fetch_or(mask, Ordering::Release);
}
fn clear_probably_occupied(&self, offset: usize) {
let (word, mask) = Self::word_and_mask(offset);
self.probably_occupied[word].fetch_and(!mask, Ordering::Release);
}
pub(crate) fn is_probably_occupied(&self, offset: usize) -> bool {
let (word, mask) = Self::word_and_mask(offset);
self.probably_occupied[word].load(Ordering::Acquire) & mask != 0
}
fn lock(&self, offset: usize) -> TaskSlotGuard<'_, T> {
self.slots[offset].lock()
}
fn lock_raw(&self, offset: usize) -> *mut T {
let value = self.slots[offset].as_ptr();
// SAFETY: this chunk and all of its slot values have stable addresses while protected.
unsafe { T::lock_raw(value) };
value
}
pub(crate) fn probably_occupied_offsets(&self) -> ProbablyOccupiedOffsets<'_> {
ProbablyOccupiedOffsets {
words: &self.probably_occupied,
word_index: 0,
bits: 0,
}
}
}
pub(crate) struct ProbablyOccupiedOffsets<'a> {
words: &'a [AtomicU64; BITMAP_WORDS],
word_index: usize,
bits: u64,
}
impl Iterator for ProbablyOccupiedOffsets<'_> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
loop {
if self.bits != 0 {
let bit = self.bits.trailing_zeros() as usize;
self.bits &= self.bits - 1;
return Some((self.word_index - 1) * BITMAP_WORD_BITS + bit);
}
let word = self.words.get(self.word_index)?;
self.word_index += 1;
self.bits = word.load(Ordering::Acquire);
}
}
}
struct ChunkDirectoryEntry<T: TaskSlotValue + Send + 'static> {
chunk: AtomOption<TaskChunk<T>>,
transition: Mutex<()>,
retire_candidate: AtomicBool,
}
impl<T: TaskSlotValue + Send + 'static> ChunkDirectoryEntry<T> {
fn new() -> Self {
Self {
chunk: AtomOption::none(),
transition: Mutex::new(()),
retire_candidate: AtomicBool::new(false),
}
}
fn retire_if_empty(&self) -> bool {
// Keep the overwhelmingly-common non-candidate path read-only. The swap below claims a
// candidate that was already observed; a concurrent false→true transition after this load
// remains set for the next retirement pass.
if !self.retire_candidate.load(Ordering::Acquire)
|| !self.retire_candidate.swap(false, Ordering::AcqRel)
{
return false;
}
let _transition = self.transition.lock();
let Some(chunk) = self.chunk.load() else {
return false;
};
if chunk.occupied_count.load(Ordering::Acquire) != 0 {
return false;
}
// Transition exclusion prevents insertion from publishing into or replacing this chunk
// between the zero-count check and the unconditional detach.
self.chunk.store_none();
true
}
}
struct ChunkedVec<T: TaskSlotValue + Send + 'static> {
chunks: boxcar::Vec<ChunkDirectoryEntry<T>>,
}
impl<T: TaskSlotValue + Send + 'static> ChunkedVec<T> {
fn with_chunk_capacity(chunk_capacity: usize) -> Self {
Self {
chunks: boxcar::Vec::with_capacity(chunk_capacity),
}
}
fn entry(&self, index: usize) -> Option<&ChunkDirectoryEntry<T>> {
self.chunks.get(index >> CHUNK_SHIFT)
}
fn get_or_create_entry(&self, index: usize) -> &ChunkDirectoryEntry<T> {
let chunk_index = index >> CHUNK_SHIFT;
loop {
if let Some(entry) = self.chunks.get(chunk_index) {
return entry;
}
// `count` includes indices reserved by in-progress pushes. If our index has already
// been reserved, wait for it to become visible; otherwise help append permanent empty
// entries toward it. Only their Kovan-managed contents are ever reclaimed.
if self.chunks.count() <= chunk_index {
self.chunks.push(ChunkDirectoryEntry::new());
} else {
std::hint::spin_loop();
}
}
}
fn len(&self) -> usize {
let len = self
.entries()
.filter_map(|(_, entry)| entry.chunk.load())
.map(|chunk| chunk.occupied_count.load(Ordering::Relaxed) as usize)
.sum();
// Empty and nonempty AtomOption loads both pin this thread.
kovan::flush();
len
}
fn entries(&self) -> impl Iterator<Item = (usize, &ChunkDirectoryEntry<T>)> {
self.chunks.iter()
}
fn clear(&self) {
let entries: Vec<_> = self.entries().map(|(_, entry)| entry).collect();
parallel::for_each(&entries, |entry| {
if let Some(chunk) = entry.chunk.load() {
for offset in chunk.probably_occupied_offsets() {
let mut value = chunk.lock(offset);
if value.is_occupied() {
value.vacate_in_place();
}
chunk.clear_probably_occupied(offset);
}
chunk.modified_count.store(0, Ordering::Relaxed);
chunk.occupied_count.store(0, Ordering::Release);
entry.retire_candidate.store(true, Ordering::Release);
drop(chunk);
}
// `AtomOption::load`, including an empty load, pins this OS thread. Do not leave a
// parallel clear worker parked with a stale reservation.
kovan::flush();
});
self.retire_empty_chunks();
}
fn directory_entry_count(&self) -> usize {
self.chunks.count()
}
#[allow(dead_code)]
fn loaded_chunk_count(&self) -> usize {
self.entries()
.filter(|(_, entry)| entry.chunk.is_some())
.count()
}
fn retire_empty_chunks(&self) -> usize {
let retired = self
.entries()
.filter(|(_, entry)| entry.retire_if_empty())
.count();
if retired != 0 {
kovan::flush();
}
retired
}
}
pub(crate) struct TaskMap<T: TaskSlotValue + Send + 'static> {
persistent: ChunkedVec<T>,
transient: ChunkedVec<T>,
}
impl<T: TaskSlotValue + Send + 'static> TaskMap<T> {
pub(crate) fn new(small_preallocation: bool) -> Self {
let persistent_chunk_capacity = if small_preallocation {
1
} else {
(1024 * 1024) / CHUNK_SIZE
};
Self {
persistent: ChunkedVec::with_chunk_capacity(persistent_chunk_capacity),
transient: ChunkedVec::with_chunk_capacity(1),
}
}
fn namespace_and_index(&self, key: TaskId) -> (&ChunkedVec<T>, usize) {
let raw = *key as usize;
let index = raw & !(TRANSIENT_TASK_BIT as usize);
if key.is_transient() {
(&self.transient, index)
} else {
(&self.persistent, index)
}
}
pub(crate) fn get(&self, key: TaskId) -> Option<TaskMapGuard<'_, T>> {
let (namespace, index) = self.namespace_and_index(key);
let entry = namespace.entry(index)?;
let protection = entry.chunk.load()?;
let offset = index & CHUNK_MASK;
if !protection.is_probably_occupied(offset) {
return None;
}
TaskMapGuard::new_owned(key, protection, entry, offset, false)
}
pub(crate) fn get_or_insert(&self, key: TaskId) -> TaskMapGuard<'_, T> {
if let Some(task) = self.get(key) {
return task;
}
let (namespace, index) = self.namespace_and_index(key);
let entry = namespace.get_or_create_entry(index);
let offset = index & CHUNK_MASK;
loop {
let Some(protection) = entry.chunk.load() else {
// Publish only the empty chunk while holding transition exclusion. Never wait for
// a task lock under this mutex: callers may already own another task in the chunk.
let transition = entry.transition.lock();
if entry.chunk.is_none() {
entry.chunk.store_some(TaskChunk::new());
entry.retire_candidate.store(false, Ordering::Release);
}
drop(transition);
continue;
};
let chunk = &*protection as *const TaskChunk<T>;
// SAFETY: `protection` keeps the loaded raw chunk alive.
let value = unsafe { (&*chunk).lock_raw(offset) };
// SAFETY: this thread owns the value's intrusive lock.
if unsafe { &*value }.is_occupied() {
return TaskMapGuard::new_locked(key, value, Some(protection), entry, chunk);
}
// Lock order is task -> transition. Retirement never takes task locks, so this cannot
// cycle with callers that already hold another task in the same chunk.
let transition = entry.transition.lock();
let current = entry.chunk.load();
let still_current = current
.as_ref()
.is_some_and(|current| std::ptr::eq::<TaskChunk<T>>(&**current, &*protection));
if !still_current {
drop(current);
drop(transition);
// SAFETY: `lock_raw` acquired this same value's lock on this thread.
unsafe { T::unlock_raw(value) };
continue;
}
// Publish the hint before authoritative occupancy. A clear hint can therefore never
// hide a modified task from a racing bulk scan. The all-true initial bitmap makes this
// branch read-only for dense first insertion.
if !unsafe { &*chunk }.is_probably_occupied(offset) {
unsafe { &*chunk }.mark_probably_occupied(offset);
}
// SAFETY: this thread owns the value's intrusive lock.
unsafe { &mut *value }.occupy();
let previous = unsafe { &*chunk }
.occupied_count
.fetch_add(1, Ordering::Release);
debug_assert!(previous < CHUNK_SIZE as u8);
entry.retire_candidate.store(false, Ordering::Release);
drop(current);
let task = TaskMapGuard::new_locked(key, value, Some(protection), entry, chunk);
drop(transition);
return task;
}
}
pub(crate) fn len(&self) -> usize {
self.persistent.len() + self.transient.len()
}
pub(crate) fn clear(&self) {
self.persistent.clear();
self.transient.clear();
}
pub(crate) fn retire_empty_chunks(&self) -> usize {
self.persistent.retire_empty_chunks() + self.transient.retire_empty_chunks()
}
#[allow(dead_code)]
pub(crate) fn loaded_chunk_count(&self) -> usize {
self.persistent.loaded_chunk_count() + self.transient.loaded_chunk_count()
}
#[allow(dead_code)]
pub(crate) fn directory_entry_count(&self) -> usize {
self.persistent.directory_entry_count() + self.transient.directory_entry_count()
}
#[allow(dead_code)]
pub(crate) fn directory_entry_size() -> usize {
std::mem::size_of::<ChunkDirectoryEntry<T>>()
}
pub(crate) fn parallel_collect<R, C>(
&self,
f: impl Fn(TaskChunkRef<'_, T>) -> R + Send + Sync,
) -> C
where
R: Send + Sync,
C: FromIterator<R>,
{
parallel::map_collect_owned(self.chunks(), |chunk| {
let result = f(chunk);
// A clean snapshot may only load the per-chunk counter and return without constructing
// LoadedTaskChunk, so flush the worker reservation at the batch boundary as well.
kovan::flush();
result
})
}
pub(crate) fn chunks(&self) -> Vec<TaskChunkRef<'_, T>> {
self.persistent
.entries()
.map(|(index, entry)| TaskChunkRef {
base_id: index << CHUNK_SHIFT,
transient: false,
entry,
})
.chain(self.transient.entries().map(|(index, entry)| TaskChunkRef {
base_id: index << CHUNK_SHIFT,
transient: true,
entry,
}))
.collect()
}
pub(crate) fn persistent_chunks(&self) -> Vec<TaskChunkRef<'_, T>> {
self.persistent
.entries()
.map(|(index, entry)| TaskChunkRef {
base_id: index << CHUNK_SHIFT,
transient: false,
entry,
})
.collect()
}
}
pub(crate) struct TaskChunkRef<'a, T: TaskSlotValue + Send + 'static> {
pub(crate) base_id: usize,
pub(crate) transient: bool,
entry: &'a ChunkDirectoryEntry<T>,
}
impl<T: TaskSlotValue + Send + 'static> Copy for TaskChunkRef<'_, T> {}
impl<T: TaskSlotValue + Send + 'static> Clone for TaskChunkRef<'_, T> {
fn clone(&self) -> Self {
*self
}
}
impl<'a, T: TaskSlotValue + Send + 'static> TaskChunkRef<'a, T> {
fn load(&self) -> Option<LoadedTaskChunk<'a, T>> {
Some(LoadedTaskChunk {
owner: *self,
chunk: self.entry.chunk.load()?,
})
}
pub(crate) fn for_each_mut(&self, f: impl FnMut(TaskMapGuard<'_, T>)) {
if let Some(chunk) = self.load() {
chunk.for_each_mut(f);
} else {
// Loading an empty AtomOption still pins this OS thread. Do not leave scan workers
// parked with a stale reservation that delays physical reclamation.
kovan::flush();
}
}
#[allow(dead_code)]
pub(crate) fn for_each_all_mut(&self, f: impl FnMut(TaskMapGuard<'_, T>)) {
if let Some(chunk) = self.load() {
chunk.for_each_all_mut(f);
} else {
kovan::flush();
}
}
#[allow(dead_code)]
pub(crate) fn get(&self, offset: usize) -> Option<TaskMapGuard<'a, T>> {
let protection = self.entry.chunk.load()?;
if !protection.is_probably_occupied(offset) {
return None;
}
TaskMapGuard::new_owned(self.task_id(offset), protection, self.entry, offset, true)
}
pub(crate) fn take_modified_count(&self) -> Option<u8> {
Some(
self.entry
.chunk
.load()?
.modified_count
.swap(0, Ordering::Relaxed),
)
}
pub(crate) fn modified_count(&self) -> u8 {
self.entry
.chunk
.load()
.map_or(0, |chunk| chunk.modified_count.load(Ordering::Relaxed))
}
#[allow(dead_code)]
pub(crate) fn is_probably_occupied(&self, offset: usize) -> bool {
self.entry
.chunk
.load()
.is_some_and(|chunk| chunk.is_probably_occupied(offset))
}
#[allow(dead_code)]
pub(crate) fn probably_occupied_offsets(&self) -> Vec<usize> {
self.entry.chunk.load().map_or_else(Vec::new, |chunk| {
chunk.probably_occupied_offsets().collect()
})
}
pub(crate) fn task_id(&self, offset: usize) -> TaskId {
let mut raw = (self.base_id + offset) as u32;
if self.transient {
raw |= TRANSIENT_TASK_BIT;
}
TaskId::try_from(raw).expect("occupied task slots always have valid task IDs")
}
}
struct LoadedTaskChunk<'a, T: TaskSlotValue + Send + 'static> {
// Keep this guard alive while any borrowed per-task guard exists.
chunk: AtomGuard<'a, TaskChunk<T>>,
owner: TaskChunkRef<'a, T>,
}
impl<T: TaskSlotValue + Send + 'static> Drop for LoadedTaskChunk<'_, T> {
fn drop(&mut self) {
// Kovan reservations are thread-local and remain published after Guard drop. Flushing each
// scan worker keeps a large eviction/snapshot/GC pass from leaving its worker idle with a
// stale reservation. Physical reclamation remains eventual for unrelated idle workers.
kovan::flush();
}
}
impl<T: TaskSlotValue + Send + 'static> LoadedTaskChunk<'_, T> {
fn for_each_mut(&self, mut f: impl FnMut(TaskMapGuard<'_, T>)) {
for offset in self.chunk.probably_occupied_offsets() {
if let Some(task) = self.get(offset, true) {
f(task);
}
}
}
fn for_each_all_mut(&self, mut f: impl FnMut(TaskMapGuard<'_, T>)) {
for offset in 0..CHUNK_SIZE {
if let Some(task) = self.get(offset, false) {
f(task);
}
}
}
fn get(&self, offset: usize, check_hint: bool) -> Option<TaskMapGuard<'_, T>> {
if check_hint && !self.chunk.is_probably_occupied(offset) {
return None;
}
let value = self.chunk.lock_raw(offset);
// SAFETY: this thread owns the value's intrusive lock.
if !unsafe { &*value }.is_occupied() {
self.chunk.clear_probably_occupied(offset);
// SAFETY: `lock_raw` acquired this same value's lock on this thread.
unsafe { T::unlock_raw(value) };
return None;
}
Some(TaskMapGuard {
key: self.owner.task_id(offset),
value_ptr: value,
_protection: None,
modified_count: &self.chunk.modified_count,
occupied_count: &self.chunk.occupied_count,
entry: self.owner.entry,
_lifetime: PhantomData,
_not_send: PhantomData,
})
}
}
pub(crate) struct TaskMapGuard<'a, T: TaskSlotValue + Send + 'static> {
key: TaskId,
value_ptr: *mut T,
// Point access owns protection through unlock. Chunk scans borrow protection from their
// LoadedTaskChunk, represented by `_lifetime`, and finish each callback before it drops.
_protection: Option<AtomGuard<'a, TaskChunk<T>>>,
modified_count: *const AtomicU8,
occupied_count: *const AtomicU8,
entry: &'a ChunkDirectoryEntry<T>,
_lifetime: PhantomData<&'a TaskChunk<T>>,
_not_send: PhantomData<Rc<()>>,
}
impl<'a, T: TaskSlotValue + Send + 'static> TaskMapGuard<'a, T> {
fn new_owned(
key: TaskId,
protection: AtomGuard<'a, TaskChunk<T>>,
entry: &'a ChunkDirectoryEntry<T>,
offset: usize,
clear_stale_hint: bool,
) -> Option<Self> {
let chunk = &*protection as *const TaskChunk<T>;
// SAFETY: the AtomGuard keeps the raw chunk alive and is moved into the returned guard.
let value = unsafe { (&*chunk).lock_raw(offset) };
// SAFETY: this thread owns the value's intrusive lock.
if !unsafe { &*value }.is_occupied() {
if clear_stale_hint {
// Bulk scans converge stale-positive hints after taking the task lock.
unsafe { &*chunk }.clear_probably_occupied(offset);
}
// SAFETY: `lock_raw` acquired this same value's lock on this thread.
unsafe { T::unlock_raw(value) };
return None;
}
Some(Self::new_locked(key, value, Some(protection), entry, chunk))
}
fn new_locked(
key: TaskId,
value_ptr: *mut T,
protection: Option<AtomGuard<'a, TaskChunk<T>>>,
entry: &'a ChunkDirectoryEntry<T>,
chunk: *const TaskChunk<T>,
) -> Self {
Self {
key,
value_ptr,
_protection: protection,
// SAFETY: owned guards retain Kovan protection; borrowed scan guards cannot outlive
// their LoadedTaskChunk protection.
modified_count: unsafe { std::ptr::addr_of!((*chunk).modified_count) },
occupied_count: unsafe { std::ptr::addr_of!((*chunk).occupied_count) },
entry,
_lifetime: PhantomData,
_not_send: PhantomData,
}
}
pub(crate) fn key(&self) -> &TaskId {
&self.key
}
pub(crate) fn modified_count(&self) -> &AtomicU8 {
// SAFETY: owned point guards retain Kovan protection; borrowed scan guards cannot outlive
// their LoadedTaskChunk protection.
unsafe { &*self.modified_count }
}
pub(crate) fn modified_count_ptr(&self) -> *const AtomicU8 {
self.modified_count
}
fn finish_vacate(&self) {
// SAFETY: Kovan protection remains live through this handoff.
let previous = unsafe { &*self.occupied_count }.fetch_sub(1, Ordering::AcqRel);
debug_assert!(previous > 0);
if previous == 1 {
self.entry.retire_candidate.store(true, Ordering::Release);
}
}
pub(crate) fn take_and_vacate(self) -> T {
// SAFETY: this guard owns the value's intrusive lock.
let detached = unsafe { &mut *self.value_ptr }.take_and_vacate();
// Leave the advisory bit set. A later scan locks, observes authoritative vacancy, and
// clears it. Immediate ID reuse therefore needs no bitmap clear/set round trip.
self.finish_vacate();
detached
}
pub(crate) fn vacate(self) {
// SAFETY: this guard owns the value's intrusive lock.
unsafe { &mut *self.value_ptr }.vacate_in_place();
self.finish_vacate();
}
}
impl<T: TaskSlotValue + Send + 'static> Deref for TaskMapGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// SAFETY: this guard owns the value's intrusive lock.
unsafe { &*self.value_ptr }
}
}
impl<T: TaskSlotValue + Send + 'static> DerefMut for TaskMapGuard<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: this guard exclusively owns the value's intrusive lock.
unsafe { &mut *self.value_ptr }
}
}
impl<T: TaskSlotValue + Send + 'static> Drop for TaskMapGuard<'_, T> {
fn drop(&mut self) {
// SAFETY: construction acquired this value's lock and the guard is !Send. This runs before
// fields are dropped, so owned Kovan protection remains live through unlock.
unsafe { T::unlock_raw(self.value_ptr) };
}
}
#[cfg(test)]
mod tests {
use std::{
sync::{
Arc, Barrier,
atomic::{AtomicUsize, Ordering},
},
thread,
};
use parking_lot::{Mutex, lock_api::RawMutex as _};
use turbo_tasks::TRANSIENT_TASK_BIT;
use super::*;
struct TestValue {
lock: Mutex<()>,
occupied: bool,
value: usize,
}
impl TestValue {
fn set(&mut self, value: usize) {
self.value = value;
}
}
// SAFETY: The raw lock is always initialized, is never moved after publication, and all
// payload/presence access in TaskMap goes through its guard.
unsafe impl TaskSlotValue for TestValue {
const EMPTY: Self = Self {
lock: Mutex::new(()),
occupied: false,
value: 0,
};
unsafe fn lock_raw(value: *const Self) {
// SAFETY: the caller provides a live, stable TestValue pointer.
let lock = unsafe { &*std::ptr::addr_of!((*value).lock) };
unsafe { lock.raw() }.lock();
}
unsafe fn unlock_raw(value: *const Self) {
// SAFETY: the current thread owns the lock acquired from this value.
let lock = unsafe { &*std::ptr::addr_of!((*value).lock) };
let raw = unsafe { lock.raw() };
unsafe { raw.unlock() };
}
fn is_occupied(&self) -> bool {
self.occupied
}
fn occupy(&mut self) {
assert!(!self.occupied);
self.occupied = true;
}
fn take_and_vacate(&mut self) -> Self {
assert!(self.occupied);
let value = self.value;
self.value = 0;
self.occupied = false;
Self {
lock: Mutex::new(()),
occupied: false,
value,
}
}
fn vacate_in_place(&mut self) {
assert!(self.occupied);
self.value = 0;
self.occupied = false;
}
}
fn task_id(raw: u32) -> TaskId {
TaskId::try_from(raw).unwrap()
}
fn remove(map: &TaskMap<TestValue>, key: TaskId) -> Option<TestValue> {
map.get(key).map(TaskMapGuard::take_and_vacate)
}
fn remove_discard(map: &TaskMap<TestValue>, key: TaskId) -> bool {
let Some(task) = map.get(key) else {
return false;
};
task.vacate();
true
}
#[test]
#[cfg(target_pointer_width = "64")]
fn directory_entry_is_compact() {
assert_eq!(std::mem::size_of::<ChunkDirectoryEntry<TestValue>>(), 16);
}
#[test]
fn grows_across_chunk_boundaries_and_reuses_slots() {
let map = TaskMap::<TestValue>::new(true);
for raw in [
1,
CHUNK_SIZE as u32 - 1,
CHUNK_SIZE as u32,
CHUNK_SIZE as u32 + 1,
] {
map.get_or_insert(task_id(raw)).set(raw as usize);
}
assert_eq!(map.len(), 4);
assert_eq!(
map.get(task_id(CHUNK_SIZE as u32)).unwrap().value,
CHUNK_SIZE
);
assert_eq!(
remove(&map, task_id(CHUNK_SIZE as u32)).unwrap().value,
CHUNK_SIZE
);
assert!(map.get(task_id(CHUNK_SIZE as u32)).is_none());
map.get_or_insert(task_id(CHUNK_SIZE as u32)).set(7);
assert_eq!(map.get(task_id(CHUNK_SIZE as u32)).unwrap().value, 7);
}
#[tokio::test(flavor = "multi_thread")]
async fn clear_drops_all_namespaces_in_parallel() {
let map = TaskMap::<TestValue>::new(true);
for raw in [1, CHUNK_SIZE as u32 + 1, 7 | TRANSIENT_TASK_BIT] {
map.get_or_insert(task_id(raw)).set(raw as usize);
}
map.clear();
assert_eq!(map.len(), 0);
assert!(map.get(task_id(1)).is_none());
assert!(map.get(task_id(CHUNK_SIZE as u32 + 1)).is_none());
assert!(map.get(task_id(7 | TRANSIENT_TASK_BIT)).is_none());
}
#[test]
fn persistent_and_transient_namespaces_do_not_alias() {
let map = TaskMap::<TestValue>::new(true);
map.get_or_insert(task_id(7)).set(1);
map.get_or_insert(task_id(7 | TRANSIENT_TASK_BIT)).set(2);
assert_eq!(map.get(task_id(7)).unwrap().value, 1);
assert_eq!(map.get(task_id(7 | TRANSIENT_TASK_BIT)).unwrap().value, 2);
}
#[test]
fn concurrent_first_access_initializes_once() {
let map = Arc::new(TaskMap::<TestValue>::new(true));
let barrier = Arc::new(Barrier::new(9));
let initializations = Arc::new(AtomicUsize::new(0));
let threads: Vec<_> = (0..8)
.map(|_| {
let map = map.clone();
let barrier = barrier.clone();
let initializations = initializations.clone();
thread::spawn(move || {
barrier.wait();
let mut value = map.get_or_insert(task_id(1));
if value.value == 0 {
initializations.fetch_add(1, Ordering::Relaxed);
value.value = 42;
}
assert_eq!(value.value, 42);
})
})
.collect();
barrier.wait();
for thread in threads {
thread.join().unwrap();
}
assert_eq!(initializations.load(Ordering::Relaxed), 1);
assert_eq!(map.len(), 1);
}
#[test]
fn concurrent_growth_preserves_existing_entries() {
let map = Arc::new(TaskMap::<TestValue>::new(true));
map.get_or_insert(task_id(1)).set(1);
let barrier = Arc::new(Barrier::new(9));
let threads: Vec<_> = (0..8)
.map(|thread_index| {
let map = map.clone();
let barrier = barrier.clone();
thread::spawn(move || {
barrier.wait();
for chunk in 1..32 {
let raw = (chunk * CHUNK_SIZE + thread_index + 1) as u32;
map.get_or_insert(task_id(raw)).set(raw as usize);
assert_eq!(map.get(task_id(1)).unwrap().value, 1);
}
})
})
.collect();
barrier.wait();
for thread in threads {
thread.join().unwrap();
}
assert_eq!(map.len(), 1 + 8 * 31);
}
#[test]
fn stale_bitmap_bit_is_safely_rechecked() {
let map = TaskMap::<TestValue>::new(true);
let id = task_id(1);
map.get_or_insert(id);
let chunk = map.chunks()[0];
// Vacating deliberately leaves the advisory bit set to avoid remove/reinsert churn.
assert!(remove_discard(&map, id));
assert!(chunk.is_probably_occupied(1));
assert!(map.get(id).is_none());
assert!(
chunk.is_probably_occupied(1),
"point misses leave hint cleanup to bulk scans"
);
assert!(chunk.get(1).is_none());
assert!(!chunk.is_probably_occupied(1));
}
#[test]
fn empty_chunk_is_detached_and_republished() {
let map = TaskMap::<TestValue>::new(true);
let id = task_id(1);
map.get_or_insert(id).set(1);
assert_eq!(map.loaded_chunk_count(), 1);
assert!(remove_discard(&map, id));
assert_eq!(map.retire_empty_chunks(), 1);
assert_eq!(map.loaded_chunk_count(), 0);
map.get_or_insert(id).set(2);
assert_eq!(map.loaded_chunk_count(), 1);
assert_eq!(map.get(id).unwrap().value, 2);
}
#[test]
fn protected_stale_chunk_survives_detach_until_guard_drops() {
let map = TaskMap::<TestValue>::new(true);
let id = task_id(1);
map.get_or_insert(id).set(1);
let entry = map.persistent.entry(1).unwrap();
let protection = entry.chunk.load().unwrap();
let chunk = &*protection as *const TaskChunk<TestValue>;
assert!(remove_discard(&map, id));
assert_eq!(map.retire_empty_chunks(), 1);
assert_eq!(map.loaded_chunk_count(), 0);
// SAFETY: the protection guard was acquired before detach and still pins the old chunk.
let stale = unsafe { (&*chunk).lock(1) };
assert!(!stale.is_occupied());
drop(stale);
drop(protection);
}
#[test]
fn insertion_racing_empty_chunk_retirement_preserves_a_valid_slot() {
let map = Arc::new(TaskMap::<TestValue>::new(true));
let id = task_id(1);
for round in 1..=500 {
map.get_or_insert(id).set(round);
let barrier = Arc::new(Barrier::new(3));
thread::scope(|scope| {
let remove_map = map.clone();
let remove_barrier = barrier.clone();
scope.spawn(move || {
remove_barrier.wait();
if remove_discard(&remove_map, id) {
remove_map.retire_empty_chunks();
}
});
let insert_map = map.clone();
let insert_barrier = barrier.clone();
scope.spawn(move || {
insert_barrier.wait();
insert_map.get_or_insert(id).set(round + 1);
});
barrier.wait();
});
assert!(map.len() <= 1);
if let Some(task) = map.get(id) {
assert_eq!(task.value, round + 1);
} else {
assert_eq!(map.len(), 0);
}
}
}
#[test]
fn occupied_chunk_is_not_retired_from_a_stale_candidate() {
let map = TaskMap::<TestValue>::new(true);
let id = task_id(1);
let task = map.get_or_insert(id);
let entry = map.persistent.entry(1).unwrap();
entry.retire_candidate.store(true, Ordering::Release);
assert_eq!(map.retire_empty_chunks(), 0);
assert_eq!(map.loaded_chunk_count(), 1);
drop(task);
}
#[tokio::test(flavor = "multi_thread")]
async fn parallel_collect_visits_dense_and_sparse_entries_once() {
let map = TaskMap::<TestValue>::new(true);
let ids = [1, 2, CHUNK_SIZE as u32 + 3, (CHUNK_SIZE * 4) as u32 + 5];
for raw in ids {
map.get_or_insert(task_id(raw)).set(raw as usize);
}
let groups: Vec<Vec<u32>> = map.parallel_collect(|chunk| {
let mut seen = Vec::new();
chunk.for_each_mut(|mut task| {
task.value ^= 0;
seen.push(**task.key());
});
seen
});
let mut seen: Vec<_> = groups.into_iter().flatten().collect();
seen.sort_unstable();
assert_eq!(seen, ids);
}
}
......@@ -64,9 +64,8 @@ pub enum TtlCounter {
/// 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),
/// Scan one live pointer page in either TaskId space.
ScanShard((bool, usize)),
/// Collect a single task.
Collect(TaskId),
}
......@@ -240,9 +239,12 @@ impl TurboTasksBackend {
None
};
let access = phase.access_token();
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())
// Scan live pages from both ID spaces, as well as aged-out durable roots.
self.storage
.shard_indices(access)
.into_iter()
.map(GcJob::ScanShard)
.chain(aged_out.into_iter().map(GcJob::Collect)),
Default::default,
......@@ -256,7 +258,7 @@ impl TurboTasksBackend {
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);
self.storage.gc_scan_shard(access, index, collector);
return ControlFlow::Continue(());
}
GcJob::Collect(task_id) => task_id,
......@@ -347,7 +349,7 @@ impl TurboTasksBackend {
// We don't do this in the GC pass because a task detected as a root 'early' might become a
// non-root later due to other operations (e.g. it might get promoted to a live aggregation
// root).
for id in self.storage.gc_scan_roots() {
for id in self.storage.gc_scan_roots(access) {
roots.insert(id, TtlCounter::MostRecent);
}
......
mod cell_data;
mod counter_map;
mod dense_task_map;
mod eviction;
mod gc;
mod operation;
mod snapshot_coordinator;
mod storage;
pub mod storage_schema;
mod task_page_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).
......@@ -374,9 +374,6 @@ impl TurboTasksBackend {
/// shutdown has begun, and blocks shutdown for as long as the returned context is alive.
///
/// Use this for entry points reachable from threads that `stop_and_wait` does **not** drain.
///
/// Returns `None` once [`TurboTasksBackend::stopping`] has run, in which case the caller must
/// do nothing: storage teardown is imminent or already underway.
fn try_execute_context<'a>(
&'a self,
turbo_tasks: &'a TurboTasks<TurboTasksBackend>,
......@@ -392,11 +389,8 @@ impl TurboTasksBackend {
))
}
pub(crate) fn start_operation(&self) -> Option<OperationGuard<'_, AnyOperation>> {
if !self.should_persist() {
return None;
}
Some(self.snapshot_coord.begin_operation())
pub(crate) fn start_operation(&self) -> OperationGuard<'_, AnyOperation> {
self.snapshot_coord.begin_operation()
}
fn should_persist(&self) -> bool {
......@@ -429,7 +423,7 @@ impl TurboTasksBackend {
return TestSnapshotOutcome::default();
}
};
let eviction_counts = self.storage.evict_after_snapshot(None);
let eviction_counts = self.storage.evict_after_snapshot(&self.snapshot_coord, None);
TestSnapshotOutcome {
had_new_data,
eviction_counts,
......@@ -440,23 +434,30 @@ impl TurboTasksBackend {
/// The number oftasks resident in the map.
#[doc(hidden)]
pub fn resident_task_count_for_testing(&self) -> usize {
self.storage.resident_task_count_for_testing()
let operation = self.start_operation();
self.storage
.resident_task_count_for_testing(operation.access_token())
}
}
/// The persistent `parent_count` of a resident task (0 if absent or not resident). Test-only
/// hook for verifying incremental refcount maintenance.
#[doc(hidden)]
pub fn parent_count_for_testing(&self, task: TaskId) -> u32 {
let operation = self.start_operation();
self.storage
.with_task(task, |t| t.gc_parent_count())
.with_task(operation.access_token(), task, |t| t.gc_parent_count())
.unwrap_or(0)
}
/// The transient `transient_ref_count` of a resident task (0 if absent or not resident).
#[doc(hidden)]
pub fn transient_ref_count_for_testing(&self, task: TaskId) -> u32 {
let operation = self.start_operation();
self.storage
.with_task(task, |t| t.gc_transient_ref_count())
.with_task(operation.access_token(), task, |t| {
t.gc_transient_ref_count()
})
.unwrap_or(0)
}
......@@ -1165,7 +1166,7 @@ impl TurboTasksBackend {
// since epoch). Instant is monotonic but has no defined epoch, so it
// can't be used for cross-process trace correlation.
let wall_start = SystemTime::now();
let mut snapshot_phase = self.snapshot_coord.begin_snapshot();
let mut snapshot_phase = self.snapshot_coord.begin_exclusion();
let (gc_elapsed, gc_roots_to_persist, gc_outcome) = if self.gc_enabled {
let gc_span = tracing::info_span!(
"gc",
......@@ -1192,12 +1193,15 @@ impl TurboTasksBackend {
debug_assert!(self.should_persist());
// Checking after start_snapshot ensures no concurrent increments can race.
let (snapshot_guard, has_modifications) = self.storage.start_snapshot();
let (snapshot_guard, has_modifications) = self
.storage
.start_snapshot(&self.snapshot_coord, snapshot_phase.access_token());
let suspended_operations = snapshot_phase.take_suspended_operations();
let snapshot_time = Instant::now();
drop(snapshot_phase);
snapshot_guard.begin_concurrent_phase();
if !has_modifications && gc_roots_to_persist.is_none() {
// No tasks modified since the last snapshot — drop the guard (which
......@@ -1681,7 +1685,9 @@ impl TurboTasksBackend {
{
eprintln!("Persisting failed during shutdown: {err:?}");
}
self.storage.drop_contents();
let clear_phase = self.snapshot_coord.begin_exclusion();
self.storage.drop_contents(clear_phase.access_token());
drop(clear_phase);
if let Err(err) = self.backing_storage.shutdown() {
println!("Shutting down failed: {err}");
}
......@@ -1836,8 +1842,11 @@ impl TurboTasksBackend {
// Initialize storage BEFORE making task_id visible in the cache.
// This ensures any thread that reads task_id from the cache sees
// the storage entry already initialized (restored flags set).
self.storage
.initialize_new_task(task_id, Some(task_type.clone()));
self.storage.initialize_new_task(
ctx.storage_access_token(),
task_id,
Some(task_type.clone()),
);
entry.insert((task_type, task_id));
(task_id, true)
}
......@@ -1939,7 +1948,8 @@ impl TurboTasksBackend {
}
fn debug_get_task_description(&self, task_id: TaskId) -> String {
let task = self.storage.access_mut(task_id);
let operation = self.start_operation();
let task = self.storage.access_mut(operation.access_token(), task_id);
if let Some(value) = task.get_persistent_task_type() {
format!("{task_id:?} {}", value)
} else if let Some(value) = task.get_transient_task_type() {
......@@ -1968,7 +1978,8 @@ impl TurboTasksBackend {
}
fn debug_get_cached_task_type(&self, task_id: TaskId) -> Option<CachedTaskTypeArc> {
let task = self.storage.access_mut(task_id);
let operation = self.start_operation();
let task = self.storage.access_mut(operation.access_token(), task_id);
task.get_persistent_task_type().cloned()
}
......@@ -3159,7 +3170,10 @@ impl TurboTasksBackend {
// when enabled we should expect it to reclaim substantial
// memory so racing with execution is as likely to save time as
// cost it.
self.storage.evict_after_snapshot(background_span.id());
self.storage.evict_after_snapshot(
&self.snapshot_coord,
background_span.id(),
);
true
} else {
false
......@@ -3416,7 +3430,8 @@ impl TurboTasksBackend {
fn create_transient_task(&self, task_type: TransientTaskType) -> TaskId {
let task_id = self.transient_task_id_factory.get();
{
let mut task = self.storage.access_mut(task_id);
let operation = self.start_operation();
let mut task = self.storage.access_mut(operation.access_token(), task_id);
task.init_transient_task(task_id, task_type, self.should_track_activeness());
}
#[cfg(feature = "verify_aggregation_graph")]
......
......@@ -35,6 +35,7 @@ use crate::{
snapshot_coordinator::{OperationGuard, SnapshotPhase},
storage::{SpecificTaskDataCategory, StorageWriteGuard, TaskEntryGuard, TrackOutcome},
storage_schema::{TaskStorage, TaskStorageAccessors},
task_page_map::StorageAccessToken,
},
data::{ActivenessState, CollectibleRef, Dirtyness, InProgressState, TransientTask},
};
......@@ -214,6 +215,8 @@ pub trait ExecuteContext<'e>: Sized {
arg: &dyn DynTaskInputs,
) -> Option<(TaskId, CachedTaskTypeArc)>;
fn debug_get_task_description(&self, task_id: TaskId) -> String;
/// Proof that this context is covered by an operation admission or exclusion phase.
fn storage_access_token(&self) -> StorageAccessToken<'_>;
}
pub trait ChildExecuteContext<'e>: Send + Sized {
......@@ -272,12 +275,55 @@ impl TaskLockCounter {
}
}
#[derive(Clone, Copy)]
enum EpochOwner<'e> {
Operation(&'e OperationGuard<'e, AnyOperation>),
Exclusion(&'e SnapshotPhase<'e, AnyOperation>),
}
impl<'e> EpochOwner<'e> {
fn access_token(self) -> StorageAccessToken<'e> {
match self {
Self::Operation(guard) => guard.access_token(),
Self::Exclusion(phase) => phase.access_token(),
}
}
}
enum ExecutePhase<'e> {
Normal {
guard: Option<OperationGuard<'e, AnyOperation>>,
access: StorageAccessToken<'e>,
},
Child {
owner: EpochOwner<'e>,
access: StorageAccessToken<'e>,
},
Gc {
collector: &'e (dyn Fn(TaskId) + Send + Sync),
phase: &'e SnapshotPhase<'e, AnyOperation>,
access: StorageAccessToken<'e>,
},
Child,
Gc(&'e (dyn Fn(TaskId) + Send + Sync)),
}
impl<'e> ExecutePhase<'e> {
fn access_token(&self) -> StorageAccessToken<'e> {
match self {
Self::Normal { access, .. }
| Self::Child { access, .. }
| Self::Gc { access, .. } => *access,
}
}
fn child_owner(&self) -> EpochOwner<'_> {
match self {
Self::Normal { guard, .. } => EpochOwner::Operation(
guard.as_ref().expect("normal context retains its operation admission"),
),
Self::Child { owner, .. } => *owner,
Self::Gc { phase, .. } => EpochOwner::Exclusion(phase),
}
}
}
pub struct ExecuteContextImpl<'e> {
......@@ -295,11 +341,14 @@ impl<'e> ExecuteContextImpl<'e> {
backend: &'e TurboTasksBackend,
turbo_tasks: &'e TurboTasks<TurboTasksBackend>,
) -> Self {
let guard = backend.start_operation();
let access = guard.access_token();
Self {
backend,
turbo_tasks,
phase: ExecutePhase::Normal {
guard: backend.start_operation(),
guard: Some(guard),
access,
},
_shutdown_guard: None,
task_lock_counter: TaskLockCounter::new(),
......@@ -314,11 +363,14 @@ impl<'e> ExecuteContextImpl<'e> {
turbo_tasks: &'e TurboTasks<TurboTasksBackend>,
shutdown_guard: RwLockReadGuard<'e, bool>,
) -> Self {
let guard = backend.start_operation();
let access = guard.access_token();
Self {
backend,
turbo_tasks,
phase: ExecutePhase::Normal {
guard: backend.start_operation(),
guard: Some(guard),
access,
},
_shutdown_guard: Some(shutdown_guard),
task_lock_counter: TaskLockCounter::new(),
......@@ -340,7 +392,11 @@ impl<'e> ExecuteContextImpl<'e> {
Self {
backend,
turbo_tasks,
phase: ExecutePhase::Gc(gc_collectible),
phase: ExecutePhase::Gc {
collector: gc_collectible,
phase: _phase,
access: _phase.access_token(),
},
_shutdown_guard: None,
task_lock_counter: TaskLockCounter::new(),
}
......@@ -354,7 +410,7 @@ impl<'e> ExecuteContextImpl<'e> {
) -> Option<TaskGuardImpl<'_>> {
self.task_lock_counter.acquire();
let mut task = OpenedTask::Owned(self.backend.storage.access_entry_mut(task_id));
let mut task = OpenedTask::Owned(self.backend.storage.access_entry_mut(self.phase.access_token(), task_id));
// Treat deleted tasks under Allowmissing as missing
if access == TaskAccess::AllowMissing && task.flags.deleted() {
self.task_lock_counter.release();
......@@ -439,7 +495,7 @@ impl<'e> ExecuteContextImpl<'e> {
task = if let Some(cat) = wait_category(data_restoring, meta_restoring) {
OpenedTask::Restored(self.wait_for_restore_or_panic(task_id, cat))
} else {
OpenedTask::Owned(self.backend.storage.access_entry_mut(task_id))
OpenedTask::Owned(self.backend.storage.access_entry_mut(self.phase.access_token(), task_id))
};
if waiting_for_restore {
// This caller owns the pin and releases it only after acquiring the task
......@@ -590,7 +646,7 @@ impl<'e> ExecuteContextImpl<'e> {
// Fast path: the restoring thread usually finishes its I/O before this waiter gets here.
// Avoid registering a listener when the requested category is already available.
{
let task = self.backend.storage.access_mut(task_id);
let task = self.backend.storage.access_mut(self.phase.access_token(), task_id);
if task.flags.is_restored(category) {
return Ok(task);
}
......@@ -600,7 +656,7 @@ impl<'e> ExecuteContextImpl<'e> {
// Register before taking the task lock to avoid a lost wakeup when another restorer is
// still active. It is harmless when this thread becomes the replacement restorer.
let listener = self.backend.storage.restored.listen();
let mut task = self.backend.storage.access_mut(task_id);
let mut task = self.backend.storage.access_mut(self.phase.access_token(), task_id);
if task.flags.is_restored(category) {
return Ok(task);
......@@ -631,7 +687,7 @@ impl<'e> ExecuteContextImpl<'e> {
let storage_meta = restore_meta
.then(|| self.restore_task_data(task_id, SpecificTaskDataCategory::Meta));
let mut task = self.backend.storage.access_mut(task_id);
let mut task = self.backend.storage.access_mut(self.phase.access_token(), task_id);
let mut restore_error = None;
if let Some(result) = storage_data
&& let Err(error) =
......@@ -706,7 +762,7 @@ impl<'e> ExecuteContextImpl<'e> {
if !self.backend.should_restore() {
for (task_id, category) in task_ids {
self.task_lock_counter.acquire();
let task = self.backend.storage.access_mut(task_id);
let task = self.backend.storage.access_mut(self.phase.access_token(), task_id);
debug_assert!(
task.flags.is_restored(category),
"task {task_id} should already be marked restored when there is no backing \
......@@ -730,7 +786,7 @@ impl<'e> ExecuteContextImpl<'e> {
// Transient tasks have restored flags set at allocation time,
// so they never need DB restoration.
if call_prepared_task_callback_for_transient_tasks {
let task = self.backend.storage.access_mut(id);
let task = self.backend.storage.access_mut(self.phase.access_token(), id);
debug_assert!(
task.flags.is_restored(category),
"transient task {id} should already be marked restored"
......@@ -774,7 +830,7 @@ impl<'e> ExecuteContextImpl<'e> {
let task_id = entry.task_id;
let category = entry.category;
self.task_lock_counter.acquire();
let mut task = self.backend.storage.access_mut(task_id);
let mut task = self.backend.storage.access_mut(self.phase.access_token(), task_id);
let mut ready = true;
if category.includes_data() && !task.flags.data_restored() {
......@@ -908,7 +964,7 @@ impl<'e> ExecuteContextImpl<'e> {
let task_id = entry.task_id;
self.task_lock_counter.acquire();
let mut task = self.backend.storage.access_mut(task_id);
let mut task = self.backend.storage.access_mut(self.phase.access_token(), task_id);
if let Some(result) = entry.data_restore_result.take() {
match apply_restore_result(&mut task, result, SpecificTaskDataCategory::Data) {
......@@ -949,7 +1005,7 @@ impl<'e> ExecuteContextImpl<'e> {
if entry.transient_ref_pinned {
self.backend
.storage
.access_mut(entry.task_id)
.access_mut(self.phase.access_token(), entry.task_id)
.update_and_get_transient_ref_count(-1);
}
}
......@@ -1104,9 +1160,12 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
where
'e: 'l,
{
let owner = self.phase.child_owner();
ChildExecuteContextImpl {
backend: self.backend,
turbo_tasks: self.turbo_tasks,
access: owner.access_token(),
owner,
}
}
......@@ -1177,7 +1236,7 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
) -> (Self::TaskGuardImpl<'_>, Self::TaskGuardImpl<'_>) {
self.task_lock_counter.acquire_multiple(2);
let (mut task1, mut task2) = self.backend.storage.access_pair_mut(task_id1, task_id2);
let (mut task1, mut task2) = self.backend.storage.access_pair_mut(self.phase.access_token(), task_id1, task_id2);
// `task_pair` is always a `MustExist` open (both endpoints of an existing edge). Existence
// check mirroring `open_task` (persistent tasks only — a transient task materializes lazily
......@@ -1278,7 +1337,7 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
drop(self.wait_for_restore_or_panic(task_id2, cat));
}
let (t1, t2) = self.backend.storage.access_pair_mut(task_id1, task_id2);
let (t1, t2) = self.backend.storage.access_pair_mut(self.phase.access_token(), task_id1, task_id2);
task1 = t1;
task2 = t2;
if waiting1 {
......@@ -1378,14 +1437,14 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
}
fn operation_suspend_point<T: Clone + Into<AnyOperation>>(&mut self, op: &T) {
let ExecutePhase::Normal { guard: Some(guard) } = &mut self.phase else {
let ExecutePhase::Normal { guard: Some(guard), .. } = &mut self.phase else {
return;
};
guard.suspend_point(|| op.clone().into());
}
fn note_maybe_collectible(&self, task: &impl TaskGuard) {
if let ExecutePhase::Gc(collector) = self.phase
if let ExecutePhase::Gc { collector, .. } = self.phase
&& task.is_gc_collectible()
{
collector(task.id());
......@@ -1436,11 +1495,17 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
fn debug_get_task_description(&self, task_id: TaskId) -> String {
self.backend.debug_get_task_description(task_id)
}
fn storage_access_token(&self) -> StorageAccessToken<'_> {
self.phase.access_token()
}
}
struct ChildExecuteContextImpl<'e> {
backend: &'e TurboTasksBackend,
turbo_tasks: &'e TurboTasks<TurboTasksBackend>,
access: StorageAccessToken<'e>,
owner: EpochOwner<'e>,
}
impl<'e> ChildExecuteContext<'e> for ChildExecuteContextImpl<'e> {
......@@ -1448,7 +1513,10 @@ impl<'e> ChildExecuteContext<'e> for ChildExecuteContextImpl<'e> {
ExecuteContextImpl {
backend: self.backend,
turbo_tasks: self.turbo_tasks,
phase: ExecutePhase::Child,
phase: ExecutePhase::Child {
owner: self.owner,
access: self.access,
},
// A child context runs inside its parent's execution, which the foreground drain
// already waits for, so it needs no shutdown guard of its own.
_shutdown_guard: None,
......@@ -2149,7 +2217,7 @@ mod filter_transient_tracking_tests {
counter: &'a TaskLockCounter,
task_id: TaskId,
) -> TaskGuardImpl<'a> {
let mut write = storage.access_mut(task_id);
let mut write = storage.access_mut(StorageAccessToken::operation(), task_id);
write.flags.set_restored(TaskDataCategory::All);
counter.acquire();
TaskGuardImpl {
......@@ -2424,7 +2492,7 @@ mod cell_data_tracking_tests {
counter: &'a TaskLockCounter,
task_id: TaskId,
) -> TaskGuardImpl<'a> {
let mut write = storage.access_mut(task_id);
let mut write = storage.access_mut(StorageAccessToken::operation(), task_id);
write.flags.set_restored(TaskDataCategory::All);
counter.acquire();
TaskGuardImpl {
......
......@@ -25,7 +25,10 @@ use parking_lot::{Condvar, Mutex};
use rustc_hash::FxHashSet;
use tracing::info_span;
use crate::{backend::AnyOperation, utils::ptr_eq_arc::PtrEqArc};
use crate::{
backend::{AnyOperation, task_page_map::StorageAccessToken},
utils::ptr_eq_arc::PtrEqArc,
};
/// High bit: set while a snapshot is requested or in flight.
/// Low bits: count of operations currently executing (not suspended).
......@@ -200,7 +203,11 @@ pub struct OperationGuard<'a, O> {
coord: &'a SnapshotCoordinator<O>,
}
impl<O> OperationGuard<'_, O> {
impl<'a, O> OperationGuard<'a, O> {
pub(crate) fn access_token(&self) -> StorageAccessToken<'a> {
StorageAccessToken::operation()
}
/// Suspend this operation if a snapshot is requested. Otherwise a no-op. The closure is called
/// only when actually suspending and must produce a handle to this operation so the
/// snapshotter can persist it for replay on the next startup.
......@@ -287,7 +294,11 @@ pub struct SnapshotPhase<'a, O> {
suspended_operations: Vec<Arc<O>>,
}
impl<O> SnapshotPhase<'_, O> {
impl<'a, O> SnapshotPhase<'a, O> {
pub(crate) fn access_token(&self) -> StorageAccessToken<'a> {
StorageAccessToken::exclusive()
}
/// Operations that were suspended at the moment the snapshot started.
/// The snapshotter must persist these so they can be replayed on the
/// next startup.
......
......@@ -4,9 +4,10 @@ use std::{
hash::BuildHasher,
ops::{Deref, DerefMut},
sync::{
Arc,
Arc, OnceLock,
atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering},
},
time::Instant,
};
use thread_local::ThreadLocal;
......@@ -16,10 +17,12 @@ use turbo_tasks::{FxDashMap, TaskId, backend::CachedTaskTypeArc, event::Event, p
use crate::{
backend::{
dense_task_map::{CHUNK_SIZE, TaskMap, TaskMapGuard},
AnyOperation,
snapshot_coordinator::{OperationGuard, SnapshotCoordinator},
storage_schema::{
DropPartialOutcome, KeyEvictability, TaskStorage, UnevictableReason, ValueEvictability,
},
task_page_map::{PAGE_SIZE, StorageAccessToken, TaskMap, TaskMapGuard},
},
backing_storage::SnapshotItem,
database::key_value_database::KeySpace,
......@@ -238,15 +241,20 @@ impl Storage {
}
if !already_modified && promoted {
let previous = modified_count.fetch_add(1, Ordering::Relaxed);
debug_assert!(previous < CHUNK_SIZE as u8);
debug_assert!(previous < PAGE_SIZE as u8);
}
}
/// 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`.
pub fn initialize_new_task(&self, task_id: TaskId, task_type: Option<CachedTaskTypeArc>) {
let mut task = self.access_mut(task_id);
pub fn initialize_new_task(
&self,
access: StorageAccessToken<'_>,
task_id: TaskId,
task_type: Option<CachedTaskTypeArc>,
) {
let mut task = self.access_mut(access, task_id);
task.flags.set_restored(TaskDataCategory::All);
task.flags.set_new_task(true);
task.gc_pin_for_construction();
......@@ -283,13 +291,30 @@ impl Storage {
P: for<'a> Fn(TaskId, &'a TaskStorage, &mut TurboBincodeBuffer) -> SnapshotItem + Sync,
>(
&'l self,
guard: SnapshotGuard<'l>,
mut guard: SnapshotGuard<'l>,
process: &'l P,
drain_entries: bool,
) -> Vec<SnapshotShard<'l, P>> {
let exclusive_phase = if drain_entries {
// Release the concurrent snapshot admission before requesting deletion exclusion.
guard.operation.take();
let phase = guard.coordinator.begin_exclusion();
Some(phase)
} else {
if guard.operation.get().is_none() {
// Unit-level callers may enter take_snapshot directly; production arms the guard
// immediately after releasing the initial exclusion phase.
guard.begin_concurrent_phase();
}
None
};
let access = exclusive_phase
.as_ref()
.map_or_else(|| guard.access_token(), |phase| phase.access_token());
let guard = Arc::new(guard);
let shards: Vec<Option<SnapshotShard<'l, P>>> = self.map.parallel_collect(|chunk| {
let shards: Vec<Option<SnapshotShard<'l, P>>> =
self.map.parallel_collect(access, |chunk| {
// Once snapshot mode is active, new writes use the during-snapshot flags and do not
// increment this counter. Each chunk can therefore be claimed independently.
let modified_count = chunk.take_modified_count().unwrap_or(0);
......@@ -340,6 +365,13 @@ impl Storage {
_guard: guard.clone(),
})
});
if drain_entries {
self.map.reclaim_empty_pages(access);
}
drop(exclusive_phase);
if drain_entries {
guard.begin_concurrent_phase();
}
shards.into_iter().flatten().collect()
}
......@@ -352,17 +384,24 @@ impl Storage {
/// 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) {
pub fn start_snapshot<'a>(
&'a self,
coordinator: &'a SnapshotCoordinator<AnyOperation>,
access: StorageAccessToken<'a>,
) -> (SnapshotGuard<'a>, bool) {
// Enter snapshot mode first so concurrent track_modification calls switch
// to the _during_snapshot path and stop incrementing per-chunk counts.
self.snapshot_mode.store(true, Ordering::SeqCst);
// Don't reset counts here: take_snapshot claims them chunk by chunk.
let has_modifications = self
.map
.chunks()
.pages(access)
.iter()
.any(|chunk| chunk.modified_count() > 0);
(SnapshotGuard::new(self), has_modifications)
(
SnapshotGuard::new(self, coordinator, access),
has_modifications,
)
}
/// End snapshot mode.
......@@ -375,7 +414,7 @@ impl Storage {
/// 1. Leave snapshot mode so new modifications go to the modified flags directly.
/// 2. Promote `modified_during_snapshot` → `modified` for tasks that were accessed during
/// snapshot mode (tracked in the small `snapshots` map).
fn end_snapshot(&self) {
fn end_snapshot(&self, access: StorageAccessToken<'_>) {
// 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::SeqCst);
......@@ -402,16 +441,12 @@ impl Storage {
});
let pending: Vec<TaskId> = pending.into_iter().flatten().collect();
parallel::for_each(&pending, |&key| {
if let Some(mut task) = self.map.get(key) {
if let Some(mut task) = self.map.get(key, access) {
let modified_count = task.modified_count_ptr();
// SAFETY: `task` holds a guard that keeps its chunk alive through this call.
self.promote_during_snapshot_flags(&mut task, unsafe { &*modified_count });
}
});
// Shutdown drain may have vacated every slot. All snapshot iterators and their task guards
// are gone before the shared SnapshotGuard calls this method.
self.map.retire_empty_chunks();
}
/// Returns true if actively snapshotting (modifications should go to snapshots map).
......@@ -420,87 +455,104 @@ impl Storage {
self.snapshot_mode.load(Ordering::SeqCst)
}
pub fn access_mut(&self, key: TaskId) -> StorageWriteGuard<'_> {
pub fn access_mut<'a>(
&'a self,
access: StorageAccessToken<'a>,
key: TaskId,
) -> StorageWriteGuard<'a> {
let inner = self
.map
.get(key)
.unwrap_or_else(|| self.map.get_or_insert(key));
.get(key, access)
.unwrap_or_else(|| self.map.get_or_insert(key, access));
StorageWriteGuard {
storage: self,
inner,
}
}
/// A locked entry that can be vacated while the guard is still held.
pub fn access_entry_mut(&self, key: TaskId) -> TaskEntryGuard<'_> {
/// A locked entry that can be removed without reopening its slot.
pub fn access_entry_mut<'a>(
&'a self,
access: StorageAccessToken<'a>,
key: TaskId,
) -> TaskEntryGuard<'a> {
TaskEntryGuard {
inner: self.access_mut(key),
inner: self.access_mut(access, key),
}
}
/// Read-only access to an already resident task. The closure runs under the task lock, so
/// it must be cheap and must not re-enter the same task.
pub fn with_task<R>(&self, key: TaskId, f: impl FnOnce(&TaskStorage) -> R) -> Option<R> {
let task = self.map.get(key)?;
/// Read-only access to an already resident task. The callback must not re-enter this task.
pub fn with_task<R>(
&self,
access: StorageAccessToken<'_>,
key: TaskId,
f: impl FnOnce(&TaskStorage) -> R,
) -> Option<R> {
let task = self.map.get(key, access)?;
Some(f(&task))
}
/// The number of tasks resident in the map.
#[doc(hidden)]
pub fn resident_task_count_for_testing(&self) -> usize {
self.map.len()
pub fn resident_task_count_for_testing(&self, access: StorageAccessToken<'_>) -> usize {
self.map.len(access)
}
/// The number of directory chunks for both persistent and transient tasks.
pub fn shard_count(&self) -> usize {
self.map.chunks().len()
/// Live pointer-page indices in both ID spaces; only live pages become GC jobs.
pub fn shard_indices(&self, access: StorageAccessToken<'_>) -> Vec<(bool, usize)> {
self.map.page_indices(access)
}
/// Scan one resident chunk and enqueue candidates using the authoritative GC predicate.
pub fn gc_scan_shard(&self, index: usize, mut on_candidate: impl FnMut(TaskId)) {
let chunks = self.map.chunks();
chunks[index].for_each_mut(|task| {
pub fn gc_scan_shard(
&self,
access: StorageAccessToken<'_>,
(transient, index): (bool, usize),
mut on_candidate: impl FnMut(TaskId),
) {
let Some(page) = self.map.page(index, transient, access) else {
return;
};
page.for_each_mut(|task| {
if task.gc_collectible() {
on_candidate(*task.key());
}
});
}
/// Return the set of all known live roots.
pub fn gc_scan_roots(&self) -> impl Iterator<Item = TaskId> {
let per_chunk: Vec<Vec<TaskId>> =
parallel::map_collect(&self.map.chunks(), |chunk| {
/// Return the set of persistent live roots.
pub fn gc_scan_roots(&self, access: StorageAccessToken<'_>) -> impl Iterator<Item = TaskId> {
let per_page: Vec<Vec<TaskId>> = self.map.parallel_collect(access, |page| {
let mut roots = Vec::new();
chunk.for_each_mut(|task| {
page.for_each_mut(|task| {
if !task.key().is_transient() && task.gc_is_root() {
roots.push(*task.key());
}
});
roots
});
per_chunk.into_iter().flatten()
per_page.into_iter().flatten()
}
pub fn access_pair_mut(
&self,
pub fn access_pair_mut<'a>(
&'a self,
access: StorageAccessToken<'a>,
key1: TaskId,
key2: TaskId,
) -> (StorageWriteGuard<'_>, StorageWriteGuard<'_>) {
) -> (StorageWriteGuard<'a>, StorageWriteGuard<'a>) {
assert_ne!(key1, key2, "cannot mutably access the same task twice");
if key1 < key2 {
let value1 = self.access_mut(key1);
let value2 = self.access_mut(key2);
let value1 = self.access_mut(access, key1);
let value2 = self.access_mut(access, key2);
(value1, value2)
} else {
let value2 = self.access_mut(key2);
let value1 = self.access_mut(key1);
let value2 = self.access_mut(access, key2);
let value1 = self.access_mut(access, key1);
(value1, value2)
}
}
pub fn drop_contents(&self) {
self.map.clear();
pub fn drop_contents(&self, access: StorageAccessToken<'_>) {
self.map.clear(access);
drop_contents(&self.snapshots);
}
......@@ -520,12 +572,35 @@ impl Storage {
/// - `No`: skip
///
/// Must be called when NOT in snapshot mode (i.e., after `end_snapshot()`).
pub fn evict_after_snapshot(&self, parent_span: Option<Id>) -> EvictionCounts {
///
/// The expensive scan races normal execution under operation admission. Only final pointer
/// removal runs under a short coordinator exclusion, where candidates are rechecked.
pub fn evict_after_snapshot(
&self,
coordinator: &SnapshotCoordinator<AnyOperation>,
parent_span: Option<Id>,
) -> EvictionCounts {
self.evict_after_snapshot_with_hook(coordinator, parent_span, || {})
}
fn evict_after_snapshot_with_hook(
&self,
coordinator: &SnapshotCoordinator<AnyOperation>,
parent_span: Option<Id>,
before_exclusion: impl FnOnce(),
) -> EvictionCounts {
let candidate_operation = coordinator.begin_operation();
let candidate_access = candidate_operation.access_token();
let span = tracing::trace_span!(
parent: parent_span,
"evict_after_snapshot",
total_task_cache_keys = self.task_cache.len(),
total_map_keys = self.map.len(),
total_map_keys = self.map.len(candidate_access),
candidate_count = tracing::field::Empty,
removed_count = tracing::field::Empty,
reclaimed_pages = tracing::field::Empty,
exclusion_wait = tracing::field::Empty,
exclusion_hold = tracing::field::Empty,
counts = tracing::field::Empty,
)
.entered();
......@@ -534,13 +609,13 @@ impl Storage {
"evict_after_snapshot must not be called during snapshot mode"
);
let counts: Vec<EvictionCounts> = self.map.parallel_collect(|chunk| {
let scan_results: Vec<(EvictionCounts, Vec<TaskId>)> =
self.map.parallel_collect(candidate_access, |chunk| {
let mut evicted = EvictionCounts::default();
let mut candidates = Vec::new();
// Removals that would invert task_cache -> task lock ordering are deferred until no
// task lock is held.
let mut deferred_task_cache_removals: Vec<CachedTaskTypeArc> = Vec::new();
// Remove a task type from `task_cache`, deferring on contention until no task lock is
// held. Shared by the GC-deleted and ordinary key-eviction paths.
let remove_from_task_cache =
|evicted: &mut EvictionCounts,
deferred: &mut Vec<CachedTaskTypeArc>,
......@@ -557,8 +632,8 @@ impl Storage {
evicted.unevictable_reasons[UnevictableReason::Transient.index()] += 1;
return;
}
// All GC'd tasks were tombstoned during the snapshot (or are not persisted) so we
// can drop them fully now.
// Tombstoned tasks can be removed under exclusion, including transient tasks
// which have no inverse persistent cache entry.
if task.flags.deleted() {
if let Some(task_type) = task.get_persistent_task_type() {
remove_from_task_cache(
......@@ -567,8 +642,7 @@ impl Storage {
task_type,
);
}
evicted.full += 1;
task.vacate();
candidates.push(task_id);
return;
}
let (key_evictability, value_evictability) = task.evictability();
......@@ -586,10 +660,7 @@ impl Storage {
match value_evictability {
ValueEvictability::Evictable { meta, data } => {
match task.drop_partial(data, meta) {
DropPartialOutcome::Empty => {
evicted.full += 1;
task.vacate();
}
DropPartialOutcome::Empty => candidates.push(task_id),
DropPartialOutcome::HasResidue => {
if data && meta {
evicted.data_and_meta += 1;
......@@ -612,16 +683,50 @@ impl Storage {
evicted.key_evictions += 1;
}
}
evicted
(evicted, candidates)
});
// All parallel task guards are gone; detach and flush chunks whose last slot was vacated.
self.map.retire_empty_chunks();
let mut totals = EvictionCounts::default();
for evicted in counts {
let mut candidates = Vec::new();
for (evicted, mut chunk_candidates) in scan_results {
totals += evicted;
candidates.append(&mut chunk_candidates);
}
span.record("candidate_count", candidates.len());
drop(candidate_operation);
before_exclusion();
let wait_start = Instant::now();
let exclusion = coordinator.begin_exclusion();
let exclusion_wait = wait_start.elapsed();
let hold_start = Instant::now();
let access = exclusion.access_token();
let mut removed = 0usize;
for task_id in candidates {
let Some(task) = self.map.get(task_id, access) else {
continue;
};
// Execution may have restored or modified this task after the candidate scan. Only the
// GC tombstone or an actually empty payload remains removable after quiescence.
if !task.flags.deleted() && !task.is_empty() {
continue;
}
if let Some(task_type) = task.get_persistent_task_type()
&& self.task_cache.remove(task_type.as_ref()).is_some()
{
totals.key_evictions += 1;
}
task.vacate();
totals.full += 1;
removed += 1;
}
let reclaimed_pages = self.map.reclaim_empty_pages(access);
let exclusion_hold = hold_start.elapsed();
drop(exclusion);
span.record("removed_count", removed);
span.record("reclaimed_pages", reclaimed_pages);
span.record("exclusion_wait", tracing::field::debug(exclusion_wait));
span.record("exclusion_hold", tracing::field::debug(exclusion_hold));
// 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
......@@ -742,7 +847,7 @@ impl StorageWriteGuard<'_> {
let bumped = !flags.any_modified();
if bumped {
let previous = self.inner.modified_count().fetch_add(1, Ordering::Relaxed);
debug_assert!(previous < CHUNK_SIZE as u8);
debug_assert!(previous < PAGE_SIZE as u8);
}
self.inner.flags.set_modified(category, true);
TrackOutcome::Tracked { category, bumped }
......@@ -891,6 +996,12 @@ enum ScratchBufferSlot {
pub struct SnapshotGuard<'l> {
storage: &'l Storage,
coordinator: &'l SnapshotCoordinator<AnyOperation>,
initial_access: StorageAccessToken<'l>,
/// Keeps resident pointers alive while normal snapshot shards perform deferred lookups. A
/// OnceLock allows shutdown drain to arm admission after its parallel exclusive scan has
/// already cloned the shared SnapshotGuard into shard iterators.
operation: OnceLock<OperationGuard<'l, AnyOperation>>,
/// Per-thread scratch buffers for encoding task data. Buffers are taken
/// by `SnapshotShardIter` on creation and returned on drop, allowing reuse
/// across multiple shards processed by the same thread. When the guard is
......@@ -900,13 +1011,32 @@ pub struct SnapshotGuard<'l> {
}
impl<'l> SnapshotGuard<'l> {
fn new(storage: &'l Storage) -> Self {
fn new(
storage: &'l Storage,
coordinator: &'l SnapshotCoordinator<AnyOperation>,
access: StorageAccessToken<'l>,
) -> Self {
Self {
storage,
coordinator,
initial_access: access,
operation: OnceLock::new(),
scratch_buffers: ThreadLocal::new(),
}
}
pub(crate) fn begin_concurrent_phase(&self) {
self.operation
.set(self.coordinator.begin_operation())
.unwrap_or_else(|_| panic!("snapshot guard operation admission was already armed"));
}
fn access_token(&self) -> StorageAccessToken<'l> {
self.operation
.get()
.map_or(self.initial_access, OperationGuard::access_token)
}
fn take_scratch_buffer(&self) -> TurboBincodeBuffer {
let cell = self.scratch_buffers.get_or_default();
match cell.take() {
......@@ -940,7 +1070,10 @@ impl<'l> SnapshotGuard<'l> {
impl Drop for SnapshotGuard<'_> {
fn drop(&mut self) {
self.storage.end_snapshot();
// The production caller transitions this guard to an operation admission immediately after
// releasing its initial exclusion. If unwinding happens before that handoff, the original
// exclusion phase still outlives us and `access` remains valid.
self.storage.end_snapshot(self.access_token());
}
}
......@@ -1015,7 +1148,8 @@ where
match &mut self.shard.work {
ShardWork::Keep(modified) => {
let task_id = modified.pop()?;
let mut inner = self.shard.storage.map.get(task_id).unwrap();
let access = self.shard._guard.access_token();
let mut inner = self.shard.storage.map.get(task_id, access).unwrap();
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
......@@ -1061,14 +1195,102 @@ mod tests {
use turbo_bincode::TurboBincodeBuffer;
use turbo_tasks::TaskId;
use super::{SpecificTaskDataCategory, Storage, TrackOutcome};
use crate::backing_storage::SnapshotItem;
use super::{SpecificTaskDataCategory, Storage, TaskDataCategory, TrackOutcome};
use crate::{
backend::{
AnyOperation, snapshot_coordinator::SnapshotCoordinator,
task_page_map::StorageAccessToken,
},
backing_storage::SnapshotItem,
};
fn access() -> StorageAccessToken<'static> {
StorageAccessToken::operation()
}
fn coordinator() -> &'static SnapshotCoordinator<AnyOperation> {
Box::leak(Box::new(SnapshotCoordinator::new()))
}
fn non_transient_task(id: u32) -> TaskId {
// TRANSIENT_TASK_BIT is 0x4000_0000; any id without that bit is non-transient.
TaskId::new(id).expect("id must be non-zero")
}
#[tokio::test(flavor = "multi_thread")]
async fn eviction_rechecks_candidate_after_concurrent_restore() {
let storage = Storage::new(2, true);
let coordinator = SnapshotCoordinator::<AnyOperation>::new();
let task_id = non_transient_task(1);
{
let operation = coordinator.begin_operation();
let mut task = storage.access_mut(operation.access_token(), task_id);
task.flags.set_restored(TaskDataCategory::All);
}
let counts = storage.evict_after_snapshot_with_hook(&coordinator, None, || {
let operation = coordinator.begin_operation();
let mut task = storage.access_mut(operation.access_token(), task_id);
task.set_output(crate::data::OutputValue::Output(task_id));
task.flags.set_meta_restored(true);
task.flags.set_meta_modified(true);
});
assert_eq!(counts.full, 0, "re-modified candidate must remain resident");
let operation = coordinator.begin_operation();
let task = storage.map.get(task_id, operation.access_token()).unwrap();
assert_eq!(
task.get_output(),
Some(&crate::data::OutputValue::Output(task_id))
);
}
#[test]
fn exclusive_removal_waits_for_admitted_task_guard() {
let storage = Arc::new(Storage::new(2, true));
let coordinator = Arc::new(SnapshotCoordinator::<AnyOperation>::new());
let task_id = non_transient_task(1);
{
let operation = coordinator.begin_operation();
storage.access_mut(operation.access_token(), task_id);
}
let (holding_tx, holding_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let reader_storage = Arc::clone(&storage);
let reader_coordinator = Arc::clone(&coordinator);
let reader = thread::spawn(move || {
let operation = reader_coordinator.begin_operation();
let task = reader_storage.access_mut(operation.access_token(), task_id);
holding_tx.send(()).unwrap();
release_rx.recv().unwrap();
drop(task);
drop(operation);
});
holding_rx.recv().unwrap();
let (removed_tx, removed_rx) = mpsc::channel();
let remover_storage = Arc::clone(&storage);
let remover_coordinator = Arc::clone(&coordinator);
let remover = thread::spawn(move || {
let phase = remover_coordinator.begin_exclusion();
remover_storage
.map
.get(task_id, phase.access_token())
.unwrap()
.vacate();
remover_storage
.map
.reclaim_empty_pages(phase.access_token());
removed_tx.send(()).unwrap();
});
assert!(removed_rx.recv_timeout(Duration::from_millis(50)).is_err());
release_tx.send(()).unwrap();
removed_rx.recv_timeout(Duration::from_secs(5)).unwrap();
reader.join().unwrap();
remover.join().unwrap();
assert_eq!(storage.map.loaded_page_count(), 0);
}
#[test]
fn new_task_is_pinned_during_construction() {
let storage = Storage::new(2, true);
......@@ -1090,7 +1312,7 @@ mod tests {
let barrier = barrier.clone();
let done_tx = done_tx.clone();
thread::spawn(move || {
let _guard = storage.access_mut(non_transient_task(id));
let _guard = storage.access_mut(access(), non_transient_task(id));
barrier.wait();
done_tx.send(()).unwrap();
});
......@@ -1112,8 +1334,11 @@ mod tests {
thread::spawn(move || {
barrier.wait();
for _ in 0..10_000 {
let guards = storage
.access_pair_mut(non_transient_task(first), non_transient_task(second));
let guards = storage.access_pair_mut(
access(),
non_transient_task(first),
non_transient_task(second),
);
drop(guards);
}
done_tx.send(()).unwrap();
......@@ -1143,20 +1368,21 @@ mod tests {
async fn task_first_modified_during_snapshot_is_carried_forward() {
let storage = Storage::new(2, true);
let task_id = non_transient_task(1);
let (snapshot_guard, has_modifications) = storage.start_snapshot();
let (snapshot_guard, has_modifications) = storage.start_snapshot(coordinator(), access());
assert!(!has_modifications);
{
let mut task = storage.access_mut(task_id);
let mut task = storage.access_mut(access(), task_id);
let _ = task.track_modification(SpecificTaskDataCategory::Data, "test");
assert!(task.flags.data_modified_during_snapshot());
assert!(!task.flags.data_modified());
}
drop(snapshot_guard);
let (_next_snapshot_guard, has_modifications) = storage.start_snapshot();
let (_next_snapshot_guard, has_modifications) =
storage.start_snapshot(coordinator(), access());
assert!(has_modifications);
let task = storage.access_mut(task_id);
let task = storage.access_mut(access(), task_id);
assert!(task.flags.data_modified());
assert!(!task.flags.data_modified_during_snapshot());
}
......@@ -1187,12 +1413,12 @@ mod tests {
// Step 1: modify the task outside snapshot mode (data_modified = true).
{
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
}
// Step 2: enter snapshot mode.
let (snapshot_guard, has_modifications) = storage.start_snapshot();
let (snapshot_guard, has_modifications) = storage.start_snapshot(coordinator(), access());
assert!(has_modifications);
// Step 3: `take_snapshot` scans the chunk. At this point the task has
......@@ -1205,7 +1431,7 @@ mod tests {
// modified → `(true, true)` branch: creates a snapshot copy (carrying the
// modified bits) and sets `data_modified_during_snapshot=true`.
{
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
// We should have set a snapshot bit
assert!(guard.flags.data_modified_during_snapshot())
......@@ -1224,14 +1450,14 @@ mod tests {
assert_eq!(items[0].task_id(), task_id);
{
let guard = storage.access_mut(task_id);
let guard = storage.access_mut(access(), task_id);
// The iterator should have promoted modified_during_snapshot → modified.
assert!(guard.flags.data_modified());
}
// The during-snapshot modification must be reflected in per-chunk modified counts so
// the next snapshot cycle picks it up. Verify by starting another snapshot.
let (_guard2, has_modifications) = storage.start_snapshot();
let (_guard2, has_modifications) = storage.start_snapshot(coordinator(), access());
assert!(
has_modifications,
"per-chunk modified counts must be non-zero after promoting modified_during_snapshot"
......@@ -1259,14 +1485,14 @@ mod tests {
// Step 1: modify meta only, outside snapshot mode.
{
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
assert!(guard.flags.meta_modified());
assert!(!guard.flags.data_modified());
}
// Step 2: enter snapshot mode.
let (snapshot_guard, has_modifications) = storage.start_snapshot();
let (snapshot_guard, has_modifications) = storage.start_snapshot(coordinator(), access());
assert!(has_modifications);
// Step 3: take_snapshot — task goes into modified list (meta_modified = true).
......@@ -1275,7 +1501,7 @@ mod tests {
// Step 4: modify data during snapshot. The `(true, false)` branch fires:
// data was not previously modified, so snapshots gets a None entry.
{
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
assert!(guard.flags.data_modified_during_snapshot());
assert!(!guard.flags.meta_modified_during_snapshot());
......@@ -1291,7 +1517,7 @@ mod tests {
assert_eq!(items[0].task_id(), task_id);
{
let guard = storage.access_mut(task_id);
let guard = storage.access_mut(access(), task_id);
// meta_modified was cleared by the iterator (it was the pre-snapshot flag).
assert!(!guard.flags.meta_modified());
// data_modified_during_snapshot was promoted to data_modified.
......@@ -1300,7 +1526,7 @@ mod tests {
}
// Next snapshot cycle must pick up the promoted data_modified.
let (_guard2, has_modifications) = storage.start_snapshot();
let (_guard2, has_modifications) = storage.start_snapshot(coordinator(), access());
assert!(
has_modifications,
"per-chunk modified counts must be non-zero after promoting \
......@@ -1319,12 +1545,12 @@ mod tests {
// Modify the task outside snapshot mode so it lands in the modified list.
{
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
}
assert!(storage.map.get(task_id).is_some());
assert!(storage.map.get(task_id, access()).is_some());
let (snapshot_guard, has_modifications) = storage.start_snapshot();
let (snapshot_guard, has_modifications) = storage.start_snapshot(coordinator(), access());
assert!(has_modifications);
// Take the snapshot in drain mode.
......@@ -1341,24 +1567,24 @@ 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.get(task_id, access()).is_none(),
"task entry should be removed from the map after being persisted in drain mode"
);
}
/// In drain mode, fully consuming the iterators empties every occupied slot. Chunk allocations
/// remain stable until `Storage` itself is dropped, but no `TaskStorage` value is retained.
/// In drain mode, the exclusive scan detaches every task box and then reclaims empty pointer
/// pages before returning the owned modified values for serialization.
#[tokio::test(flavor = "multi_thread")]
async fn drain_entries_clears_dense_slots() {
async fn drain_entries_reclaims_pointer_pages() {
let storage = Storage::new(2, true);
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 mut guard = storage.access_mut(access(), task_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
}
assert_eq!(storage.map.len(), task_ids.len());
assert_eq!(storage.map.len(access()), task_ids.len());
let (snapshot_guard, has_modifications) = storage.start_snapshot();
let (snapshot_guard, has_modifications) = storage.start_snapshot(coordinator(), access());
assert!(has_modifications);
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, true);
let items: Vec<_> = shards
......@@ -1366,13 +1592,8 @@ mod tests {
.flat_map(|shard| shard.into_iter())
.collect();
assert_eq!(items.len(), task_ids.len());
assert_eq!(storage.map.len(), 0);
for chunk in storage.map.chunks() {
for offset in chunk.probably_occupied_offsets() {
assert!(chunk.get(offset).is_none());
}
assert!(chunk.probably_occupied_offsets().is_empty());
}
assert_eq!(storage.map.len(access()), 0);
assert_eq!(storage.map.loaded_page_count(), 0);
}
/// In drain mode, `take_snapshot`'s scan removes *both* kinds of entry from the map: unmodified
......@@ -1389,14 +1610,14 @@ mod tests {
// One modified task (gets serialized) and one unmodified task (e.g. restored from disk but
// never dirtied) that just occupies memory and must not be serialized.
{
let mut guard = storage.access_mut(modified_id);
let mut guard = storage.access_mut(access(), modified_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
}
// `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());
let _ = storage.access_mut(access(), unmodified_id);
assert!(storage.map.get(unmodified_id, access()).is_some());
let (snapshot_guard, has_modifications) = storage.start_snapshot();
let (snapshot_guard, has_modifications) = storage.start_snapshot(coordinator(), access());
assert!(has_modifications);
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, true);
......@@ -1404,11 +1625,11 @@ mod tests {
// 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.
assert!(
storage.map.get(unmodified_id).is_none(),
storage.map.get(unmodified_id, access()).is_none(),
"unmodified entry should be removed during take_snapshot in drain mode"
);
assert!(
storage.map.get(modified_id).is_none(),
storage.map.get(modified_id, access()).is_none(),
"modified entry should be moved out of the map during take_snapshot in drain mode"
);
......@@ -1428,7 +1649,7 @@ mod tests {
let task_id = non_transient_task(1);
{
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
let outcome = guard.track_modification(SpecificTaskDataCategory::Data, "test");
assert!(guard.flags.data_modified());
guard.undo_track_modification(outcome);
......@@ -1437,7 +1658,7 @@ mod tests {
}
// Counter is back to zero: the next snapshot sees no modifications.
let (_guard, has_modifications) = storage.start_snapshot();
let (_guard, has_modifications) = storage.start_snapshot(coordinator(), access());
assert!(
!has_modifications,
"undo must decrement the chunk counter so no modifications remain"
......@@ -1451,7 +1672,7 @@ mod tests {
let storage = Storage::new(2, true);
let task_id = non_transient_task(1);
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
// First track is the real modification.
let _first = guard.track_modification(SpecificTaskDataCategory::Data, "test");
// Second track on the same category changes nothing.
......@@ -1473,7 +1694,7 @@ mod tests {
let task_id = non_transient_task(1);
{
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
let _data = guard.track_modification(SpecificTaskDataCategory::Data, "test");
let meta = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
assert!(guard.flags.meta_modified());
......@@ -1483,7 +1704,7 @@ mod tests {
}
// Data is still modified, so the counter is still non-zero.
let (_guard, has_modifications) = storage.start_snapshot();
let (_guard, has_modifications) = storage.start_snapshot(coordinator(), access());
assert!(has_modifications);
}
......@@ -1495,11 +1716,11 @@ mod tests {
let storage = Storage::new(2, true);
let task_id = non_transient_task(1);
// Insert the task (unmodified) so it exists in the map.
let _ = storage.access_mut(task_id);
let _ = storage.access_mut(access(), task_id);
let (_snapshot_guard, _) = storage.start_snapshot();
let (_snapshot_guard, _) = storage.start_snapshot(coordinator(), access());
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
let outcome = guard.track_modification(SpecificTaskDataCategory::Data, "test");
assert!(matches!(
outcome,
......@@ -1530,13 +1751,13 @@ mod tests {
// Modify before snapshot so the category is part of the snapshot.
{
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
}
let (_snapshot_guard, _) = storage.start_snapshot();
let (_snapshot_guard, _) = storage.start_snapshot(coordinator(), access());
let mut guard = storage.access_mut(task_id);
let mut guard = storage.access_mut(access(), task_id);
let outcome = guard.track_modification(SpecificTaskDataCategory::Data, "test");
assert!(matches!(
outcome,
......
......@@ -33,7 +33,7 @@ use turbo_tasks::{
};
use crate::{
backend::{cell_data::CellData, counter_map::CounterMap, dense_task_map::TaskSlotValue},
backend::{cell_data::CellData, counter_map::CounterMap, task_page_map::TaskSlotValue},
data::{
ActivenessState, AggregationNumber, CellRef, CollectibleRef, CollectiblesRef, Dirtyness,
InProgressCellState, InProgressState, LeafDistance, OutputValue, RootType, TransientTask,
......@@ -48,7 +48,7 @@ type AutoSet<K, const I: usize> = auto_hash_map::AutoSet<K, BuildHasherDefault<F
/// See [`AutoSet`] for the meaning of `I`.
type AutoMap<K, V, const I: usize> = auto_hash_map::AutoMap<K, V, BuildHasherDefault<FxHasher>, I>;
/// Intrusive parking_lot lock embedded in each always-initialized task slot.
/// Intrusive parking_lot lock embedded in each stable task allocation.
///
/// The newtype supplies the generated `Debug`, `Default`, and `ShrinkToFit` requirements while
/// retaining parking_lot's standard RAII guard and one-byte mutex layout.
......@@ -603,10 +603,13 @@ pub enum KeyEvictability {
Unevictable,
}
// SAFETY: `TaskStorage::empty_slot` always initializes the mutex. Dense chunks pin every slot
// after publication, and `take_and_vacate` moves only payload fields while preserving that mutex.
// SAFETY: `TaskStorage::new` initializes the mutex. Resident values remain at stable boxed
// addresses from release publication until an exclusive storage epoch detaches them.
unsafe impl TaskSlotValue for TaskStorage {
const EMPTY: Self = Self::empty_slot();
fn new() -> Self {
TaskStorage::new()
}
unsafe fn lock_raw(value: *const Self) {
// SAFETY: TaskSlotValue guarantees a live, stably-addressed TaskStorage.
unsafe { IntrusiveTaskLock::lock_raw(std::ptr::addr_of!((*value).lock)) };
......@@ -616,36 +619,11 @@ unsafe impl TaskSlotValue for TaskStorage {
// SAFETY: TaskSlotGuard owns the lock acquired through the same raw value pointer.
unsafe { IntrusiveTaskLock::unlock_raw(std::ptr::addr_of!((*value).lock)) };
}
fn is_occupied(&self) -> bool {
self.is_occupied()
}
fn occupy(&mut self) {
self.occupy();
}
fn take_and_vacate(&mut self) -> Self {
self.take_and_vacate()
}
fn vacate_in_place(&mut self) {
self.vacate_in_place();
}
}
impl TaskStorage {
pub(crate) fn is_occupied(&self) -> bool {
self.occupied
}
pub(crate) fn occupy(&mut self) {
debug_assert!(!self.occupied);
self.occupied = true;
}
/// Canonical const representation of a vacant, always-initialized dense task slot.
pub const fn empty_slot() -> Self {
/// Canonical const representation of a fresh boxed task payload.
pub const fn empty_task() -> Self {
Self {
leaf_distance: LeafDistance {
distance: 0,
......@@ -665,7 +643,6 @@ impl TaskStorage {
flags: TaskFlags::empty(),
lazy: TinyVec::new(),
lock: IntrusiveTaskLock::new(),
occupied: false,
}
}
......@@ -1224,13 +1201,16 @@ impl<K: IsTransient + Hash + Eq, V: IsTransient, const I: usize> DropPartial for
mod tests {
// Only used by the 64-bit schema-size assertions.
#[cfg(target_pointer_width = "64")]
use std::{mem::size_of, sync::atomic::AtomicU64};
use std::{
mem::size_of,
sync::atomic::{AtomicPtr, AtomicU64},
};
use turbo_tasks::{CellId, TaskId};
use super::*;
use crate::{
backend::dense_task_map::{BITMAP_WORDS, CHUNK_SIZE, TaskChunk, TaskSlot},
backend::task_page_map::{BITMAP_WORDS, PAGE_SIZE, TaskMap},
data::{AggregationNumber, CellRef, Dirtyness, OutputValue},
};
......@@ -1974,11 +1954,7 @@ mod tests {
#[test]
fn const_new_slots_have_independent_unlocked_mutexes() {
let empty_task = const { TaskStorage::new() };
let slots = [const { TaskStorage::new() }; 2];
assert!(!empty_task.is_occupied());
assert!(!slots[0].is_occupied());
assert!(!slots[1].is_occupied());
assert!(!slots[0].lock.is_locked());
assert!(!slots[1].lock.is_locked());
let guard = slots[0].lock.lock();
......@@ -1987,41 +1963,10 @@ mod tests {
drop(guard);
}
#[test]
fn vacate_preserves_lock_and_resets_payload() {
let mut task = TaskStorage::empty_slot();
let lock_address = std::ptr::addr_of!(task.lock);
let detached = with_task_locked(&mut task, |task| {
task.occupy();
task.set_output(OutputValue::Output(TaskId::new(1).unwrap()));
task.take_and_vacate()
});
assert_eq!(std::ptr::addr_of!(task.lock), lock_address);
assert!(!task.lock.is_locked());
assert!(!task.is_occupied());
assert_eq!(task.get_output(), None);
assert_eq!(
detached.get_output(),
Some(&OutputValue::Output(TaskId::new(1).unwrap()))
);
assert!(!detached.lock.is_locked());
assert!(!detached.is_occupied());
with_task_locked(&mut task, |task| {
task.occupy();
task.set_output(OutputValue::Output(TaskId::new(2).unwrap()));
assert!(task.is_occupied());
task.vacate_in_place();
assert!(task.lock.is_locked());
assert!(!task.is_occupied());
assert_eq!(task.get_output(), None);
});
}
#[test]
fn snapshot_clone_has_fresh_synchronization_state() {
let mut task = TaskStorage::empty_slot();
let mut task = TaskStorage::empty_task();
let snapshot = with_task_locked(&mut task, |task| {
task.occupy();
task.set_output(OutputValue::Output(TaskId::new(1).unwrap()));
let snapshot = task.clone_snapshot();
assert!(task.lock.is_locked());
......@@ -2029,7 +1974,6 @@ mod tests {
snapshot
});
assert!(!snapshot.lock.is_locked());
assert!(!snapshot.is_occupied());
}
// `hanging_detection` grows LazyField via Event descriptions; diagnostic-only layouts are not
......@@ -2047,25 +1991,25 @@ mod tests {
128,
"TaskStorage's niche should make its Option free"
);
assert_eq!(
size_of::<TaskSlot<TaskStorage>>(),
128,
"intrusive task slot must not add padding"
);
assert_eq!(
size_of::<[AtomicU64; BITMAP_WORDS]>(),
CHUNK_SIZE / 8,
PAGE_SIZE / 8,
"chunk occupancy bitmap size changed"
);
assert_eq!(
size_of::<TaskChunk<TaskStorage>>(),
16 + CHUNK_SIZE / 8,
"chunk counters and bitmap size changed"
TaskMap::<TaskStorage>::directory_entry_size(),
size_of::<AtomicPtr<()>>(),
"permanent page-directory entry must remain one pointer"
);
assert_eq!(
size_of::<[AtomicPtr<TaskStorage>; PAGE_SIZE]>(),
size_of::<AtomicPtr<TaskStorage>>() * PAGE_SIZE,
"pointer-page slot array size changed"
);
assert_eq!(
size_of::<[TaskSlot<TaskStorage>; CHUNK_SIZE]>(),
128 * CHUNK_SIZE,
"chunk slot allocation size changed"
TaskMap::<TaskStorage>::pointer_page_size(),
24 + size_of::<AtomicPtr<TaskStorage>>() * PAGE_SIZE,
"pointer-page counters, bitmap, or slots changed"
);
// `LazyField` is 40 B = 32 B largest payload + 8 B discriminant.
assert_eq!(
......
//! Sparse, directly indexed resident task storage.
//!
//! The permanent `boxcar::Vec` directory has one entry per 128 historical task IDs. Each entry
//! optionally owns a 128-pointer page, and each non-null pointer owns one boxed resident task.
//! Pointer pages and tasks are detached only while the operation coordinator holds exclusion, so
//! ordinary admitted operations need only acquire-load pointers and take the task's intrusive lock.
use std::{
marker::PhantomData,
ops::{Deref, DerefMut},
ptr,
rc::Rc,
sync::atomic::{AtomicPtr, AtomicU8, AtomicU64, Ordering},
};
use turbo_tasks::{TRANSIENT_TASK_BIT, TaskId, parallel};
pub(crate) const PAGE_SHIFT: usize = 7;
pub(crate) const PAGE_SIZE: usize = 1 << PAGE_SHIFT;
const PAGE_MASK: usize = PAGE_SIZE - 1;
const BITMAP_WORD_BITS: usize = u64::BITS as usize;
pub(crate) const BITMAP_WORDS: usize = PAGE_SIZE / BITMAP_WORD_BITS;
const _: () = assert!(PAGE_SIZE <= u8::MAX as usize);
/// Opaque proof that resident pointers are protected by a live operation admission or exclusion.
///
/// The token is intentionally not an owning guard. Its creator must keep the matching operation
/// guard or exclusion phase alive until every task guard carrying this token has been dropped.
#[derive(Clone, Copy)]
pub(crate) struct StorageAccessToken<'a> {
kind: AccessKind,
_lifetime: PhantomData<&'a ()>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum AccessKind {
Operation,
Exclusive,
}
impl StorageAccessToken<'_> {
pub(crate) fn operation() -> Self {
Self {
kind: AccessKind::Operation,
_lifetime: PhantomData,
}
}
pub(crate) fn exclusive() -> Self {
Self {
kind: AccessKind::Exclusive,
_lifetime: PhantomData,
}
}
fn assert_exclusive(self) {
assert!(
self.kind == AccessKind::Exclusive,
"resident task removal requires coordinator exclusion"
);
}
}
/// Value stored behind one independently allocated resident pointer.
///
/// # Safety
///
/// Implementations must initialize their intrusive lock in `new`, and every shared payload access
/// must be protected by `lock_raw`/`unlock_raw`. A published value remains at a stable boxed
/// address until an exclusive storage phase removes it.
pub(crate) unsafe trait TaskSlotValue: Sized {
fn new() -> Self;
/// # Safety
/// `value` must point to a live, stably-addressed value.
unsafe fn lock_raw(value: *const Self);
/// # Safety
/// The current thread must own the lock acquired through the same pointer.
unsafe fn unlock_raw(value: *const Self);
}
struct TaskPointerPage<T: TaskSlotValue + Send + 'static> {
pub(crate) modified_count: AtomicU8,
occupied_count: AtomicU8,
occupied: [AtomicU64; BITMAP_WORDS],
slots: [AtomicPtr<T>; PAGE_SIZE],
}
impl<T: TaskSlotValue + Send + 'static> TaskPointerPage<T> {
fn new() -> Self {
Self {
modified_count: AtomicU8::new(0),
occupied_count: AtomicU8::new(0),
occupied: [const { AtomicU64::new(0) }; BITMAP_WORDS],
slots: [const { AtomicPtr::new(ptr::null_mut()) }; PAGE_SIZE],
}
}
fn word_and_mask(offset: usize) -> (usize, u64) {
(offset / BITMAP_WORD_BITS, 1 << (offset % BITMAP_WORD_BITS))
}
fn mark_occupied(&self, offset: usize) {
let (word, mask) = Self::word_and_mask(offset);
self.occupied[word].fetch_or(mask, Ordering::Release);
}
fn clear_occupied(&self, offset: usize) {
let (word, mask) = Self::word_and_mask(offset);
self.occupied[word].fetch_and(!mask, Ordering::Release);
}
fn is_occupied(&self, offset: usize) -> bool {
let (word, mask) = Self::word_and_mask(offset);
self.occupied[word].load(Ordering::Acquire) & mask != 0
}
fn occupied_offsets(&self) -> OccupiedOffsets<'_> {
OccupiedOffsets {
words: &self.occupied,
word_index: 0,
bits: 0,
}
}
fn lock_slot(&self, offset: usize) -> Option<*mut T> {
if !self.is_occupied(offset) {
return None;
}
let value = self.slots[offset].load(Ordering::Acquire);
if value.is_null() {
// A losing insertion may leave a stale positive hint. Physical deletion cannot race an
// admitted reader, so null is authoritative and this hint is safe to clean up.
self.clear_occupied(offset);
return None;
}
// SAFETY: operation/exclusion admission keeps the box live, and this page is still live.
unsafe { T::lock_raw(value) };
Some(value)
}
}
impl<T: TaskSlotValue + Send + 'static> Drop for TaskPointerPage<T> {
fn drop(&mut self) {
for slot in &mut self.slots {
let value = *slot.get_mut();
if !value.is_null() {
// SAFETY: page destruction requires exclusive access, so no task guard exists.
unsafe { drop(Box::from_raw(value)) };
}
}
}
}
pub(crate) struct OccupiedOffsets<'a> {
words: &'a [AtomicU64; BITMAP_WORDS],
word_index: usize,
bits: u64,
}
impl Iterator for OccupiedOffsets<'_> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
loop {
if self.bits != 0 {
let bit = self.bits.trailing_zeros() as usize;
self.bits &= self.bits - 1;
return Some((self.word_index - 1) * BITMAP_WORD_BITS + bit);
}
let word = self.words.get(self.word_index)?;
self.word_index += 1;
self.bits = word.load(Ordering::Acquire);
}
}
}
struct PageDirectoryEntry<T: TaskSlotValue + Send + 'static> {
page: AtomicPtr<TaskPointerPage<T>>,
}
impl<T: TaskSlotValue + Send + 'static> PageDirectoryEntry<T> {
fn new() -> Self {
Self {
page: AtomicPtr::new(ptr::null_mut()),
}
}
fn load(&self) -> Option<&TaskPointerPage<T>> {
let page = self.page.load(Ordering::Acquire);
if page.is_null() {
None
} else {
// SAFETY: every caller holds operation/exclusion access, so a published page cannot be
// detached or freed for the duration of the returned use.
Some(unsafe { &*page })
}
}
fn get_or_insert(&self) -> &TaskPointerPage<T> {
if let Some(page) = self.load() {
return page;
}
let new_page = Box::into_raw(Box::new(TaskPointerPage::new()));
match self.page.compare_exchange(
ptr::null_mut(),
new_page,
Ordering::Release,
Ordering::Acquire,
) {
Ok(_) => {
// SAFETY: this thread published and owns the stable page allocation.
unsafe { &*new_page }
}
Err(page) => {
// SAFETY: publication failed, so no other thread can observe this allocation.
unsafe { drop(Box::from_raw(new_page)) };
debug_assert!(!page.is_null());
// SAFETY: the winning publisher release-initialized the page; acquire failure
// ordering observes it, and operation access prevents detachment.
unsafe { &*page }
}
}
}
fn detach_if_empty(&self, access: StorageAccessToken<'_>) -> bool {
access.assert_exclusive();
let page = self.page.load(Ordering::Acquire);
if page.is_null() {
return false;
}
// SAFETY: exclusion prevents pointer users and publishers.
if unsafe { &*page }.occupied_count.load(Ordering::Acquire) != 0 {
return false;
}
let detached = self.page.swap(ptr::null_mut(), Ordering::AcqRel);
debug_assert_eq!(detached, page);
// SAFETY: exclusion proves no task/page guard exists and this pointer was detached once.
unsafe { drop(Box::from_raw(detached)) };
true
}
fn clear(&self, access: StorageAccessToken<'_>) {
access.assert_exclusive();
let page = self.page.swap(ptr::null_mut(), Ordering::AcqRel);
if !page.is_null() {
// SAFETY: exclusion proves no pointer user exists and the swap transferred ownership.
unsafe { drop(Box::from_raw(page)) };
}
}
}
struct PagedVec<T: TaskSlotValue + Send + 'static> {
entries: boxcar::Vec<PageDirectoryEntry<T>>,
}
impl<T: TaskSlotValue + Send + 'static> PagedVec<T> {
fn with_page_capacity(page_capacity: usize) -> Self {
Self {
entries: boxcar::Vec::with_capacity(page_capacity),
}
}
fn entry(&self, index: usize) -> Option<&PageDirectoryEntry<T>> {
self.entries.get(index >> PAGE_SHIFT)
}
fn get_or_create_entry(&self, index: usize) -> &PageDirectoryEntry<T> {
let page_index = index >> PAGE_SHIFT;
if let Some(entry) = self.entries.get(page_index) {
return entry;
}
while self.entries.count() <= page_index {
self.entries.push(PageDirectoryEntry::new());
}
loop {
if let Some(entry) = self.entries.get(page_index) {
return entry;
}
std::hint::spin_loop();
}
}
fn entries(&self) -> impl Iterator<Item = (usize, &PageDirectoryEntry<T>)> {
self.entries.iter()
}
fn live_pages<'a>(
&'a self,
access: StorageAccessToken<'a>,
transient: bool,
) -> Vec<TaskPageRef<'a, T>> {
self.entries()
.filter_map(|(index, entry)| {
entry.load().map(|page| TaskPageRef {
page,
base_id: index << PAGE_SHIFT,
transient,
access,
})
})
.collect()
}
fn len(&self) -> usize {
self.entries()
.filter_map(|(_, entry)| entry.load())
.map(|page| page.occupied_count.load(Ordering::Relaxed) as usize)
.sum()
}
fn clear(&self, access: StorageAccessToken<'_>) {
access.assert_exclusive();
for (_, entry) in self.entries() {
entry.clear(access);
}
}
fn reclaim_empty_pages(&self, access: StorageAccessToken<'_>) -> usize {
access.assert_exclusive();
self.entries()
.filter(|(_, entry)| entry.detach_if_empty(access))
.count()
}
fn live_page_count(&self) -> usize {
self.entries()
.filter(|(_, entry)| !entry.page.load(Ordering::Acquire).is_null())
.count()
}
}
impl<T: TaskSlotValue + Send + 'static> Drop for PagedVec<T> {
fn drop(&mut self) {
for index in 0..self.entries.count() {
let entry = self
.entries
.get_mut(index)
.expect("all Boxcar entries below count are initialized");
let page = *entry.page.get_mut();
if !page.is_null() {
// SAFETY: `&mut self` proves no directory/page users remain.
unsafe { drop(Box::from_raw(page)) };
}
}
}
}
pub(crate) struct TaskMap<T: TaskSlotValue + Send + 'static> {
persistent: PagedVec<T>,
transient: PagedVec<T>,
}
impl<T: TaskSlotValue + Send + 'static> TaskMap<T> {
pub(crate) fn new(small_preallocation: bool) -> Self {
let persistent_page_capacity = if small_preallocation {
1
} else {
(1024 * 1024) / PAGE_SIZE
};
Self {
persistent: PagedVec::with_page_capacity(persistent_page_capacity),
transient: PagedVec::with_page_capacity(1),
}
}
fn namespace_and_index(&self, key: TaskId) -> (&PagedVec<T>, usize) {
let raw = *key as usize;
if key.is_transient() {
(&self.transient, raw & !(TRANSIENT_TASK_BIT as usize))
} else {
(&self.persistent, raw)
}
}
pub(crate) fn get<'a>(
&'a self,
key: TaskId,
access: StorageAccessToken<'a>,
) -> Option<TaskMapGuard<'a, T>> {
let (namespace, index) = self.namespace_and_index(key);
let entry = namespace.entry(index)?;
let page = entry.load()?;
let offset = index & PAGE_MASK;
let value = page.lock_slot(offset)?;
Some(TaskMapGuard::new_locked(
key,
value,
&page.slots[offset],
page,
access,
))
}
pub(crate) fn get_or_insert<'a>(
&'a self,
key: TaskId,
access: StorageAccessToken<'a>,
) -> TaskMapGuard<'a, T> {
if let Some(task) = self.get(key, access) {
return task;
}
let (namespace, index) = self.namespace_and_index(key);
let entry = namespace.get_or_create_entry(index);
let page = entry.get_or_insert();
let offset = index & PAGE_MASK;
let slot = &page.slots[offset];
loop {
let current = slot.load(Ordering::Acquire);
if !current.is_null() {
// This path follows a bitmap miss, so repair a transient/stale false hint before
// returning the authoritative pointer. Ordinary hits never perform this RMW.
page.mark_occupied(offset);
// SAFETY: operation admission keeps the published box live.
unsafe { T::lock_raw(current) };
return TaskMapGuard::new_locked(key, current, slot, page, access);
}
let new_value = Box::into_raw(Box::new(T::new()));
// Lock before publication so this creator returns the first mutable guard and racing
// readers cannot observe a partially initialized caller mutation.
// SAFETY: `new_value` is a live stable box initialized by `T::new`.
unsafe { T::lock_raw(new_value) };
match slot.compare_exchange(
ptr::null_mut(),
new_value,
Ordering::Release,
Ordering::Acquire,
) {
Ok(_) => {
// Publish iteration metadata only after the authoritative pointer. Exclusive
// scans wait for this operation to finish; concurrent scans may miss this
// in-flight insertion, but can never clear a bit before publication.
page.mark_occupied(offset);
let previous = page.occupied_count.fetch_add(1, Ordering::AcqRel);
debug_assert!((previous as usize) < PAGE_SIZE);
return TaskMapGuard::new_locked(key, new_value, slot, page, access);
}
Err(winner) => {
// SAFETY: publication failed; unlock and free the unobserved allocation.
unsafe { T::unlock_raw(new_value) };
unsafe { drop(Box::from_raw(new_value)) };
if !winner.is_null() {
page.mark_occupied(offset);
// SAFETY: operation admission keeps the winner live.
unsafe { T::lock_raw(winner) };
return TaskMapGuard::new_locked(key, winner, slot, page, access);
}
}
}
}
}
pub(crate) fn len(&self, _access: StorageAccessToken<'_>) -> usize {
self.persistent.len() + self.transient.len()
}
pub(crate) fn clear(&self, access: StorageAccessToken<'_>) {
access.assert_exclusive();
self.persistent.clear(access);
self.transient.clear(access);
}
pub(crate) fn reclaim_empty_pages(&self, access: StorageAccessToken<'_>) -> usize {
access.assert_exclusive();
self.persistent.reclaim_empty_pages(access) + self.transient.reclaim_empty_pages(access)
}
#[allow(dead_code)]
pub(crate) fn loaded_page_count(&self) -> usize {
self.persistent.live_page_count() + self.transient.live_page_count()
}
#[allow(dead_code)]
pub(crate) fn directory_entry_count(&self) -> usize {
self.persistent.entries.count() + self.transient.entries.count()
}
#[allow(dead_code)]
pub(crate) fn directory_entry_size() -> usize {
std::mem::size_of::<PageDirectoryEntry<T>>()
}
#[allow(dead_code)]
pub(crate) fn pointer_page_size() -> usize {
std::mem::size_of::<TaskPointerPage<T>>()
}
pub(crate) fn parallel_collect<'a, R, C>(
&'a self,
access: StorageAccessToken<'a>,
f: impl Fn(TaskPageRef<'a, T>) -> R + Send + Sync,
) -> C
where
R: Send + Sync,
C: FromIterator<R>,
{
let pages = self.pages(access);
parallel::map_collect_owned(pages, f)
}
pub(crate) fn pages<'a>(&'a self, access: StorageAccessToken<'a>) -> Vec<TaskPageRef<'a, T>> {
let mut pages = self.persistent.live_pages(access, false);
pages.extend(self.transient.live_pages(access, true));
pages
}
pub(crate) fn persistent_pages<'a>(
&'a self,
access: StorageAccessToken<'a>,
) -> Vec<TaskPageRef<'a, T>> {
self.persistent.live_pages(access, false)
}
pub(crate) fn page_indices(&self, _access: StorageAccessToken<'_>) -> Vec<(bool, usize)> {
self.persistent
.entries()
.filter_map(|(index, entry)| {
(!entry.page.load(Ordering::Acquire).is_null()).then_some((false, index))
})
.chain(self.transient.entries().filter_map(|(index, entry)| {
(!entry.page.load(Ordering::Acquire).is_null()).then_some((true, index))
}))
.collect()
}
pub(crate) fn page<'a>(
&'a self,
index: usize,
transient: bool,
access: StorageAccessToken<'a>,
) -> Option<TaskPageRef<'a, T>> {
let entries = if transient {
&self.transient.entries
} else {
&self.persistent.entries
};
let entry = entries.get(index)?;
let page = entry.load()?;
Some(TaskPageRef {
page,
base_id: index << PAGE_SHIFT,
transient,
access,
})
}
}
#[derive(Clone, Copy)]
pub(crate) struct TaskPageRef<'a, T: TaskSlotValue + Send + 'static> {
page: &'a TaskPointerPage<T>,
base_id: usize,
transient: bool,
access: StorageAccessToken<'a>,
}
impl<'a, T: TaskSlotValue + Send + 'static> TaskPageRef<'a, T> {
pub(crate) fn for_each_mut(&self, mut f: impl FnMut(TaskMapGuard<'a, T>)) {
for offset in self.page.occupied_offsets() {
if let Some(value) = self.page.lock_slot(offset) {
f(TaskMapGuard::new_locked(
self.task_id(offset),
value,
&self.page.slots[offset],
self.page,
self.access,
));
}
}
}
#[allow(dead_code)]
pub(crate) fn for_each_all_mut(&self, mut f: impl FnMut(TaskMapGuard<'a, T>)) {
for offset in 0..PAGE_SIZE {
if let Some(value) = self.page.lock_slot(offset) {
f(TaskMapGuard::new_locked(
self.task_id(offset),
value,
&self.page.slots[offset],
self.page,
self.access,
));
}
}
}
#[allow(dead_code)]
pub(crate) fn get(&self, offset: usize) -> Option<TaskMapGuard<'a, T>> {
let value = self.page.lock_slot(offset)?;
Some(TaskMapGuard::new_locked(
self.task_id(offset),
value,
&self.page.slots[offset],
self.page,
self.access,
))
}
pub(crate) fn take_modified_count(&self) -> Option<u8> {
Some(self.page.modified_count.swap(0, Ordering::AcqRel))
}
pub(crate) fn modified_count(&self) -> u8 {
self.page.modified_count.load(Ordering::Relaxed)
}
#[allow(dead_code)]
pub(crate) fn is_probably_occupied(&self, offset: usize) -> bool {
self.page.is_occupied(offset)
}
#[allow(dead_code)]
pub(crate) fn probably_occupied_offsets(&self) -> Vec<usize> {
self.page.occupied_offsets().collect()
}
fn task_id(&self, offset: usize) -> TaskId {
let mut raw = self.base_id + offset;
if self.transient {
raw |= TRANSIENT_TASK_BIT as usize;
}
TaskId::new(raw as u32).expect("occupied task slot must have a valid TaskId")
}
}
/// Exclusive access to one boxed resident task.
pub(crate) struct TaskMapGuard<'a, T: TaskSlotValue + Send + 'static> {
key: TaskId,
value_ptr: *mut T,
slot: &'a AtomicPtr<T>,
page: &'a TaskPointerPage<T>,
access: StorageAccessToken<'a>,
locked: bool,
_not_send: PhantomData<Rc<()>>,
}
impl<'a, T: TaskSlotValue + Send + 'static> TaskMapGuard<'a, T> {
fn new_locked(
key: TaskId,
value: *mut T,
slot: &'a AtomicPtr<T>,
page: &'a TaskPointerPage<T>,
access: StorageAccessToken<'a>,
) -> Self {
Self {
key,
value_ptr: value,
slot,
page,
access,
locked: true,
_not_send: PhantomData,
}
}
pub(crate) fn key(&self) -> &TaskId {
&self.key
}
pub(crate) fn modified_count(&self) -> &AtomicU8 {
&self.page.modified_count
}
pub(crate) fn modified_count_ptr(&self) -> *const AtomicU8 {
&self.page.modified_count
}
fn remove_box(mut self) -> Box<T> {
self.access.assert_exclusive();
let removed = self
.slot
.compare_exchange(
self.value_ptr,
ptr::null_mut(),
Ordering::AcqRel,
Ordering::Acquire,
)
.expect("exclusive task removal must detach the guarded pointer");
debug_assert_eq!(removed, self.value_ptr);
let raw = *self.key as usize & !(TRANSIENT_TASK_BIT as usize);
self.page.clear_occupied(raw & PAGE_MASK);
let previous = self.page.occupied_count.fetch_sub(1, Ordering::AcqRel);
debug_assert!(previous > 0);
// Unlock before transferring/dropping allocation ownership: the mutex lives inside T.
// SAFETY: this guard owns the intrusive lock acquired through `self.value`.
unsafe { T::unlock_raw(self.value_ptr) };
self.locked = false;
// SAFETY: compare_exchange transferred the one published box allocation to this guard.
unsafe { Box::from_raw(self.value_ptr) }
}
pub(crate) fn take_and_vacate(self) -> T {
*self.remove_box()
}
pub(crate) fn vacate(self) {
drop(self.remove_box());
}
}
impl<T: TaskSlotValue + Send + 'static> Deref for TaskMapGuard<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// SAFETY: this guard owns the pointed-to task's intrusive lock and operation/exclusion
// access keeps the allocation alive.
unsafe { &*self.value_ptr }
}
}
impl<T: TaskSlotValue + Send + 'static> DerefMut for TaskMapGuard<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
// SAFETY: this guard exclusively owns the pointed-to task's intrusive lock.
unsafe { &mut *self.value_ptr }
}
}
impl<T: TaskSlotValue + Send + 'static> Drop for TaskMapGuard<'_, T> {
fn drop(&mut self) {
if self.locked {
// SAFETY: construction acquired this lock and the guard is !Send.
unsafe { T::unlock_raw(self.value_ptr) };
}
}
}
#[cfg(test)]
mod tests {
use std::{
sync::{Arc, Barrier},
thread,
};
use parking_lot::{Mutex, lock_api::RawMutex as _};
use static_assertions::assert_not_impl_any;
use super::*;
struct TestValue {
lock: Mutex<()>,
value: u64,
}
// SAFETY: every payload access is protected by `lock` and values stay boxed while admitted.
unsafe impl TaskSlotValue for TestValue {
fn new() -> Self {
Self {
lock: Mutex::new(()),
value: 0,
}
}
unsafe fn lock_raw(value: *const Self) {
// SAFETY: guaranteed by TaskSlotValue's caller contract.
unsafe { (&*ptr::addr_of!((*value).lock)).raw().lock() };
}
unsafe fn unlock_raw(value: *const Self) {
// SAFETY: caller owns the same raw lock.
unsafe { (&*ptr::addr_of!((*value).lock)).raw().unlock() };
}
}
fn task_id(raw: u32) -> TaskId {
TaskId::new(raw).unwrap()
}
fn operation() -> StorageAccessToken<'static> {
StorageAccessToken::operation()
}
fn exclusive() -> StorageAccessToken<'static> {
StorageAccessToken::exclusive()
}
assert_not_impl_any!(TaskMapGuard<'static, TestValue>: Send, Sync);
#[test]
fn page_boundary_and_reclamation() {
let map = TaskMap::<TestValue>::new(true);
map.get_or_insert(task_id(127), operation()).value = 1;
map.get_or_insert(task_id(128), operation()).value = 2;
assert_eq!(map.loaded_page_count(), 2);
map.get(task_id(127), exclusive()).unwrap().vacate();
assert_eq!(map.reclaim_empty_pages(exclusive()), 1);
assert_eq!(map.loaded_page_count(), 1);
map.get(task_id(128), exclusive()).unwrap().vacate();
assert_eq!(map.reclaim_empty_pages(exclusive()), 1);
assert_eq!(map.loaded_page_count(), 0);
map.get_or_insert(task_id(128), operation()).value = 3;
assert_eq!(map.get(task_id(128), operation()).unwrap().value, 3);
}
#[test]
fn sparse_high_id_allocates_one_page() {
let map = TaskMap::<TestValue>::new(true);
map.get_or_insert(task_id(1_000_000), operation());
assert_eq!(map.loaded_page_count(), 1);
assert_eq!(map.directory_entry_count(), (1_000_000 >> PAGE_SHIFT) + 1);
}
#[test]
fn transient_and_persistent_namespaces_do_not_alias() {
let map = TaskMap::<TestValue>::new(true);
let persistent = task_id(1);
let transient = task_id(1 | TRANSIENT_TASK_BIT);
map.get_or_insert(persistent, operation()).value = 10;
map.get_or_insert(transient, operation()).value = 20;
assert_eq!(map.get(persistent, operation()).unwrap().value, 10);
assert_eq!(map.get(transient, operation()).unwrap().value, 20);
}
#[test]
fn concurrent_first_insertion_has_one_winner() {
let map = Arc::new(TaskMap::<TestValue>::new(true));
let barrier = Arc::new(Barrier::new(8));
let threads = (0..8)
.map(|_| {
let map = Arc::clone(&map);
let barrier = Arc::clone(&barrier);
thread::spawn(move || {
barrier.wait();
map.get_or_insert(task_id(1), operation()).value += 1;
})
})
.collect::<Vec<_>>();
for thread in threads {
thread.join().unwrap();
}
assert_eq!(map.len(operation()), 1);
assert_eq!(map.get(task_id(1), operation()).unwrap().value, 8);
}
#[tokio::test(flavor = "multi_thread")]
async fn parallel_collect_seeds_only_live_pages() {
let map = TaskMap::<TestValue>::new(true);
for id in [1, 130, 1_000_000] {
map.get_or_insert(task_id(id), operation());
}
let counts: Vec<usize> = map.parallel_collect(operation(), |page| {
let mut count = 0;
page.for_each_mut(|_| count += 1);
count
});
assert_eq!(counts.len(), 3);
assert_eq!(counts.into_iter().sum::<usize>(), 3);
map.clear(exclusive());
let counts: Vec<usize> = map.parallel_collect(operation(), |_| 1);
assert!(counts.is_empty());
assert_eq!(map.loaded_page_count(), 0);
}
}
......@@ -1364,14 +1364,12 @@ fn generate_typed_storage_struct(grouped_fields: &GroupedFields) -> TokenStream
// Collect all field definitions from both categories
let mut field_defs = Vec::new();
let mut field_names = Vec::new();
// Add inline fields directly on TaskStorage (private - use accessor methods)
// Note: No bincode attributes since we don't derive Encode/Decode (manual serialization)
for field in grouped_fields.all_inline() {
let field_name = &field.field_name;
let field_type = &field.field_type;
field_names.push(field_name.clone());
field_defs.push(quote! {
#field_name: #field_type
});
......@@ -1397,19 +1395,6 @@ fn generate_typed_storage_struct(grouped_fields: &GroupedFields) -> TokenStream
quote! {}
};
let swap_flags = has_flags.then(|| {
quote! { std::mem::swap(&mut self.flags, &mut detached.flags); }
});
let swap_lazy = has_lazy.then(|| {
quote! { std::mem::swap(&mut self.lazy, &mut detached.lazy); }
});
let reset_flags = has_flags.then(|| {
quote! { self.flags = Default::default(); }
});
let reset_lazy = has_lazy.then(|| {
quote! { self.lazy = Default::default(); }
});
// Note: Helper methods like find_lazy, find_lazy_mut, get_or_create_lazy, and
// remove_if_empty are defined in storage_schema.rs rather than generated here.
// This provides better IDE support (autocomplete, go-to-definition, etc.).
......@@ -1426,39 +1411,15 @@ fn generate_typed_storage_struct(grouped_fields: &GroupedFields) -> TokenStream
#(#field_defs,)*
#flags_field
#lazy_field
#[doc = "Intrusive lock protecting this stable task slot"]
#[doc = "Intrusive lock protecting this stable task allocation"]
pub(crate) lock: IntrusiveTaskLock,
#[doc = "Authoritative slot presence, accessed only while `lock` is held"]
pub(crate) occupied: bool,
}
#[automatically_derived]
impl TaskStorage {
#[doc = "Constructs fresh task payload with unlocked, vacant slot metadata."]
#[doc = "Constructs a fresh task payload with an unlocked intrusive mutex."]
pub const fn new() -> Self {
Self::empty_slot()
}
#[doc = "Moves payload into a fresh unlocked value and leaves this locked slot vacant."]
#[doc = "The caller must hold this task's intrusive lock."]
pub(crate) fn take_and_vacate(&mut self) -> Self {
debug_assert!(self.occupied);
let mut detached = Self::default();
#(std::mem::swap(&mut self.#field_names, &mut detached.#field_names);)*
#swap_flags
#swap_lazy
self.occupied = false;
detached
}
#[doc = "Drops and resets payload in place while preserving the held mutex."]
#[doc = "The caller must hold this task's intrusive lock."]
pub(crate) fn vacate_in_place(&mut self) {
debug_assert!(self.occupied);
#(self.#field_names = Default::default();)*
#reset_flags
#reset_lazy
self.occupied = false;
Self::empty_task()
}
}
}
......
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