Unverified Commit 4bad5e74 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Turbopack: fix lock-order inversion between Storage::map and Storage::snapshots (#93788)

### What?

Fix a latent deadlock between `track_modification_internal` /
`SnapshotShardIter::next` and `Storage::end_snapshot` in
`turbo-tasks-backend`, and harden `dash_map_multi::RefMut` so that
holding a `StorageWriteGuard` across an `.await` can no longer compile.

### Why?

`Storage` has three sharded `DashMap`s — `task_cache`, `map`, and
`snapshots`. The two call sites that touch both `map` and `snapshots`
(`track_modification_internal` at `storage.rs:685/703` and
`SnapshotShardIter::next` at `storage.rs:845/851`) hold a `map` shard
write lock and then take a `snapshots` shard write lock — i.e. order
`map → snapshots`.

`end_snapshot` did the opposite: it called
`parallel::for_each(self.snapshots.shards(), ...)`, took a `snapshots`
shard write lock, drained it, and then called `self.map.get_mut(&key)`
to promote flags — order `snapshots → map`. The existing comment argued
this was safe because `track_modification` only inserts into `snapshots`
when `snapshot_mode == true` and `end_snapshot` first stores
`snapshot_mode = false`.

That argument is incorrect. `track_modification_internal` loads
`snapshot_mode` (line 616) and inserts into `snapshots` later (line 685
or 703); the two are not atomic. The interleaving:

1. T1 in `track_modification_internal`: holds `map[N]`, reads
`snapshot_mode() → true`.
2. T2 in `end_snapshot`: stores `snapshot_mode = false`, takes
`snapshots[N]` write lock.
3. T2: tries `map.get_mut(&key)` → blocks on `map[N]` (T1 holds it).
4. T1: tries `snapshots.insert(...)` → blocks on `snapshots[N]` (T2
holds it).

deadlocks both threads.

Separately, `dash_map_multi::RefMut` (which backs `StorageWriteGuard`)
had `unsafe impl Send`. The wrapped `parking_lot` `RwLockWriteGuard` is
intentionally `!Send` upstream (via `lock_api::GuardNoSend(*mut ())`);
the manual override let callers compile code that holds a
`StorageWriteGuard` across an `.await`. In that pattern the guard pins a
shard write lock from a parked future and every other tokio worker piles
up trying to take the same shard — a deadlock that the borrow checker
would otherwise catch for free.

### How?

**`Storage::end_snapshot`** (`storage.rs:383`):
- Zip `map.shards()` with `snapshots.shards()` by index and lock each
pair in the documented order: `map_shard.write()` first, then
`snap_shard.write()`.
- For every key drained from `snapshots[N]`, resolve it directly in the
held `map_shard` guard via `RawTable::find`, rather than calling
`self.map.get_mut` (which would re-enter the same shard).
- `debug_assert_eq!` on the shard counts.
- Update the obsolete "this is fine" comment to describe the prior race
and the new pattern.

**Shard pairing invariant** is now documented on the `map` and
`snapshots` field declarations: both `DashMap`s are constructed with the
same `shard_amount`, the same `TaskId` key type, and the same stateless
`FxBuildHasher`, so shard `N` in `snapshots` corresponds exactly to
shard `N` in `map`. Every key present in `snapshots.shards()[N]` (if
present in `map`) lives in `map.shards()[N]`, so the zipped acquisition
covers every drainable entry.

**`dash_map_multi::RefMut`** (`dash_map_multi.rs:32`):
- Removed the `unsafe impl<K: Eq + Hash + Sync, V: Sync> Send for
RefMut<'_, K, V> {}`.
- `RwLockWriteGuard` already contains `GuardNoSend(*mut ())`, so the
auto-trait derivation correctly marks `RefMut` (and therefore
`StorageWriteGuard`, `TaskGuardImpl`, `OccupiedEntry`, `VacantEntry`)
`!Send`. Verified by compile-fail probes on all four guard types.
- Kept `unsafe impl Sync` — sharing `&RefMut` between threads is still
sound (the write guard provides exclusive access, `K: Sync + V: Sync`).
- Replaced the old SAFETY comment with one that explains why `Send` is
intentionally omitted.

### Audit summary

After the fix, the full lock-order graph for the three `Storage`
dashmaps is:

```
task_cache ─→ map ─→ snapshots
       ▲
       └── (non-blocking try_lock_and_remove + defer in evict_after_snapshot)
```

Total order: `task_cache → map → snapshots`. The only reverse edge is
`evict_after_snapshot`'s non-blocking `try_lock_and_remove` on
`task_cache` while holding `map`, which defers on contention — no
hold-and-wait possible. Within `map`, the only multi-guard path is
`access_pair_mut`, whose retry loop in `get_multiple_mut` holds zero
shard guards at every blocking acquire. Per-thread nested task guards
are prevented at runtime in debug builds by `TaskLockCounter::acquire`
(`operation/mod.rs:128–166`).

### Testing

- `cargo check --all-targets` (turbopack workspace): clean.
- `cargo test -p turbo-tasks-backend --lib storage::`: 4/4 pass,
including `modify_during_snapshot_clears_live_modified_flags` and
`modify_different_category_during_snapshot` which exercise the snapshot
lifecycle this PR touches.
- Compile-fail probes confirmed `StorageWriteGuard`, `TaskGuardImpl`,
`OccupiedEntry`, and `VacantEntry` are all `!Send` post-change.

<!-- NEXT_JS_LLM_PR -->
parent 3cf7aa24
......@@ -2353,6 +2353,9 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
) {
debug_assert!(!output_dependent_tasks.is_empty());
#[cfg(feature = "trace_task_dirty")]
let task_description = self.debug_get_task_description(task_id);
if output_dependent_tasks.len() > 1 {
ctx.prepare_tasks(
output_dependent_tasks
......@@ -2365,6 +2368,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
fn process_output_dependents(
ctx: &mut impl ExecuteContext<'_>,
task_id: TaskId,
#[cfg(feature = "trace_task_dirty")] task_description: &str,
dependent_task_id: TaskId,
queue: &mut AggregationUpdateQueue,
) {
......@@ -2405,7 +2409,9 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
dependent_task_id,
make_stale,
#[cfg(feature = "trace_task_dirty")]
TaskDirtyCause::OutputChange { task_id },
TaskDirtyCause::OutputChange {
task_description: task_description.to_string(),
},
queue,
ctx,
);
......@@ -2419,6 +2425,8 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
let _ = scope_and_block(chunks.len(), |scope| {
for chunk in chunks {
let child_ctx = ctx.child_context();
#[cfg(feature = "trace_task_dirty")]
let task_description = &task_description;
scope.spawn(move || {
let mut ctx = child_ctx.create();
let mut queue = AggregationUpdateQueue::new();
......@@ -2426,6 +2434,8 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
process_output_dependents(
&mut ctx,
task_id,
#[cfg(feature = "trace_task_dirty")]
task_description,
dependent_task_id,
&mut queue,
)
......@@ -2437,7 +2447,14 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
} else {
let mut queue = AggregationUpdateQueue::new();
for dependent_task_id in output_dependent_tasks {
process_output_dependents(ctx, task_id, dependent_task_id, &mut queue);
process_output_dependents(
ctx,
task_id,
#[cfg(feature = "trace_task_dirty")]
&task_description,
dependent_task_id,
&mut queue,
);
}
queue.execute(ctx);
}
......
......@@ -97,7 +97,7 @@ pub enum TaskDirtyCause {
value_type: turbo_tasks::ValueTypeId,
},
OutputChange {
task_id: TaskId,
task_description: String,
},
CollectiblesChange {
collectible_type: turbo_tasks::TraitTypeId,
......@@ -106,31 +106,18 @@ pub enum TaskDirtyCause {
Unknown,
}
// NOTE: `TaskDirtyCause` is formatted for tracing inside `make_task_dirty_internal`, which
// already holds the dependent task's `StorageWriteGuard`. The `Display` impl below must NOT
// acquire any task guard — doing so would take a second map shard write lock with no ordering
// guarantee against the first and two concurrent invalidations of each other's outputs would
// form a classic hold-and-wait deadlock on the dashmap. `OutputChange::task_description` is
// therefore filled at the call site (before any guard is held) and only formatted here.
// The `TaskLockCounter` debug-assert that normally catches this kind of nested acquire is
// `cfg(debug_assertions)`-only, so release builds hang silently.
#[cfg(feature = "trace_task_dirty")]
struct TaskDirtyCauseInContext<'l> {
cause: &'l TaskDirtyCause,
task_description: String,
}
#[cfg(feature = "trace_task_dirty")]
impl<'l> TaskDirtyCauseInContext<'l> {
fn new(cause: &'l TaskDirtyCause, ctx: &'l mut impl ExecuteContext<'_>) -> Self {
Self {
cause,
task_description: match cause {
TaskDirtyCause::OutputChange { task_id } => ctx
.task(*task_id, TaskDataCategory::Data)
.get_task_description(),
_ => String::new(),
},
}
}
}
#[cfg(feature = "trace_task_dirty")]
impl std::fmt::Display for TaskDirtyCauseInContext<'_> {
impl std::fmt::Display for TaskDirtyCause {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.cause {
match self {
TaskDirtyCause::InitialDirty => write!(f, "initial dirty"),
TaskDirtyCause::CellChange { value_type, keys } => {
if keys.is_empty() {
......@@ -161,8 +148,8 @@ impl std::fmt::Display for TaskDirtyCauseInContext<'_> {
turbo_tasks::registry::get_value_type(*value_type).ty.name
)
}
TaskDirtyCause::OutputChange { .. } => {
write!(f, "task {} output changed", self.task_description)
TaskDirtyCause::OutputChange { task_description } => {
write!(f, "task {task_description} output changed")
}
TaskDirtyCause::CollectiblesChange { collectible_type } => {
write!(
......@@ -208,10 +195,7 @@ pub fn make_task_dirty_internal(
#[cfg(any(debug_assertions, feature = "verify_immutable"))]
if task.immutable() {
#[cfg(feature = "trace_task_dirty")]
let extra_info = format!(
" Invalidation cause: {}",
TaskDirtyCauseInContext::new(&cause, ctx)
);
let extra_info = format!(" Invalidation cause: {cause}");
#[cfg(not(feature = "trace_task_dirty"))]
let extra_info = "";
......@@ -234,7 +218,7 @@ pub fn make_task_dirty_internal(
"make task stale",
task_id = display(task_id),
name = task_name,
cause = %TaskDirtyCauseInContext::new(&cause, ctx)
cause = %cause
)
.entered();
*stale = true;
......@@ -247,7 +231,7 @@ pub fn make_task_dirty_internal(
"task already dirty",
task_id = display(task_id),
name = task_name,
cause = %TaskDirtyCauseInContext::new(&cause, ctx)
cause = %cause
)
.entered();
// already dirty
......@@ -273,7 +257,7 @@ pub fn make_task_dirty_internal(
let _span = tracing::trace_span!(
"session-dependent task already dirty",
name = task_name,
cause = %TaskDirtyCauseInContext::new(&cause, ctx)
cause = %cause
)
.entered();
// already dirty
......@@ -305,7 +289,7 @@ pub fn make_task_dirty_internal(
"make task dirty",
task_id = display(task_id),
name = task_name,
cause = %TaskDirtyCauseInContext::new(&cause, ctx)
cause = %cause
)
.entered();
......
......@@ -149,6 +149,18 @@ pub struct Storage {
/// Contains a copy of the pre-snapshot state that needs to be persisted.
/// - `None`: Task was first modified during snapshot mode (not part of current snapshot). Will
/// be marked as modified at the beginning of the next snapshot cycle.
///
/// Lock Ordering: `snapshots` locks are acquired **after** `map` locks (see the comment on
/// `map` below). Holding a `snapshots` shard write lock and then trying to take a `map` shard
/// write lock is forbidden — it would deadlock against `track_modification_internal` /
/// `SnapshotShardIter::next`, which take map first.
///
/// Shard Invariant: `snapshots` is constructed with the same `shard_amount`, the same key
/// type (`TaskId`), and the same stateless hasher (`FxBuildHasher`) as `map`. Therefore shard
/// index `N` in `snapshots` corresponds exactly to shard index `N` in `map`: any `TaskId`
/// present in `snapshots.shards()[N]` (if present in `map` at all) is in `map.shards()[N]`.
/// Code that walks both maps in parallel (e.g. `end_snapshot`) relies on this to lock pairs
/// of shards by index instead of going through the top-level `DashMap` accessors.
snapshots: FxDashMap<TaskId, Option<Box<TaskStorage>>>,
/// The main storage map
///
......@@ -156,6 +168,11 @@ pub struct Storage {
/// Because both datastructures are sharded on different keys, the locks are not 'strictly'
/// ordered but we should treat them as such
/// Acquiring locks in the opposite order should be defensive
///
/// Lock Ordering vs. `snapshots`: `map` locks are acquired **before** `snapshots` locks.
/// `track_modification_internal` and `SnapshotShardIter::next` both hold a `map` shard write
/// lock (via `StorageWriteGuard` / `map.get_mut`) and then take a `snapshots` shard lock.
/// `end_snapshot` must lock in the same order — see the shard-zipping pattern there.
map: FxDashMap<TaskId, Box<TaskStorage>>,
/// A shared event notified whenever any task finishes restoring (successfully or not).
///
......@@ -372,24 +389,57 @@ impl Storage {
// The snapshots map should be small (only tasks concurrently accessed during snapshot
// mode). Increment the per-shard modified counts for promoted tasks.
// Lock Ordering: Note, in track_modification_internal, we modify the snapshots map while
// holding a StorageWriteGuard and here we do the opposite. This is fine because that code
// only runs when `snapshot_mode==true` and this loop only runs when it is false.
parallel::for_each(self.snapshots.shards(), |shard| {
let mut shard_guard = shard.write();
for (key, _) in shard_guard.drain() {
if let Some(mut inner) = self.map.get_mut(&key) {
self.promote_during_snapshot_flags(&mut inner, self.shard_index(&key));
// Lock Ordering: we must acquire `map` shards BEFORE `snapshots` shards, matching the
// order used by `track_modification_internal` and `SnapshotShardIter::next`. The
// previous implementation drained `snapshots` first and then called `self.map.get_mut`,
// which is the opposite order — a concurrent `track_modification` (holding map[N], about
// to insert into snapshots[N]) could deadlock against it through the
// `snapshot_mode = false` race window.
//
// Shard pairing: `map` and `snapshots` are constructed with the same `shard_amount`,
// same `TaskId` keys, and the same stateless `FxBuildHasher`. Therefore shard `N` in
// `snapshots` pairs with shard `N` in `map`: every key drained from `snapshots[N]` (if
// it still exists in `map`) lives in `map[N]`. We zip them and lock each pair in order.
let map_shards = self.map.shards();
let snapshot_shards = self.snapshots.shards();
debug_assert_eq!(
map_shards.len(),
snapshot_shards.len(),
"map and snapshots must share shard count for zipped locking; see Shard Invariant on \
`snapshots` field"
);
let shard_indices: Vec<usize> = (0..map_shards.len()).collect();
parallel::for_each(&shard_indices, |&shard_idx| {
let map_shard = &map_shards[shard_idx];
let snap_shard = &snapshot_shards[shard_idx];
// Acquire in documented order: map first, snapshots second.
let map_guard = map_shard.write();
let mut snap_guard = snap_shard.write();
for (key, _) in snap_guard.drain() {
// The key is in this shard's `map` (or absent entirely), by the shard
// invariant above. Resolve directly in the held map guard rather than going
// through `self.map.get_mut`, which would attempt to re-acquire this shard's
// write lock and would also obscure the pairing.
let hash = self.map.hasher().hash_one(key);
if let Some(bucket) = map_guard.find(hash, |(k, _)| *k == key) {
// SAFETY: We hold `map_shard`'s write lock for the duration of this
// access, so the bucket pointer is valid and no other thread can alias it.
let (_, shared_value) = unsafe { bucket.as_mut() };
self.promote_during_snapshot_flags(shared_value.get_mut(), shard_idx);
}
}
// If we are saving a non-trivial amount of memory just clear it out.
if shard_guard.capacity() > 1024 {
shard_guard.shrink_to(0, |_entry| {
if snap_guard.capacity() > 1024 {
snap_guard.shrink_to(0, |_entry| {
unreachable!("nothing is hashed when resizing an empty shard to zero");
});
}
// Safety: shard_guard must outlive the iterator.
drop(shard_guard);
drop(snap_guard);
drop(map_guard);
});
}
......
use std::{
hash::{BuildHasher, Hash},
marker::PhantomData,
ops::{Deref, DerefMut},
sync::Arc,
};
......@@ -18,18 +19,29 @@ pub enum RefMut<'a, K, V> {
Shared {
_guard: Arc<RwLockWriteTableGuard<'a, K, V>>,
bucket: Bucket<(K, SharedValue<V>)>,
// Ensures that RefMut is !Send, preventing holding RefMut across .await points in async
// code, which can cause deadlocks. See safety comment on `unsafe impl Sync for RefMut`
// below.
phantom: std::marker::PhantomData<*const ()>,
},
}
// SAFETY: `RefMut` contains a raw `Bucket` pointer into a `DashMap` shard's `RawTable`.
// Sending/sharing is safe because:
// `RefMut` is intentionally **not** `Send`. While sending the guard across threads would be sound
// under the same reasoning that justifies `Sync` below, allowing `Send` makes it possible to hold
// a `RefMut` (and therefore a `StorageWriteGuard`) across an `.await` in async code, since the
// compiler will then accept the resulting future as `Send`. That pattern causes hard async
// deadlocks: the guard parks together with the suspended future and pins the shard's write lock,
// while every other tokio worker piles up trying to take the same lock — leaving no thread free
// to poll the parked future. Marking the type `!Send` makes the borrow checker reject those call
// sites at compile time.
// SAFETY (Sync): `RefMut` contains a raw `Bucket` pointer into a `DashMap` shard's `RawTable`.
// Sharing `&RefMut` is safe because:
// - `Simple` variant: The `Bucket` is accessed under an exclusive `RwLockWriteGuard` on a single
// shard. The guard provides exclusive access to all data in that shard.
// - `Shared` variant: The `Bucket` is accessed under an `Arc<RwLockWriteGuard>`. The
// `get_multiple_mut` function asserts that bucket pointers do not alias, so each `RefMut` has
// exclusive access to its bucket even when sharing a guard.
// - `K: Sync + V: Sync` bounds ensure the key and value types are safe to share across threads.
unsafe impl<K: Eq + Hash + Sync, V: Sync> Send for RefMut<'_, K, V> {}
unsafe impl<K: Eq + Hash + Sync, V: Sync> Sync for RefMut<'_, K, V> {}
impl<K: Eq + Hash, V> RefMut<'_, K, V> {
......@@ -161,10 +173,12 @@ where
RefMut::Shared {
_guard: guard.clone(),
bucket: bucket1,
phantom: PhantomData,
},
RefMut::Shared {
_guard: guard,
bucket: bucket2,
phantom: PhantomData,
},
)
} else {
......
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