Unverified Commit 8d8c0cd5 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbo-tasks] Experiment: capture snapshot pending bits under exclusion (#99747)

## Summary

This experiment builds on the copy-on-write snapshot design from #99649,
which is now on canary. It holds the operation exclusion while
`take_snapshot` runs, so the scan can move modified bits into new
`meta_snapshot_pending` / `data_snapshot_pending` bits safely.

Holding the exclusion means a task touched for the first time during the
snapshot doesn't need a `None` placeholder in `snapshots`. The map now
stores only copy-on-write `SnapshotItem`s, and `end_snapshot` just
leaves snapshot mode and clears the map. It no longer has to promote
during-snapshot flags or take paired shard locks.

Why: compare this simpler bookkeeping with #99649's approach, which
keeps the scan outside the exclusion. The trade-off is that operations
stay blocked during the O(N) capture scan. Encoding still happens later
in the snapshot iterators, after the exclusion is released. This design
was rejected earlier on #99649 ("delaying the snapshot to set these bits
is not acceptable"), so this PR is meant for comparison, not as the
assumed final direction.

How:
- The scan moves the modified bits into pending bits and records each
captured task.
- The first mutation of a captured task encodes all of its pending
categories before the mutation, so cases where different categories
change in different orders are covered.
- Pending bits stay set until the iterator yields the task. Undo and
eviction still see those bits until then.
- Shutdown drain mode still uses the modified bits directly.
- If persisting stops early (an error or a panic), each dropped shard
clears the pending bits of its captured tasks that weren't yielded,
before `end_snapshot` clears `snapshot_mode`. Pending bits never outlive
a snapshot, so `track_modification` decides copy-on-write from the
pending bits and the map alone, without reading `snapshot_mode`. The
iterator removes a task from its list only after it has finished with
that task, so a panic while encoding is cleaned up too.
- The snapshot callbacks take a `TaskDataCategory` (`Meta` / `Data` /
`All`) instead of a two-bool mask, because a persisted task always has
at least one category.
- The lower-layer changes are kept: the local copy-on-write buffer,
stats on encoded items, and `LastPersistenceStatus`.

## Verification

- `cargo test -p turbo-tasks-backend`
- `cargo test -p turbo-tasks-macros-tests`
- `cargo test -p turbo-tasks-backend --lib --features
verify_serialization,print_cache_item_size`
- `cargo clippy -p turbo-tasks-backend --all-targets -- -D warnings`,
with default features and with
`verify_serialization,print_cache_item_size`
- Mutation check: skipping copy-on-write for tasks with pending bits
made 6 tests fail. One of them shows the persisted meta bytes no longer
matching the captured meta.
- Failed-persist cleanup:
`dropping_shards_early_leaves_no_copy_on_write_items` and
`panic_while_encoding_clears_pending_flags` both failed before the
shard-drop cleanup existed. Emptying the `Drop` cleanup makes both fail
again. Removing a task from the list before encoding it makes only the
panic test fail. The panic test is skipped on wasm, which can't unwind;
the early-drop test still runs there.
- wasm: `cargo test -p turbo-tasks-backend --lib --target
wasm32-wasip1-threads` under `scripts/wasi-test-host` passes (108
passed, 14 ignored).
- Not run: benchmarks of how long the exclusion lasts or how long a full
snapshot takes. Holding the scan under the exclusion is a deliberate
trade-off here.
- Not run: `pnpm build-all` (this worktree has no `node_modules`).

<!-- NEXT_JS_LLM -->

<!-- fleet 98a896e8-00fa-4f81-97f0-48bd49e2a9a2 -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 0e912cb9
......@@ -1257,7 +1257,6 @@ impl TurboTasksBackend {
let (snapshot_guard, has_modifications) = self.storage.start_snapshot();
let snapshot_time = Instant::now();
drop(snapshot_phase);
if !has_modifications && gc_roots_to_persist.is_none() {
// No tasks modified since the last snapshot — drop the guard (which
......@@ -1413,18 +1412,21 @@ impl TurboTasksBackend {
let task_cache_stats: Mutex<FxHashMap<_, TaskCacheStats>> =
Mutex::new(FxHashMap::default());
// Encode each task's modified categories. We only encode categories with `modified` set,
// meaning the category was actually dirtied. Categories restored from disk but never
// modified don't need re-persisting since the on-disk version is still valid.
// Tasks that were modified again during snapshot mode were already encoded by
// Encode each task's captured categories (`category`). Only categories with `modified` set
// are captured, meaning the category was actually dirtied. Categories restored from disk
// but never modified don't need re-persisting since the on-disk version is still valid.
// Captured tasks that were modified again before being persisted were already encoded by
// `track_modification` (see `Storage::snapshots`), and are yielded without calling this.
let process = |task_id: TaskId, inner: &TaskStorage, buffer: &mut TurboBincodeBuffer| {
let process = |task_id: TaskId,
inner: &TaskStorage,
category: TaskDataCategory,
buffer: &mut TurboBincodeBuffer| {
debug_assert!(
!self.gc_enabled || inner.flags.deleted() || !inner.gc_collectible(),
"tasks scheduled for persistent must not be collectible, this implies a missed \
task during GC"
);
encode_snapshot_item(task_id, inner, buffer).unwrap_or_else(|err| {
encode_snapshot_item(task_id, inner, category, buffer).unwrap_or_else(|err| {
panic!(
"Serializing task {} failed: {:?}",
self.debug_get_task_description(task_id),
......@@ -1456,12 +1458,16 @@ impl TurboTasksBackend {
let _ = item;
};
// The scan captures the modified tasks, so it needs the exclusion (`snapshot_phase`).
// Encoding happens later, in the returned iterators, after the exclusion ends.
let task_snapshots = self.storage.take_snapshot(
&snapshot_phase,
snapshot_guard,
&process,
&inspect_snapshot_item,
reason.drain_entries(),
);
drop(snapshot_phase);
drop(snapshot_span);
let snapshot_duration = start.elapsed();
......@@ -4008,6 +4014,6 @@ mod persist_failure_tests {
task.flags.data_modified(),
"the second snapshot must not start"
);
assert!(!task.flags.any_modified_during_snapshot());
assert!(!task.flags.any_snapshot_pending());
}
}
......@@ -2367,6 +2367,7 @@ mod cell_data_tracking_tests {
use crate::{
backend::{
TaskDataCategory,
snapshot_coordinator::SnapshotCoordinator,
storage::{Storage, StorageOptions, encode_snapshot_item, encode_task_contents},
storage_schema::TaskStorageAccessors,
},
......@@ -2555,10 +2556,16 @@ mod cell_data_tracking_tests {
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let process = |_: TaskId, _: &TaskStorage, _: &mut TurboBincodeBuffer| -> SnapshotItem {
panic!("the pre-encoded snapshot item must be used")
};
let shards = storage.take_snapshot(snapshot_guard, &process, &|_| {}, false);
let process =
|_: TaskId,
_: &TaskStorage,
_: TaskDataCategory,
_: &mut TurboBincodeBuffer|
-> SnapshotItem { panic!("the pre-encoded snapshot item must be used") };
let coordinator = SnapshotCoordinator::new();
let phase = coordinator.try_begin_snapshot().unwrap();
let shards = storage.take_snapshot(&phase, snapshot_guard, &process, &|_| {}, false);
drop(phase);
{
let mut g = guard_for(&storage, task_id);
......@@ -2595,9 +2602,8 @@ mod cell_data_tracking_tests {
/// category that isn't part of the snapshot.
///
/// Meta is modified before the snapshot, data is clean. During the snapshot, data is modified
/// first and then meta. If the data modification only inserted a `None` marker, the meta
/// modification would find a marker already present and not copy either, so the snapshot
/// would persist the already mutated meta.
/// first and then meta. The data modification must copy the captured meta, even though data
/// itself wasn't captured; otherwise the snapshot would persist the already mutated meta.
#[tokio::test(flavor = "multi_thread")]
async fn modify_other_category_first_during_snapshot_preserves_snapshot_meta() {
let storage = Storage::new(StorageOptions::for_tests());
......@@ -2621,10 +2627,16 @@ mod cell_data_tracking_tests {
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
// Encodes the live state, like the backend does for tasks that weren't copied.
let process = |task_id: TaskId, task: &TaskStorage, buffer: &mut TurboBincodeBuffer| {
encode_snapshot_item(task_id, task, buffer).unwrap()
let process = |task_id: TaskId,
task: &TaskStorage,
category: TaskDataCategory,
buffer: &mut TurboBincodeBuffer| {
encode_snapshot_item(task_id, task, category, buffer).unwrap()
};
let shards = storage.take_snapshot(snapshot_guard, &process, &|_| {}, false);
let coordinator = SnapshotCoordinator::new();
let phase = coordinator.try_begin_snapshot().unwrap();
let shards = storage.take_snapshot(&phase, snapshot_guard, &process, &|_| {}, false);
drop(phase);
{
let mut g = guard_for(&storage, task_id);
......@@ -2649,7 +2661,7 @@ mod cell_data_tracking_tests {
let task = storage.access_mut(task_id);
assert!(task.flags.meta_modified());
assert!(task.flags.data_modified());
assert!(!task.flags.any_modified_during_snapshot());
assert!(!task.flags.any_snapshot_pending());
}
/// A pre-encoded (copy-on-write) item carries the cache size stats of the state it encoded,
......@@ -2665,10 +2677,16 @@ mod cell_data_tracking_tests {
}
let (snapshot_guard, _) = storage.start_snapshot();
let process = |_: TaskId, _: &TaskStorage, _: &mut TurboBincodeBuffer| -> SnapshotItem {
panic!("the pre-encoded snapshot item must be used")
};
let shards = storage.take_snapshot(snapshot_guard, &process, &|_| {}, false);
let process =
|_: TaskId,
_: &TaskStorage,
_: TaskDataCategory,
_: &mut TurboBincodeBuffer|
-> SnapshotItem { panic!("the pre-encoded snapshot item must be used") };
let coordinator = SnapshotCoordinator::new();
let phase = coordinator.try_begin_snapshot().unwrap();
let shards = storage.take_snapshot(&phase, snapshot_guard, &process, &|_| {}, false);
drop(phase);
// The tracked add copies the task (no children yet) before inserting the child.
{
......
......@@ -199,21 +199,25 @@ struct TaskStorageSchema {
#[field(storage = "flag", category = "transient")]
data_restoring: bool,
/// Whether meta was modified before snapshot mode was entered.
/// Whether meta has unpersisted modifications. Set by every persistable meta modification and
/// cleared when a snapshot captures the task.
#[field(storage = "flag", category = "transient")]
meta_modified: bool,
/// Whether data was modified before snapshot mode was entered.
/// Whether data has unpersisted modifications. Set by every persistable data modification and
/// cleared when a snapshot captures the task.
#[field(storage = "flag", category = "transient")]
data_modified: bool,
/// Whether meta was modified after snapshot mode was entered (snapshot taken).
/// Whether meta was captured by the in-progress snapshot and has not been persisted (encoded)
/// yet.
#[field(storage = "flag", category = "transient")]
meta_modified_during_snapshot: bool,
meta_snapshot_pending: bool,
/// Whether data was modified after snapshot mode was entered (snapshot taken).
/// Whether data was captured by the in-progress snapshot and has not been persisted (encoded)
/// yet.
#[field(storage = "flag", category = "transient")]
data_modified_during_snapshot: bool,
data_snapshot_pending: bool,
/// Whether dependencies have been prefetched.
#[field(storage = "flag", category = "transient")]
......@@ -434,9 +438,10 @@ impl TaskFlags {
}
}
/// Check if any snapshot flag is set
pub fn any_modified_during_snapshot(&self) -> bool {
self.meta_modified_during_snapshot() || self.data_modified_during_snapshot()
/// Check if the in-progress snapshot captured any category of this task that it has not
/// persisted yet.
pub fn any_snapshot_pending(&self) -> bool {
self.meta_snapshot_pending() || self.data_snapshot_pending()
}
/// Check if any modified flag is set
......@@ -459,26 +464,6 @@ impl TaskFlags {
SpecificTaskDataCategory::Data => self.set_data_modified(value),
}
}
/// Check if the specified category has a snapshot
pub fn is_modified_during_snapshot(&self, category: SpecificTaskDataCategory) -> bool {
match category {
SpecificTaskDataCategory::Meta => self.meta_modified_during_snapshot(),
SpecificTaskDataCategory::Data => self.data_modified_during_snapshot(),
}
}
/// Set the snapshot flag for the specified category
pub fn set_modified_during_snapshot(
&mut self,
category: SpecificTaskDataCategory,
value: bool,
) {
match category {
SpecificTaskDataCategory::Meta => self.set_meta_modified_during_snapshot(value),
SpecificTaskDataCategory::Data => self.set_data_modified_during_snapshot(value),
}
}
}
// =============================================================================
......@@ -604,15 +589,13 @@ impl TaskStorage {
// === Data evictability (independent) ===
// Data can be dropped if it's been restored from disk and hasn't been
// modified.
let data_evictable = flags.data_restored()
&& !flags.data_modified()
&& !flags.data_modified_during_snapshot();
let data_evictable =
flags.data_restored() && !flags.data_modified() && !flags.data_snapshot_pending();
// === Meta evictability (independent) ===
// Same semantics as data: flag checks only.
let meta_evictable = flags.meta_restored()
&& !flags.meta_modified()
&& !flags.meta_modified_during_snapshot();
let meta_evictable =
flags.meta_restored() && !flags.meta_modified() && !flags.meta_snapshot_pending();
// === Combined decision ===
(
......@@ -1214,8 +1197,8 @@ mod tests {
assert!(!storage.flags.data_restored());
assert!(!storage.flags.meta_modified());
assert!(!storage.flags.data_modified());
assert!(!storage.flags.meta_modified_during_snapshot());
assert!(!storage.flags.data_modified_during_snapshot());
assert!(!storage.flags.meta_snapshot_pending());
assert!(!storage.flags.data_snapshot_pending());
assert!(!storage.flags.prefetched());
// Test setting restored flags
......@@ -1231,10 +1214,10 @@ mod tests {
assert!(storage.flags.data_modified());
// Test setting snapshot flags
storage.flags.set_meta_modified_during_snapshot(true);
storage.flags.set_data_modified_during_snapshot(true);
assert!(storage.flags.meta_modified_during_snapshot());
assert!(storage.flags.data_modified_during_snapshot());
storage.flags.set_meta_snapshot_pending(true);
storage.flags.set_data_snapshot_pending(true);
assert!(storage.flags.meta_snapshot_pending());
assert!(storage.flags.data_snapshot_pending());
// Test prefetched flag
storage.flags.set_prefetched(true);
......
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