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 -->
Showing
Please
register
or
sign in
to comment