Unverified Commit ef247bc8 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbopack] Remove per-shard modified counts from snapshots (#99955)

## Summary

Removes the per-shard modified counts from Turbopack's task storage.
Each snapshot now scans every shard of the task map instead of skipping
shards that report no modified tasks, and `track_modification` and its
undo no longer update a shared atomic counter.

The counter was there to solve two problems.

- **Skipping unmodified shards.** In a warm `next build` every snapshot
found modified tasks in all 4096 shards, so the counts never skipped
one. In a cold build every task is modified anyway.
- **Making a no-op snapshot cheap.** The persistence loop only snapshots
after enough foreground work has accumulated (1s by default), so a full
scan always follows real work. That makes it unlikely to be a no-op, and
limits how often it can run. Plus in dev `eviction` means unmodified
tasks will be removed from the map, so it will tend to be the case that
resident tasks are dirty

## Verification

Warm `next build` of vercel-site over 21 commits, 2 repeats, GC on. Base
is #99902's head, and the two arms differ only in this change. Both were
built with `build-native --release`, installed through `pack-next`, and
interleaved per commit. Snapshot phases were timed with a bench-only log
that isn't part of this PR.

| warm (40 pairs) | with counts | without | delta [95% CI] |
|---|---|---|---|
| wall | 52.26s | 52.59s | +0.33s [-1.09, +1.75] |
| user CPU | 155.0s | 154.0s | -1.0s [-5.3, +3.4] |
| snapshot capture | 177.9ms | 173.2ms | -4.7ms [-18.9, +9.5] |
| max RSS | 10.34 GB | 10.38 GB | |

Every interval includes zero. Tests that asserted on the counts were
reduced to the behaviour they still describe.

<!-- NEXT_JS_LLM -->
parent 5b370524
......@@ -1253,18 +1253,10 @@ impl TurboTasksBackend {
debug_assert!(self.should_persist());
// Checking after the exclusion begins ensures no concurrent increments can race.
let (snapshot_guard, has_modifications) = self.storage.start_snapshot();
let snapshot_guard = self.storage.start_snapshot();
let snapshot_time = Instant::now();
if !has_modifications && gc_roots_to_persist.is_none() {
// No tasks modified since the last snapshot — drop the guard (which
// calls end_snapshot) and skip the expensive O(N) scan.
drop(snapshot_guard);
return Ok(Some((start, false, gc_outcome)));
}
#[cfg(feature = "print_cache_item_size")]
#[derive(Default)]
struct TaskCacheStats {
......@@ -1474,9 +1466,8 @@ impl TurboTasksBackend {
let task_count = task_snapshots.len();
if task_snapshots.is_empty() && gc_roots_to_persist.is_none() {
// Rare: the modified counts are out of sync with the modified persistable tasks, which
// only happens if every modified task was both new and deleted.
std::hint::cold_path();
// No task was modified since the last snapshot (or every modified task was both new
// and deleted), so there is nothing to write.
return Ok(Some((snapshot_time, false, gc_outcome)));
}
......
......@@ -2550,8 +2550,7 @@ mod cell_data_tracking_tests {
.unwrap()
};
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let snapshot_guard = storage.start_snapshot();
let process =
|_: TaskId,
_: &TaskStorage,
......@@ -2620,8 +2619,7 @@ mod cell_data_tracking_tests {
.unwrap()
};
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let snapshot_guard = storage.start_snapshot();
// Encodes the live state, like the backend does for tasks that weren't copied.
let process = |task_id: TaskId,
task: &TaskStorage,
......
......@@ -5,12 +5,11 @@ use std::{
ops::{Deref, DerefMut},
sync::{
Arc,
atomic::{AtomicBool, AtomicU64, Ordering},
atomic::{AtomicBool, Ordering},
},
};
use anyhow::{Context, Result};
use crossbeam_utils::CachePadded;
use hashbrown::hash_table;
use smallvec::SmallVec;
use thread_local::ThreadLocal;
......@@ -154,13 +153,11 @@ impl SpecificTaskDataCategory {
pub enum TrackOutcome {
/// Nothing was tracked: the category was already modified. Undo is a no-op.
NoChange,
/// `modified(category)` was set. `bumped` is true if this call also incremented the per-shard
/// modified counter (i.e. the task had no prior modifications). `inserted_snapshot` is true if
/// this call also inserted the task's pre-mutation encoded state into the `snapshots` map
/// (the task was captured by the in-progress snapshot and not persisted yet).
/// `modified(category)` was set. `inserted_snapshot` is true if this call also inserted the
/// task's pre-mutation encoded state into the `snapshots` map (the task was captured by the
/// in-progress snapshot and not persisted yet).
Tracked {
category: SpecificTaskDataCategory,
bumped: bool,
inserted_snapshot: bool,
},
}
......@@ -319,16 +316,6 @@ fn snapshot_item_stats(inner: &TaskStorage) -> crate::backing_storage::SnapshotI
pub struct Storage {
snapshot_mode: AtomicBool,
/// Per-shard counts of tasks with modified flags set. Incremented when a task
/// transitions from unmodified to modified. Reset to zero when `take_snapshot` captures the
/// shard's modified tasks (clearing their modified flags). Used to skip unmodified
/// shards in `take_snapshot`, avoiding unnecessary iteration and enabling early returns
///
/// Indexed by `map.determine_shard(map.hash_usize(&key))` and guaranteed by construction so
/// that `shard_modified_counts.len()==map.shards().len()`
///
/// Should only be modified while holding the corresponding dashmap shard lock.
shard_modified_counts: Box<[CachePadded<AtomicU64>]>,
/// Copy-on-write snapshots of tasks that are currently enqueued for persistence (they have
/// `*_snapshot_pending` flags) and then modified.
/// Captured as `SnapshotItem` to defend against interior mutability in tasks carrying `State`.
......@@ -367,7 +354,7 @@ pub struct Storage {
/// Options for [`Storage::new`].
#[derive(Debug, Clone, Copy)]
pub struct StorageOptions {
/// Number of shards of the task map (and of the per-shard modified counters).
/// Number of shards of the task map.
pub shard_amount: usize,
/// Preallocate a small task map instead of a large one (e.g. for tests or short-lived
/// instances).
......@@ -411,13 +398,8 @@ impl Storage {
Default::default(),
shard_amount,
);
let shard_modified_counts = (0..shard_amount)
.map(|_| CachePadded::new(AtomicU64::new(0)))
.collect::<Vec<_>>()
.into_boxed_slice();
Self {
snapshot_mode: AtomicBool::new(false),
shard_modified_counts,
snapshots: FxDashMap::with_capacity_and_hasher_and_shard_amount(
// We expect very few updates to this map since it will only happen when updates
// race with snapshots. This never happens in a build and only rarely happens in
......@@ -432,12 +414,6 @@ impl Storage {
}
}
/// Returns the shard index for the given key in the `map` DashMap.
fn shard_index(&self, key: &TaskId) -> usize {
let hash = self.map.hash_usize(key);
self.map.determine_shard(hash)
}
/// 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`.
......@@ -500,23 +476,11 @@ impl Storage {
) -> Vec<SnapshotShard<'l, P, I>> {
let guard = Arc::new(guard);
let shards: Vec<_> = self.map.shards().iter().enumerate().collect();
let shards: Vec<_> = self.map.shards().iter().collect();
// The number of shards is much larger than the number of threads, so the effect of the
// locks held is negligible.
parallel::map_collect::<_, _, Vec<_>>(&shards, |&(shard_idx, shard)| {
// Check how many modifications there are in this shard. Operations are excluded, so
// there are no racing writes and we can reset the count: every modified task in the
// shard is captured (and its modified flags cleared) below.
let modified_count = self.shard_modified_counts[shard_idx].swap(0, Ordering::Relaxed);
if modified_count == 0 && !drain_entries {
// Nothing to persist in this shard and we're keeping the map, so skip the scan.
// TODO: when not draining but eviction is enabled we should run that logic here as
// well
return None;
}
parallel::map_collect::<_, _, Vec<_>>(&shards, |&shard| {
// Scan the shard once, building the work this shard's iterator will perform. The two
// modes carry different data so that `next` has no per-item `drain` branch:
// - keep mode collects the modified `TaskId`s and looks them up again while iterating.
......@@ -547,18 +511,13 @@ impl Storage {
// as it is serialized, and the shard's table allocation is released here.
ShardWork::Drain(std::mem::take(&mut *shard_guard).into_iter())
} else {
let mut modified = Vec::with_capacity(modified_count as usize);
let mut skipped_deleted_new = 0u64;
let mut modified = Vec::new();
for (key, task) in shard_guard.iter_mut() {
if is_deleted_new_task(task) {
// Nothing on disk to write or tombstone. The shard's count was already
// reset above, so clearing the flags is all the bookkeeping needed;
// eviction frees the entry.
if task.flags.any_modified() {
skipped_deleted_new += 1;
task.flags.set_meta_modified(false);
task.flags.set_data_modified(false);
}
// Nothing on disk to write or tombstone. Clear its flags and let
// eviction free the entry.
task.flags.set_meta_modified(false);
task.flags.set_data_modified(false);
continue;
}
// Only check modified flags — transient tasks never have modified flags set
......@@ -582,13 +541,7 @@ impl Storage {
modified.push(*key);
}
}
// Empty when every modified task in the shard was a deleted new task.
if modified.is_empty() {
debug_assert_eq!(
skipped_deleted_new, modified_count,
"a shard with no persistable modified tasks must only have counted \
deleted new tasks"
);
return None;
}
ShardWork::Keep(modified)
......@@ -609,26 +562,11 @@ impl Storage {
}
/// Enter snapshot mode and return a guard that will call `end_snapshot` on drop.
///
/// Returns whether any shard has modifications. Per-shard counts are reset
/// in `take_snapshot` as each shard is captured, not here — resetting eagerly
/// would lose the counts `take_snapshot` uses to skip unmodified shards.
///
/// 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(&self) -> SnapshotGuard<'_> {
// Enter snapshot mode so track_modification copies captured tasks
// (copy-on-write) before mutating them.
self.snapshot_mode.store(true, Ordering::Release);
// Check if any shard has modifications. Don't reset counts here —
// take_snapshot resets per-shard counts as it captures each shard,
// and uses them to skip shards without modifications.
let has_modifications = self
.shard_modified_counts
.iter()
.any(|c| c.load(Ordering::Relaxed) > 0);
(SnapshotGuard::new(self), has_modifications)
SnapshotGuard::new(self)
}
/// End snapshot mode.
......@@ -814,15 +752,7 @@ impl Storage {
return true;
}
if task.flags.deleted() {
if task.flags.new_task() {
// Never persisted, so nothing on disk to protect. It is still counted as
// modified if no snapshot skipped it since, e.g. after an interrupted GC
// pass.
if task.flags.any_modified() {
self.shard_modified_counts[self.shard_index(task_id)]
.fetch_sub(1, Ordering::Relaxed);
}
} else if task.flags.any_modified() {
if !task.flags.new_task() && task.flags.any_modified() {
// Its tombstone is still pending. Its neighbours' halves of the torn-down
// edges reach disk with the next snapshot, so dropping it now would leave
// its last snapshot live on disk, to be restored later as a live task with
......@@ -1014,15 +944,9 @@ impl StorageWriteGuard<'_> {
// when their shard drops, before the snapshot ends.
let inserted_snapshot =
self.inner.flags.any_snapshot_pending() && self.maybe_encode_for_snapshot();
let bumped = !self.inner.flags.any_modified();
if bumped {
let shard_idx = self.storage.shard_index(self.inner.key());
self.storage.shard_modified_counts[shard_idx].fetch_add(1, Ordering::Relaxed);
}
self.inner.flags.set_modified(category, true);
TrackOutcome::Tracked {
category,
bumped,
inserted_snapshot,
}
}
......@@ -1058,23 +982,18 @@ impl StorageWriteGuard<'_> {
/// map shard write lock held continuously in between — i.e. `track_modification`, the mutation,
/// and `undo_track_modification` all run within one guard's lifetime. The guard holds its shard
/// write lock for its whole lifetime, so this guarantees no other thread observed the tracked
/// state, and that `bumped` / `inserted_snapshot` still describe reality (the counter and
/// `snapshots` entry are only mutated under that lock). Because those flags record whether
/// *this* call created the state, undo never clears a flag, counter, or snapshot entry that a
/// state, and that `inserted_snapshot` still describes reality (the `snapshots` entry is only
/// mutated under that lock). Because it records whether *this* call created the state, undo
/// never clears a flag or snapshot entry that a
/// prior modification owns.
pub fn undo_track_modification(&mut self, outcome: TrackOutcome) {
match outcome {
TrackOutcome::NoChange => {}
TrackOutcome::Tracked {
category,
bumped,
inserted_snapshot,
} => {
self.inner.flags.set_modified(category, false);
if bumped {
let shard_idx = self.storage.shard_index(self.inner.key());
self.storage.shard_modified_counts[shard_idx].fetch_sub(1, Ordering::Relaxed);
}
if inserted_snapshot {
self.storage.snapshots.remove(self.inner.key());
}
......@@ -1325,8 +1244,6 @@ impl<P, I> Drop for SnapshotShard<'_, P, I> {
#[cfg(test)]
mod tests {
use std::sync::atomic::Ordering;
use turbo_bincode::TurboBincodeBuffer;
use turbo_tasks::TaskId;
......@@ -1357,8 +1274,7 @@ mod tests {
}
/// A never-persisted task that GC deleted has nothing on disk, so eviction drops it even while
/// it is still modified (no snapshot ran, as after an interrupted GC pass) and releases its
/// modified count.
/// it is still modified (no snapshot ran, as after an interrupted GC pass).
// `evict_after_snapshot` uses `parallel::map_collect`, which requires a multi-threaded runtime.
#[tokio::test(flavor = "multi_thread")]
async fn gc_deleted_new_task_is_evicted_while_modified() {
......@@ -1370,18 +1286,9 @@ mod tests {
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "teardown");
guard.flags.set_deleted(true);
}
let shard = storage.shard_index(&task_id);
assert_eq!(
storage.shard_modified_counts[shard].load(Ordering::Relaxed),
1
);
storage.evict_after_snapshot(None);
assert!(storage.with_task(task_id, |_| ()).is_none());
assert_eq!(
storage.shard_modified_counts[shard].load(Ordering::Relaxed),
0
);
}
/// A snapshot skips a never-persisted task that GC deleted: there is nothing on disk to write
......@@ -1397,8 +1304,7 @@ mod tests {
guard.flags.set_deleted(true);
}
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let snapshot_guard = storage.start_snapshot();
let shards = take_snapshot(
&storage,
snapshot_guard,
......@@ -1411,10 +1317,6 @@ mod tests {
let guard = storage.access_mut(task_id);
assert!(!guard.flags.any_modified());
assert!(!guard.flags.any_snapshot_pending());
assert_eq!(
storage.shard_modified_counts[storage.shard_index(&task_id)].load(Ordering::Relaxed),
0
);
}
/// A persisted task that GC deleted keeps its tombstone pending until a snapshot writes it, so
......@@ -1484,7 +1386,7 @@ mod tests {
/// forward to the next cycle.
///
/// Sequence of events:
/// 1. Task is modified (data_modified = true) → added to shard_modified_counts.
/// 1. Task is modified (data_modified = true).
/// 2. `start_snapshot` puts us in snapshot mode.
/// 3. `take_snapshot` captures the task: `data_modified` moves to `data_snapshot_pending`.
/// 4. **Between capture and iteration**: `track_modification` is called on the same category.
......@@ -1506,8 +1408,7 @@ mod tests {
}
// Step 2: enter snapshot mode.
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let snapshot_guard = storage.start_snapshot();
// Step 3: `take_snapshot` captures the task.
let shards = take_snapshot(
......@@ -1547,14 +1448,6 @@ mod tests {
assert!(guard.flags.data_modified());
assert!(!guard.flags.any_snapshot_pending());
}
// The new modification must be reflected in shard_modified_counts so the next
// snapshot cycle picks it up. Verify by starting another snapshot.
let (_guard2, has_modifications) = storage.start_snapshot();
assert!(
has_modifications,
"shard_modified_counts must count the modification made after the capture"
);
}
/// A task modified in one category before a snapshot, then modified in a *different* category
......@@ -1582,8 +1475,7 @@ mod tests {
}
// Step 2: enter snapshot mode.
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let snapshot_guard = storage.start_snapshot();
// Step 3: take_snapshot captures the task.
let shards = take_snapshot(
......@@ -1619,13 +1511,6 @@ mod tests {
assert!(guard.flags.data_modified());
assert!(!guard.flags.any_snapshot_pending());
}
// Next snapshot cycle must pick up data_modified.
let (_guard2, has_modifications) = storage.start_snapshot();
assert!(
has_modifications,
"shard_modified_counts must count the data modification made after the capture"
);
}
/// With `drain_entries = true` (shutdown path), the modified entries are moved out of the map
......@@ -1644,8 +1529,7 @@ mod tests {
}
assert!(storage.map.get(&task_id).is_some());
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let snapshot_guard = storage.start_snapshot();
// Take the snapshot in drain mode.
let shards = take_snapshot(
......@@ -1693,8 +1577,7 @@ mod tests {
.sum();
assert!(grown_capacity >= task_ids.len());
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let snapshot_guard = storage.start_snapshot();
let shards = take_snapshot(
&storage,
......@@ -1743,8 +1626,7 @@ mod tests {
let _ = storage.access_mut(unmodified_id);
assert!(storage.map.get(&unmodified_id).is_some());
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let snapshot_guard = storage.start_snapshot();
let shards = take_snapshot(
&storage,
......@@ -1788,13 +1670,6 @@ mod tests {
assert!(!guard.flags.data_modified());
assert!(!guard.flags.any_modified());
}
// Counter is back to zero: the next snapshot sees no modifications.
let (_guard, has_modifications) = storage.start_snapshot();
assert!(
!has_modifications,
"undo must decrement the shard counter so no modifications remain"
);
}
/// A second track on an already-modified category returns `NoChange`; undoing it is a no-op and
......@@ -1836,8 +1711,6 @@ mod tests {
}
// Data is still modified, so the counter is still non-zero.
let (_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
}
/// A task wholly outside the snapshot (not captured) that is modified during the snapshot is
......@@ -1855,8 +1728,7 @@ mod tests {
// Insert the task (unmodified) so it exists in the map.
let _ = storage.access_mut(task_id);
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let snapshot_guard = storage.start_snapshot();
let shards = take_snapshot(
&storage,
snapshot_guard,
......@@ -1871,7 +1743,6 @@ mod tests {
assert!(matches!(
outcome,
TrackOutcome::Tracked {
bumped: true,
inserted_snapshot: false,
..
}
......@@ -1879,17 +1750,9 @@ mod tests {
assert!(guard.flags.data_modified());
assert!(!guard.flags.any_snapshot_pending());
assert!(!storage.snapshots.contains_key(&task_id));
assert_eq!(
storage.shard_modified_counts[storage.shard_index(&task_id)].load(Ordering::Relaxed),
1
);
guard.undo_track_modification(outcome);
assert!(!guard.flags.data_modified());
assert_eq!(
storage.shard_modified_counts[storage.shard_index(&task_id)].load(Ordering::Relaxed),
0
);
drop(guard);
let items: Vec<_> = shards.into_iter().flatten().collect();
assert_eq!(items.len(), 1);
......@@ -1909,7 +1772,7 @@ mod tests {
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
}
let (snapshot_guard, _) = storage.start_snapshot();
let snapshot_guard = storage.start_snapshot();
let shards = take_snapshot(
&storage,
snapshot_guard,
......@@ -1924,7 +1787,6 @@ mod tests {
assert!(matches!(
outcome,
TrackOutcome::Tracked {
bumped: true,
inserted_snapshot: true,
..
}
......@@ -1942,10 +1804,6 @@ mod tests {
"undo must remove the pre-mutation item it inserted"
);
}
assert_eq!(
storage.shard_modified_counts[storage.shard_index(&task_id)].load(Ordering::Relaxed),
0
);
// The captured state is still persisted (from the live task, since no entry remains).
let items: Vec<_> = shards.into_iter().flatten().collect();
......@@ -1965,7 +1823,7 @@ mod tests {
let _ = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
}
let (snapshot_guard, _) = storage.start_snapshot();
let snapshot_guard = storage.start_snapshot();
let process = |id: TaskId,
inner: &TaskStorage,
category: TaskDataCategory,
......@@ -1981,12 +1839,6 @@ mod tests {
assert!(!guard.flags.data_snapshot_pending());
assert!(guard.flags.new_task());
}
assert!(
storage
.shard_modified_counts
.iter()
.all(|c| c.load(Ordering::Relaxed) == 0)
);
let items: Vec<_> = shards.into_iter().flatten().collect();
assert_eq!(items.len(), 1);
......@@ -2012,7 +1864,7 @@ mod tests {
}
let frozen = task_ids[0];
let (snapshot_guard, _) = storage.start_snapshot();
let snapshot_guard = storage.start_snapshot();
let shards = take_snapshot(
&storage,
snapshot_guard,
......@@ -2084,7 +1936,7 @@ mod tests {
dummy_process(task_id, inner, category, buffer)
};
let (snapshot_guard, _) = storage.start_snapshot();
let snapshot_guard = storage.start_snapshot();
let shards = take_snapshot(&storage, snapshot_guard, &process, &noop_inspect, false);
let mut panicked = false;
for shard in shards {
......@@ -2146,8 +1998,7 @@ mod tests {
.unwrap()
};
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let snapshot_guard = storage.start_snapshot();
let process = |id: TaskId,
inner: &TaskStorage,
category: TaskDataCategory,
......
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