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

[lts-active] turbo-tasks snapshot consistency fixes (#99644, #99732, #99649) (#100002)

## Summary

Backports three snapshot-consistency fixes to `releases/lts/active`, in
canary order:

- #99644 turbo-tasks: bincode-encode copy-on-write snapshots instead of
cloning
- #99732 turbo-tasks: disable persisting after a failed snapshot
- #99649 turbo-tasks: copy tasks on their first modification during a
snapshot

16.4.0 can persist inconsistent task state when a mutation races a
background snapshot. The main case is #99649. A task that is meta-dirty
and data-clean when the snapshot starts, then writes data before meta,
has its live (post-mutation) meta persisted. One example is an
invalidated task that re-runs while an idle snapshot is writing.
`children` and `parent_count` are both meta, so the cache on disk can
list a child edge without the child's matching `parent_count`. `next
dev` doesn't persist on shutdown, so the next session restores that
state. When the parent later drops the edge, the server aborts with
`parent_count underflow: decremented below the number of persistent
parents`. We have one report of this from a 16.4.0 dev run.

The cherry-picks apply without conflicts. The six touched files are
identical to `canary` at #99649.

## Verification

- `cargo test -p turbo-tasks-backend --lib` on this branch: 119 passed.
This includes #99649's regression test
`modify_other_category_first_during_snapshot_preserves_snapshot_meta`
and #99732's `failed_persist_disables_persisting`.
- Locally on macOS this needed
`CARGO_TARGET_AARCH64_APPLE_DARWIN_LINKER=cc` and `RUSTFLAGS` set to the
repo's shared flags without `--icf=all`. The branch's pinned
`nightly-2026-08-20` ships a `rust-lld` that can't read the current
macOS SDK's `.tbd` files. This is unrelated to the change, and CI uses
its normal config.

<!-- NEXT_JS_LLM -->

---------
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>
Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
parent 7217011a
......@@ -22,7 +22,7 @@ use std::{
time::SystemTime,
};
use anyhow::{Context, Result, bail};
use anyhow::{Result, bail};
use auto_hash_map::{AutoMap, AutoSet};
use gc::DEFAULT_GC_ROOT_TTL;
pub use gc::{GcPassResult, GcStats, TtlCounter};
......@@ -32,7 +32,7 @@ use rustc_hash::{FxHashMap, FxHashSet, FxHasher};
use smallvec::{SmallVec, smallvec};
use tokio::time::{Duration, Instant};
use tracing::{Span, field::display, trace_span};
use turbo_bincode::{TurboBincodeBuffer, new_turbo_bincode_decoder, new_turbo_bincode_encoder};
use turbo_bincode::TurboBincodeBuffer;
use turbo_tasks::{
CellId, DynTaskInputsStorage, RawVc, RawVcUnpacked, ReadCellOptions, ReadCellTracking,
ReadConsistency, ReadOutcome, ReadOutputOptions, ReadTracking, SharedReference,
......@@ -70,10 +70,10 @@ use crate::{
make_task_dirty_internal, prepare_new_children, update_cell,
},
snapshot_coordinator::{OperationGuard, SlowSettle, SnapshotCoordinator},
storage::Storage,
storage::{Storage, StorageOptions, encode_snapshot_item},
storage_schema::{TaskStorage, TaskStorageAccessors},
},
backing_storage::{SnapshotItem, compute_task_type_hash},
backing_storage::SnapshotItem,
data::{
ActivenessState, CellRef, CollectibleRef, CollectiblesRef, Dirtyness, InProgressCellState,
InProgressState, InProgressStateInner, OutputValue, TransientTask,
......@@ -229,6 +229,17 @@ impl SnapshotReason {
}
}
/// The outcome of the last persistence cycle. The backend starts at `Ok` in its constructor.
///
/// `Failed` is sticky: a failed persist (an error or a panic) leaves the task graph and the
/// database out of sync (e.g. `save_snapshot` already consumed `persisted_task_cache_log`
/// entries), so persisting stays disabled for the rest of the session.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LastPersistenceStatus {
Ok,
Failed,
}
pub struct TurboTasksBackend {
options: BackendOptions,
......@@ -246,7 +257,9 @@ pub struct TurboTasksBackend {
/// `begin_exclusion` asserts that exclusive phases don't overlap; this mutex
/// enforces that contract for our callers (background loop and
/// `stop_and_wait`).
snapshot_in_progress: Mutex<()>,
///
/// Also holds the [`LastPersistenceStatus`], which disables persisting after a failure.
snapshot_in_progress: Mutex<LastPersistenceStatus>,
/// Experimental feature to enable dead tasks to be deleted from storage and ram.
gc_enabled: bool,
......@@ -349,9 +362,12 @@ impl TurboTasksBackend {
TaskId::try_from(TRANSIENT_TASK_BIT).unwrap(),
TaskId::MAX,
),
storage: Storage::new(shard_amount, small_preallocation),
storage: Storage::new(StorageOptions {
shard_amount,
small_preallocation,
}),
snapshot_coord: SnapshotCoordinator::new(),
snapshot_in_progress: Mutex::new(()),
snapshot_in_progress: Mutex::new(LastPersistenceStatus::Ok),
stopping: RwLock::new(false),
stopping_event: Event::new(|| || "TurboTasksBackend::stopping_event".to_string()),
idle_start_event: Event::new(|| || "TurboTasksBackend::idle_start_event".to_string()),
......@@ -426,8 +442,9 @@ impl TurboTasksBackend {
let snapshot_result = self.snapshot_and_persist(None, SnapshotReason::Test, turbo_tasks);
let (had_new_data, gc_outcome) = match snapshot_result {
Ok(Some((_, new_data, gc_outcome))) => (new_data, gc_outcome),
Ok(None) => unreachable!("test snapshots wait for operations to settle"),
Err(_) => {
// Test snapshots wait for operations to settle, so `None` means persisting is
// disabled after an earlier failure.
Ok(None) | Err(_) => {
// Snapshot/persist failed — skip eviction since the data may not
// be on disk yet. Evicting now could lose in-memory state that
// can't be restored.
......@@ -1150,24 +1167,49 @@ impl TurboTasksBackend {
/// Runs a persistence cycle
///
/// Returns `None` if the cycle was skipped because operations were active and the reason
/// doesn't [wait for them](SnapshotReason::waits_for_operations). Otherwise returns
/// Returns `None` if the cycle was skipped: persisting is disabled after an earlier failure, or
/// operations were active and the reason doesn't
/// [wait for them](SnapshotReason::waits_for_operations). Otherwise returns
/// `(snapshot_start, had_new_data, gc_outcome)`. `gc_outcome` is `None` when GC is
/// disabled; it is returned rather than stashed on `self` so a test can inspect the pass it
/// just triggered without the backend carrying test-only state. Production reads the same
/// numbers off the `gc` span.
///
/// A failure (an error or a panic) disables persisting for the rest of the session: later
/// calls return `None` without starting a snapshot or GC.
#[allow(clippy::type_complexity, reason = "only used for tests")]
fn snapshot_and_persist(
&self,
parent_span: Option<tracing::Id>,
reason: SnapshotReason,
turbo_tasks: &TurboTasks<TurboTasksBackend>,
) -> Result<Option<(Instant, bool, Option<(GcStats, GcPassResult)>)>> {
// Serialize snapshots and GC for the entire persistence cycle.
let mut status = self.snapshot_in_progress.lock();
if *status == LastPersistenceStatus::Failed {
return Ok(None);
}
// Mark the cycle failed up front and only reset it on success: encoding failures panic,
// and a panic unwinds past any post-call check (`parking_lot` mutexes don't poison).
*status = LastPersistenceStatus::Failed;
let result = self.snapshot_and_persist_locked(parent_span, reason, turbo_tasks);
if result.is_ok() {
*status = LastPersistenceStatus::Ok;
}
result
}
/// [`Self::snapshot_and_persist`], called while holding `snapshot_in_progress`.
#[allow(clippy::type_complexity, reason = "only used for tests")]
fn snapshot_and_persist_locked(
&self,
parent_span: Option<tracing::Id>,
reason: SnapshotReason,
turbo_tasks: &TurboTasks<TurboTasksBackend>,
) -> Result<Option<(Instant, bool, Option<(GcStats, GcPassResult)>)>> {
let snapshot_span =
tracing::trace_span!(parent: parent_span.clone(), "snapshot", reason = reason.as_str())
.entered();
// Serialize snapshots and GC for the entire persistence cycle.
let _snapshot_in_progress = self.snapshot_in_progress.lock();
// One exclusion covers the GC pass and the snapshot that follows it, so the collected
// tasks' tombstones (derived from the `deleted` flag) ride this same commit and no
......@@ -1296,8 +1338,8 @@ impl TurboTasksBackend {
self.meta_count += 1;
}
fn add_counts(&mut self, storage: &TaskStorage) {
let counts = storage.meta_counts();
fn add_counts(&mut self, stats: &crate::backing_storage::SnapshotItemStats) {
let counts = &stats.counts;
self.upper_count += counts.upper;
self.collectibles_count += counts.collectibles;
self.aggregated_collectibles_count += counts.aggregated_collectibles;
......@@ -1305,21 +1347,7 @@ impl TurboTasksBackend {
self.followers_count += counts.followers;
self.collectibles_dependents_count += counts.collectibles_dependents;
self.aggregated_dirty_containers_count += counts.aggregated_dirty_containers;
if let Some(output) = storage.get_output() {
use turbo_bincode::turbo_bincode_encode;
self.output_size += turbo_bincode_encode(&output)
.map(|data| data.len())
.unwrap_or(0);
}
}
/// Returns the task name used as the stats grouping key.
fn task_name(storage: &TaskStorage) -> String {
storage
.get_persistent_task_type()
.map(|t| t.to_string())
.unwrap_or_else(|| "<unknown>".to_string())
self.output_size += stats.output_size;
}
/// Returns the primary sort key: compressed total when
......@@ -1388,120 +1416,52 @@ impl TurboTasksBackend {
// 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.
// For tasks accessed during snapshot mode, a frozen copy was made and its `modified`
// flags were copied from the live task at snapshot creation time, reflecting which
// categories were dirtied before the snapshot was taken.
// Tasks that were modified again during snapshot mode 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 encode_category = |task_id: TaskId,
data: &TaskStorage,
category: SpecificTaskDataCategory,
buffer: &mut TurboBincodeBuffer|
-> Option<TurboBincodeBuffer> {
match encode_task_data(task_id, data, category, buffer) {
Ok(encoded) => {
#[cfg(feature = "print_cache_item_size")]
{
let mut stats = task_cache_stats.lock();
let entry = stats.entry(TaskCacheStats::task_name(inner)).or_default();
match category {
SpecificTaskDataCategory::Meta => entry.add_meta(&encoded),
SpecificTaskDataCategory::Data => entry.add_data(&encoded),
}
}
Some(encoded)
}
Err(err) => {
panic!(
"Serializing task {} failed ({:?}): {:?}",
self.debug_get_task_description(task_id),
category,
err
);
}
}
};
if task_id.is_transient() {
unreachable!("transient task_ids should never be enqueued to be persisted");
}
if self.gc_enabled {
if inner.flags.deleted() {
debug_assert!(
!inner.flags.new_task(),
"a scanned GC-deleted task must be persisted; new tasks are discarded by \
GC"
);
let task_type_hash = compute_task_type_hash(
inner
.get_persistent_task_type()
.expect("a GC-deleted task must have a task type"),
);
return SnapshotItem::Delete {
task_id,
task_type_hash,
};
} else {
debug_assert!(
!inner.gc_collectible(),
"tasks scheduled for persistent must not be collectible, this implies a \
missed task during GC"
);
}
} else {
debug_assert!(
!inner.flags.deleted(),
"Deleted flags should only be set by GC and it is disabled"
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| {
panic!(
"Serializing task {} failed: {:?}",
self.debug_get_task_description(task_id),
err
)
}
let encode_meta = inner.flags.meta_modified();
let encode_data = inner.flags.data_modified();
})
};
// Called for every item persisted, including the ones encoded by `track_modification`.
// The stats were captured when the item was encoded.
let inspect_snapshot_item = |item: &SnapshotItem| {
#[cfg(feature = "print_cache_item_size")]
if encode_data || encode_meta {
task_cache_stats
.lock()
.entry(TaskCacheStats::task_name(inner))
.or_default()
.add_counts(inner);
}
let meta = if encode_meta {
encode_category(task_id, inner, SpecificTaskDataCategory::Meta, buffer)
} else {
None
};
let data = if encode_data {
encode_category(task_id, inner, SpecificTaskDataCategory::Data, buffer)
} else {
None
};
let task_type_hash = if inner.flags.new_task() {
let task_type = inner.get_persistent_task_type().expect(
"It is not possible for a new_task to not have a persistent_task_type. Task \
creation for persistent tasks uses a single ExecutionContextImpl for \
creating the task (which sets new_task) and connect_child (which sets \
persistent_task_type) and take_snapshot waits for all operations to complete \
before we start snapshotting. So task creation will always set the \
task_type.",
);
Some(compute_task_type_hash(task_type))
} else {
None
};
SnapshotItem::Put {
task_id,
meta,
data,
task_type_hash,
if let SnapshotItem::Put {
meta, data, stats, ..
} = item
&& (meta.is_some() || data.is_some())
{
let mut task_cache_stats = task_cache_stats.lock();
let entry = task_cache_stats.entry(stats.task_name.clone()).or_default();
entry.add_counts(stats);
if let Some(meta) = meta {
entry.add_meta(meta);
}
if let Some(data) = data {
entry.add_data(data);
}
}
#[cfg(not(feature = "print_cache_item_size"))]
let _ = item;
};
let task_snapshots =
self.storage
.take_snapshot(snapshot_guard, &process, reason.drain_entries());
let task_snapshots = self.storage.take_snapshot(
snapshot_guard,
&process,
&inspect_snapshot_item,
reason.drain_entries(),
);
drop(snapshot_span);
let snapshot_duration = start.elapsed();
......@@ -3997,39 +3957,57 @@ fn far_future() -> Instant {
Instant::now() + Duration::from_secs(86400 * 365 * 30)
}
/// Encodes task data, using the provided buffer as a scratch space. Returns a new exactly sized
/// buffer.
/// This allows reusing the buffer across multiple encode calls to optimize allocations and
/// resulting buffer sizes.
///
/// TODO: The `Result` return type is an artifact of the bincode `Encode` trait requiring
/// fallible encoding. In practice, encoding to a `SmallVec` is infallible (no I/O), and the only
/// real failure mode — a `TypedSharedReference` whose value type has no bincode impl — is a
/// programmer error caught by the panic in the caller. Consider making the bincode encoding trait
/// infallible (i.e. returning `()` instead of `Result<(), EncodeError>`) to eliminate the
/// spurious `Result` threading throughout the encode path.
fn encode_task_data(
task: TaskId,
data: &TaskStorage,
category: SpecificTaskDataCategory,
scratch_buffer: &mut TurboBincodeBuffer,
) -> Result<TurboBincodeBuffer> {
scratch_buffer.clear();
let mut encoder = new_turbo_bincode_encoder(scratch_buffer);
data.encode(category, &mut encoder)?;
if cfg!(feature = "verify_serialization") {
TaskStorage::new()
.decode(
category,
&mut new_turbo_bincode_decoder(&scratch_buffer[..]),
)
.with_context(|| {
format!(
"expected to be able to decode serialized data for '{category:?}' information \
for {task}"
)
})?;
#[cfg(test)]
mod persist_failure_tests {
use turbo_tasks::{TaskId, TurboTasks};
use crate::{
backend::{
BackendOptions, LastPersistenceStatus, SnapshotReason, StorageMode, TurboTasksBackend,
storage::SpecificTaskDataCategory,
},
noop_backing_storage,
};
/// A failed persist (the noop backing storage rejects writes) disables persisting for the
/// session: a later snapshot doesn't start, so it leaves the task's modification as it is.
#[tokio::test(flavor = "multi_thread")]
async fn failed_persist_disables_persisting() {
let tt = TurboTasks::new(TurboTasksBackend::new(
BackendOptions {
storage_mode: Some(StorageMode::ReadWrite),
num_workers: Some(1),
small_preallocation: true,
..Default::default()
},
noop_backing_storage(),
));
let backend = tt.backend();
let modify = |id: u32| {
let task_id = TaskId::new(id).unwrap();
let mut task = backend.storage.access_mut(task_id);
let _ = task.track_modification(SpecificTaskDataCategory::Data, "test");
task_id
};
let status = || *backend.snapshot_in_progress.lock();
modify(1);
assert_eq!(status(), LastPersistenceStatus::Ok);
let _ = backend.snapshot_and_evict_for_testing(&tt);
assert_eq!(status(), LastPersistenceStatus::Failed);
let task_id = modify(2);
let result = backend
.snapshot_and_persist(None, SnapshotReason::Test, &tt)
.expect("a disabled persist is skipped, not an error");
assert!(result.is_none(), "persisting must stay disabled");
assert_eq!(status(), LastPersistenceStatus::Failed);
let task = backend.storage.access_mut(task_id);
assert!(
task.flags.data_modified(),
"the second snapshot must not start"
);
assert!(!task.flags.any_modified_during_snapshot());
}
Ok(SmallVec::from_slice(scratch_buffer))
}
......@@ -1911,6 +1911,8 @@ mod must_exist_tests {
data: Some(encoded_data.clone()),
meta: Some(encoded_meta.clone()),
task_type_hash: None,
#[cfg(feature = "print_cache_item_size")]
stats: Default::default(),
})
.collect::<Vec<_>>();
backing.save_snapshot(None, vec![items]).unwrap();
......@@ -2104,7 +2106,10 @@ mod filter_transient_tracking_tests {
use super::*;
use crate::{
backend::{TaskDataCategory, storage::Storage},
backend::{
TaskDataCategory,
storage::{Storage, StorageOptions},
},
data::{CellRef, OutputValue},
};
......@@ -2140,7 +2145,7 @@ mod filter_transient_tracking_tests {
#[test]
fn autoset_add_remove_only_tracks_persistent_keys() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let task_id = persistent_task(1);
// `children` is an AutoSet<TaskId> meta field with filter_transient.
......@@ -2190,7 +2195,7 @@ mod filter_transient_tracking_tests {
#[test]
fn autoset_extend_tracks_iff_any_persistent() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
// Extend with only transient children: no meta modification.
let task_id = persistent_task(1);
......@@ -2218,7 +2223,7 @@ mod filter_transient_tracking_tests {
#[test]
fn countermap_update_count_only_tracks_persistent_keys() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let task_id = persistent_task(1);
// `upper` is a CounterMap<TaskId> meta field with filter_transient.
......@@ -2241,7 +2246,7 @@ mod filter_transient_tracking_tests {
#[test]
fn countermap_update_counts_batch_tracks_iff_any_persistent() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
// followers: CounterMap<TaskId>, filter_transient, has update_counts.
let task_id = persistent_task(1);
......@@ -2267,7 +2272,7 @@ mod filter_transient_tracking_tests {
#[test]
fn direct_option_set_take_tracks_by_value_transience() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
// `output` is a direct Option<OutputValue> meta field with filter_transient.
// Setting a transient output: no meta modification.
......@@ -2352,19 +2357,40 @@ mod filter_transient_tracking_tests {
mod cell_data_tracking_tests {
//! `cell_data` writes track a Data modification only when the cell's value
//! type persists something.
use turbo_bincode::TurboBincodeBuffer;
use turbo_tasks::{
self as turbo_tasks, CellId, TRANSIENT_TASK_BIT, TaskId, ValueTypePersistence, VcValueType,
registry,
};
use super::*;
use crate::backend::{
TaskDataCategory, storage::Storage, storage_schema::TaskStorageAccessors,
use crate::{
backend::{
TaskDataCategory,
storage::{Storage, StorageOptions, encode_snapshot_item, encode_task_contents},
storage_schema::TaskStorageAccessors,
},
backing_storage::SnapshotItem,
};
#[turbo_tasks::value]
struct PersistableV(#[allow(dead_code)] u32);
#[turbo_tasks::value(eq = "manual")]
struct InteriorMutableV {
#[bincode(with = "turbo_tasks::parking_lot_mutex_bincode")]
#[turbo_tasks(debug_ignore)]
value: parking_lot::Mutex<u32>,
}
impl PartialEq for InteriorMutableV {
fn eq(&self, _other: &Self) -> bool {
false
}
}
impl Eq for InteriorMutableV {}
#[turbo_tasks::value(serialization = "skip")]
struct SkipCheapV(#[allow(dead_code)] u32);
......@@ -2409,7 +2435,7 @@ mod cell_data_tracking_tests {
// (HashOnly persists via the separate `cell_data_hash` field) — but both
// are still stored in memory. Tracking is monotonic: a later persistable
// write flips the flag even after skipped writes left it clean.
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let mut g = guard_for(&storage, persistent_task(1));
let skip = cell_of::<SkipCheapV>(0);
......@@ -2432,7 +2458,7 @@ mod cell_data_tracking_tests {
#[test]
fn remove_tracks_only_for_persistable() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let skip = cell_of::<SkipCheapV>(0);
let persistable = cell_of::<PersistableV>(0);
......@@ -2471,7 +2497,7 @@ mod cell_data_tracking_tests {
// `drop_partial` (which keys on Evictability, not the modified flag), so
// a task that only wrote such a cell is both evictable-clean AND keeps the
// value. This is the core safety property of not tracking Skip writes.
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let task_id = persistent_task(1);
let cell = cell_of::<SkipNeverV>(0);
......@@ -2495,4 +2521,167 @@ mod cell_data_tracking_tests {
"Skip + evict=never cell must survive eviction even though the task was never modified"
);
}
/// Regression test for copy-on-write snapshots with interior-mutable cell contents.
///
/// Cloning `TaskStorage` only clones the cell's `SharedReference` pointer, so a mutation
/// through the shared value would also change the supposedly frozen snapshot copy. The
/// pre-mutation state must instead be encoded when the task is modified during a snapshot.
#[tokio::test(flavor = "multi_thread")]
async fn modify_during_snapshot_encodes_interior_mutable_cell_contents() {
let storage = Storage::new(StorageOptions::for_tests());
let task_id = persistent_task(1);
let cell = cell_of::<InteriorMutableV>(0);
let value = SharedReference::new(triomphe::Arc::new(InteriorMutableV {
value: parking_lot::Mutex::new(1),
}));
{
let mut g = guard_for(&storage, task_id);
g.insert_cell_data(cell, value.clone(), persistence_of(&cell));
assert!(g.data_modified());
}
let expected = {
let task = storage.access_mut(task_id);
encode_task_contents(
task_id,
&task,
SpecificTaskDataCategory::Data,
&mut TurboBincodeBuffer::new(),
)
.unwrap()
};
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 mut g = guard_for(&storage, task_id);
let _ = g.track_modification(SpecificTaskDataCategory::Data, "test");
*value
.downcast_ref::<InteriorMutableV>()
.unwrap()
.value
.lock() = 2;
}
let items: Vec<_> = shards.into_iter().flatten().collect();
assert_eq!(items.len(), 1);
let SnapshotItem::Put { data, .. } = &items[0] else {
panic!("expected a Put item");
};
assert_eq!(data.as_deref(), Some(&expected[..]));
let live = {
let task = storage.access_mut(task_id);
encode_task_contents(
task_id,
&task,
SpecificTaskDataCategory::Data,
&mut TurboBincodeBuffer::new(),
)
.unwrap()
};
assert_ne!(live, expected, "the shared cell value really changed");
}
/// Regression test: a task that is part of the snapshot through one category must be copied
/// on its first modification during the snapshot, even when that modification touches a
/// 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.
#[tokio::test(flavor = "multi_thread")]
async fn modify_other_category_first_during_snapshot_preserves_snapshot_meta() {
let storage = Storage::new(StorageOptions::for_tests());
let task_id = persistent_task(1);
{
let mut g = guard_for(&storage, task_id);
let _ = g.track_modification(SpecificTaskDataCategory::Meta, "test");
assert!(!g.data_modified());
}
let expected_meta = {
let task = storage.access_mut(task_id);
encode_task_contents(
task_id,
&task,
SpecificTaskDataCategory::Meta,
&mut TurboBincodeBuffer::new(),
)
.unwrap()
};
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 shards = storage.take_snapshot(snapshot_guard, &process, &|_| {}, false);
{
let mut g = guard_for(&storage, task_id);
let cell = cell_of::<PersistableV>(0);
g.insert_cell_data(cell, dummy_ref(), persistence_of(&cell));
assert!(g.add_children(persistent_task(2)));
}
let items: Vec<_> = shards.into_iter().flatten().collect();
assert_eq!(items.len(), 1);
let SnapshotItem::Put { meta, data, .. } = &items[0] else {
panic!("expected a Put item");
};
assert_eq!(
meta.as_deref(),
Some(&expected_meta[..]),
"the snapshot must persist the meta from before the snapshot"
);
assert!(data.is_none(), "data wasn't modified before the snapshot");
// Both modifications made during the snapshot are left for the next snapshot.
let task = storage.access_mut(task_id);
assert!(task.flags.meta_modified());
assert!(task.flags.data_modified());
assert!(!task.flags.any_modified_during_snapshot());
}
/// A pre-encoded (copy-on-write) item carries the cache size stats of the state it encoded,
/// not the live state after the mutation that triggered the copy.
#[cfg(feature = "print_cache_item_size")]
#[tokio::test(flavor = "multi_thread")]
async fn pre_encoded_item_carries_stats_captured_at_copy_time() {
let storage = Storage::new(StorageOptions::for_tests());
let task_id = persistent_task(1);
{
let mut g = guard_for(&storage, task_id);
let _ = g.track_modification(SpecificTaskDataCategory::Meta, "test");
}
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);
// The tracked add copies the task (no children yet) before inserting the child.
{
let mut g = guard_for(&storage, task_id);
assert!(g.add_children(persistent_task(2)));
}
let items: Vec<_> = shards.into_iter().flatten().collect();
assert_eq!(items.len(), 1);
let SnapshotItem::Put { stats, .. } = &items[0] else {
panic!("expected a Put item");
};
assert_eq!(stats.counts.children, 0);
assert_eq!(storage.access_mut(task_id).meta_counts().children, 1);
}
}
......@@ -9,23 +9,26 @@ use std::{
},
};
use anyhow::{Context, Result};
use crossbeam_utils::CachePadded;
use hashbrown::hash_table;
use smallvec::SmallVec;
use thread_local::ThreadLocal;
use tracing::span::Id;
use turbo_bincode::TurboBincodeBuffer;
use turbo_bincode::{TurboBincodeBuffer, new_turbo_bincode_decoder, new_turbo_bincode_encoder};
use turbo_tasks::{FxDashMap, TaskId, backend::CachedTaskTypeArc, event::Event, parallel};
use crate::{
backend::storage_schema::{
DropPartialOutcome, KeyEvictability, TaskStorage, UnevictableReason, ValueEvictability,
},
backing_storage::SnapshotItem,
backing_storage::{SnapshotItem, compute_task_type_hash},
database::key_value_database::KeySpace,
utils::{
dash_map_drop_contents::drop_contents,
dash_map_entry::{TryLockAndRemove, try_lock_and_remove},
dash_map_multi::{RefMut, get_disjoint_mut},
shard_amount::compute_shard_amount,
},
};
......@@ -156,14 +159,138 @@ pub enum TrackOutcome {
bumped: bool,
},
/// Snapshot path: `modified_during_snapshot(category)` was set. `inserted_snapshot` is true if
/// this call also inserted the task's entry into the `snapshots` map (the pre-mutation copy or
/// a `None` marker).
/// this call also inserted the task's entry into the `snapshots` map (the pre-mutation encoded
/// item or a `None` marker).
TrackedDuringSnapshot {
category: SpecificTaskDataCategory,
inserted_snapshot: bool,
},
}
/// Encodes task data, using the provided buffer as a scratch space. Returns a new exactly sized
/// buffer.
/// This allows reusing the buffer across multiple encode calls to optimize allocations and
/// resulting buffer sizes.
///
/// TODO: The `Result` return type is an artifact of the bincode `Encode` trait requiring
/// fallible encoding. In practice, encoding to a `SmallVec` is infallible (no I/O), and the only
/// real failure mode — a `TypedSharedReference` whose value type has no bincode impl — is a
/// programmer error caught by the panic in the caller. Consider making the bincode encoding trait
/// infallible (i.e. returning `()` instead of `Result<(), EncodeError>`) to eliminate the
/// spurious `Result` threading throughout the encode path.
pub(crate) fn encode_task_contents(
task: TaskId,
data: &TaskStorage,
category: SpecificTaskDataCategory,
scratch_buffer: &mut TurboBincodeBuffer,
) -> Result<TurboBincodeBuffer> {
scratch_buffer.clear();
let mut encoder = new_turbo_bincode_encoder(scratch_buffer);
data.encode(category, &mut encoder)?;
if cfg!(feature = "verify_serialization") {
TaskStorage::new()
.decode(
category,
&mut new_turbo_bincode_decoder(&scratch_buffer[..]),
)
.with_context(|| {
format!(
"expected to be able to decode serialized data for '{category:?}' information \
for {task}"
)
})?;
}
Ok(SmallVec::from_slice(scratch_buffer))
}
/// Converts a task's current state into the [`SnapshotItem`] that persistence writes for it.
///
/// Only categories whose `modified` flag is set are encoded. A `new_task` additionally carries
/// its task type hash so it can be added to the task cache. A GC-deleted task becomes a
/// [`SnapshotItem::Delete`] tombstone.
///
/// This is shared by the regular snapshot path and by [`StorageWriteGuard::track_modification`],
/// which encodes a task eagerly when it is about to be mutated while a snapshot that includes it
/// is still in progress. Consistency checks run where items are yielded instead (see
/// `SnapshotShardIter`), since this may run in the middle of an operation.
pub(crate) fn encode_snapshot_item(
task_id: TaskId,
inner: &TaskStorage,
buffer: &mut TurboBincodeBuffer,
) -> Result<SnapshotItem> {
if task_id.is_transient() {
unreachable!("transient task_ids should never be enqueued to be persisted");
}
if inner.flags.deleted() {
let task_type_hash = compute_task_type_hash(
inner
.get_persistent_task_type()
.expect("a GC-deleted task must have a task type"),
);
return Ok(SnapshotItem::Delete {
task_id,
task_type_hash,
});
}
let meta = if inner.flags.meta_modified() {
Some(
encode_task_contents(task_id, inner, SpecificTaskDataCategory::Meta, buffer)
.context("failed to encode task meta data")?,
)
} else {
None
};
let data = if inner.flags.data_modified() {
Some(
encode_task_contents(task_id, inner, SpecificTaskDataCategory::Data, buffer)
.context("failed to encode task data")?,
)
} else {
None
};
let task_type_hash = if inner.flags.new_task() {
let task_type = inner.get_persistent_task_type().expect(
"It is not possible for a new_task to not have a persistent_task_type. Task creation \
for persistent tasks uses a single ExecutionContextImpl for creating the task (which \
sets new_task) and connect_child (which sets persistent_task_type) and take_snapshot \
waits for all operations to complete before we start snapshotting. So task creation \
will always set the task_type.",
);
Some(compute_task_type_hash(task_type))
} else {
None
};
Ok(SnapshotItem::Put {
task_id,
meta,
data,
task_type_hash,
#[cfg(feature = "print_cache_item_size")]
stats: Box::new(snapshot_item_stats(inner)),
})
}
/// Captures the cache size statistics of the task state being encoded.
#[cfg(feature = "print_cache_item_size")]
fn snapshot_item_stats(inner: &TaskStorage) -> crate::backing_storage::SnapshotItemStats {
crate::backing_storage::SnapshotItemStats {
task_name: inner
.get_persistent_task_type()
.map(|t| t.to_string())
.unwrap_or_else(|| "<unknown>".to_string()),
counts: inner.meta_counts(),
output_size: inner.get_output().map_or(0, |output| {
turbo_bincode::turbo_bincode_encode(&output).map_or(0, |data| data.len())
}),
}
}
pub struct Storage {
snapshot_mode: AtomicBool,
/// Per-shard counts of tasks with modified flags set. Incremented when a task
......@@ -178,10 +305,15 @@ pub struct Storage {
/// Should only be modified while holding the corresponding dashmap shard lock.
shard_modified_counts: Box<[CachePadded<AtomicU64>]>,
/// Stores snapshots of task state for tasks accessed during snapshot mode.
/// - `Some(snapshot)`: Task was modified before snapshot mode and accessed again during it.
/// 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.
/// - `Some(item)`: Task was modified before snapshot mode and modified again during it.
/// Contains the pre-snapshot state, already bincode-encoded into the [`SnapshotItem`] that
/// persistence writes. Encoding (rather than cloning the `TaskStorage`) is required for
/// consistency: a clone would share cell contents with interior mutability via `Arc`, so
/// later mutations could leak into the supposedly frozen copy. Persistence uses the item
/// as-is, so no work is wasted.
/// - `None`: Task had no modified category when it 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
......@@ -194,7 +326,7 @@ pub struct Storage {
/// 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>>>,
snapshots: FxDashMap<TaskId, Option<Box<SnapshotItem>>>,
/// The main storage map
///
/// Lock Ordering: Task creation acquires a `task_cache` lock and then inserts into this map.
......@@ -219,8 +351,42 @@ pub struct Storage {
pub task_cache: FxDashMap<CachedTaskTypeArc, TaskId>,
}
/// 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).
pub shard_amount: usize,
/// Preallocate a small task map instead of a large one (e.g. for tests or short-lived
/// instances).
pub small_preallocation: bool,
}
impl Default for StorageOptions {
fn default() -> Self {
Self {
shard_amount: compute_shard_amount(None, false),
small_preallocation: false,
}
}
}
#[cfg(test)]
impl StorageOptions {
/// Small storage for unit tests.
pub(crate) fn for_tests() -> Self {
Self {
shard_amount: 2,
small_preallocation: true,
}
}
}
impl Storage {
pub fn new(shard_amount: usize, small_preallocation: bool) -> Self {
pub fn new(options: StorageOptions) -> Self {
let StorageOptions {
shard_amount,
small_preallocation,
} = options;
let map_capacity: usize = if small_preallocation {
1024
} else {
......@@ -305,11 +471,10 @@ impl Storage {
/// the results. Ends snapshot mode when the returned `SnapshotGuard` (held by each shard) is
/// dropped.
///
/// `process` is called while holding a read lock on the task storage, so it can access
/// the TaskStorage directly without cloning.
/// `process` is called with the task storage to encode. It receives a mutable scratch buffer
/// that can be reused across iterations to avoid repeated allocations.
///
/// Both callbacks receive a mutable scratch buffer that can be reused across iterations
/// to avoid repeated allocations.
/// `inspect_snapshot_item` allows gathering statistics about encoded items
///
/// The returned shards implement `IntoIterator`. Empty shards (no modified or snapshot
/// entries) are filtered out, but shards may still yield no items if all entries produce
......@@ -322,12 +487,14 @@ impl Storage {
pub fn take_snapshot<
'l,
P: for<'a> Fn(TaskId, &'a TaskStorage, &mut TurboBincodeBuffer) -> SnapshotItem + Sync,
I: Fn(&SnapshotItem) + Sync,
>(
&'l self,
guard: SnapshotGuard<'l>,
process: &'l P,
inspect_snapshot_item: &'l I,
drain_entries: bool,
) -> Vec<SnapshotShard<'l, P>> {
) -> Vec<SnapshotShard<'l, P, I>> {
let guard = Arc::new(guard);
let shards: Vec<_> = self.map.shards().iter().enumerate().collect();
......@@ -401,6 +568,7 @@ impl Storage {
work,
storage: self,
process,
inspect_snapshot_item,
_guard: guard.clone(),
})
})
......@@ -851,62 +1019,53 @@ impl StorageWriteGuard<'_> {
}
#[cfg(feature = "trace_task_modification")]
let _span = (!modified).then(|| tracing::trace_span!("mark_modified", name).entered());
match (self.storage.snapshot_mode(), flags.is_modified(category)) {
(false, false) => {
// Not in snapshot mode and item is unmodified
let bumped = !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 }
}
(false, true) => {
if !self.storage.snapshot_mode() {
if flags.is_modified(category) {
// Not in snapshot mode and item is already modified
// Do nothing
TrackOutcome::NoChange
}
(true, false) => {
// In snapshot mode and item is unmodified (so it's not part of the snapshot)
// Mark it so it gets re-added as Modified after this snapshot completes.
// Insert a None entry into snapshots so end_snapshot discovers this task
// and promotes its _during_snapshot flags.
let inserted_snapshot = !flags.any_modified_during_snapshot();
if inserted_snapshot {
self.storage.snapshots.insert(*self.inner.key(), None);
}
self.inner
.flags
.set_modified_during_snapshot(category, true);
TrackOutcome::TrackedDuringSnapshot {
category,
inserted_snapshot,
}
return TrackOutcome::NoChange;
}
(true, true) => {
// In snapshot mode and item is modified (so it's part of the snapshot)
// We need to store the original version that is part of the snapshot
let inserted_snapshot = !flags.any_modified_during_snapshot();
if inserted_snapshot {
// Snapshot all non-transient fields, carrying the modified bits into
// the copy so the iterator knows which categories to persist.
let mut snapshot = self.inner.clone_snapshot();
snapshot.flags.set_data_modified(flags.data_modified());
snapshot.flags.set_meta_modified(flags.meta_modified());
snapshot.flags.set_new_task(flags.new_task());
self.storage
.snapshots
.insert(*self.inner.key(), Some(Box::new(snapshot)));
}
self.inner
.flags
.set_modified_during_snapshot(category, true);
TrackOutcome::TrackedDuringSnapshot {
category,
inserted_snapshot,
}
// Not in snapshot mode and item is unmodified
let bumped = !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);
return TrackOutcome::Tracked { category, bumped };
}
// In snapshot mode. The first modification of the task during the snapshot decides how
// the snapshot sees the task, whichever category it touches: if any category was
// modified before the snapshot, the task is part of it and its pre-mutation state must be
// preserved, including the categories this modification doesn't touch (they can still be
// modified later during the snapshot). Otherwise the task isn't part of the snapshot and
// only gets a `None` marker, so `end_snapshot` discovers it and promotes its
// `_during_snapshot` flags.
let inserted_snapshot = !flags.any_modified_during_snapshot();
if inserted_snapshot {
let task_id = *self.inner.key();
let item = if flags.any_modified() {
// Encode the pre-mutation state now, using the live modified bits to decide
// which categories to persist. This way persistence sees a consistent view of
// the task pre-mutation.
let mut buffer = TurboBincodeBuffer::new();
let item =
encode_snapshot_item(task_id, &self.inner, &mut buffer).unwrap_or_else(|err| {
panic!("Serializing task {task_id} for a snapshot failed: {err:?}")
});
Some(Box::new(item))
} else {
None
};
self.storage.snapshots.insert(task_id, item);
}
self.inner
.flags
.set_modified_during_snapshot(category, true);
TrackOutcome::TrackedDuringSnapshot {
category,
inserted_snapshot,
}
}
......@@ -1073,21 +1232,23 @@ enum ShardWork {
Drain(hash_table::IntoIter<(TaskId, Box<TaskStorage>)>),
}
pub struct SnapshotShard<'l, P> {
pub struct SnapshotShard<'l, P, I> {
shard_idx: usize,
work: ShardWork,
storage: &'l Storage,
process: &'l P,
inspect_snapshot_item: &'l I,
/// Held for its `Drop` impl — ensures snapshot mode ends when all shards are done.
_guard: Arc<SnapshotGuard<'l>>,
}
impl<'l, P> IntoIterator for SnapshotShard<'l, P>
impl<'l, P, I> IntoIterator for SnapshotShard<'l, P, I>
where
P: Fn(TaskId, &TaskStorage, &mut TurboBincodeBuffer) -> SnapshotItem + Sync,
I: Fn(&SnapshotItem) + Sync,
{
type Item = SnapshotItem;
type IntoIter = SnapshotShardIter<'l, P>;
type IntoIter = SnapshotShardIter<'l, P, I>;
fn into_iter(self) -> Self::IntoIter {
let buffer = self._guard.take_scratch_buffer();
......@@ -1100,34 +1261,42 @@ where
/// Iterator over a single shard's snapshot items. Holds a thread-local scratch
/// buffer for the duration of iteration and returns it on drop.
pub struct SnapshotShardIter<'l, P> {
shard: SnapshotShard<'l, P>,
pub struct SnapshotShardIter<'l, P, I> {
shard: SnapshotShard<'l, P, I>,
buffer: TurboBincodeBuffer,
}
impl<'l, P> Iterator for SnapshotShardIter<'l, P>
impl<'l, P, I> Iterator for SnapshotShardIter<'l, P, I>
where
P: Fn(TaskId, &TaskStorage, &mut TurboBincodeBuffer) -> SnapshotItem + Sync,
I: Fn(&SnapshotItem) + Sync,
{
type Item = SnapshotItem;
fn next(&mut self) -> Option<Self::Item> {
let process = self.shard.process;
let inspect_snapshot_item = self.shard.inspect_snapshot_item;
let snapshots = &self.shard.storage.snapshots;
let buffer = &mut self.buffer;
let mut serialize_task = |task_id: TaskId, inner: &TaskStorage| {
debug_assert!(
!(inner.flags.deleted() && inner.flags.new_task()),
"a scanned GC-deleted task must be persisted; new tasks are discarded by GC"
);
// If the task was re-modified during snapshot, the snapshots map may
// hold a pre-modification copy we must serialize instead of the live
// data. Remove the entry so end_snapshot doesn't double-promote it;
// hold the pre-modification state, already encoded, which we must persist instead
// of the live data. Remove the entry so end_snapshot doesn't double-promote it;
// we promote manually below.
if inner.flags.any_modified_during_snapshot() {
let item = if inner.flags.any_modified_during_snapshot() {
match snapshots.remove(&task_id) {
Some((_, Some(snapshot))) => process(task_id, &snapshot, buffer),
Some((_, Some(item))) => *item,
Some((_, None)) | None => process(task_id, inner, buffer),
}
} else {
process(task_id, inner, buffer)
}
};
inspect_snapshot_item(&item);
item
};
match &mut self.shard.work {
......@@ -1135,7 +1304,7 @@ where
let task_id = modified.pop()?;
let mut inner = self.shard.storage.map.get_mut(&task_id).unwrap();
let item = serialize_task(task_id, &inner);
// Clear the modified flags that were captured into the snapshot copy,
// Clear the modified flags that were captured into the snapshot item,
// then promote modified_during_snapshot → modified so the task stays
// dirty for the next snapshot cycle.
inner.flags.set_data_modified(false);
......@@ -1161,7 +1330,7 @@ where
}
}
impl<P> Drop for SnapshotShardIter<'_, P> {
impl<P, I> Drop for SnapshotShardIter<'_, P, I> {
fn drop(&mut self) {
self.shard
._guard
......@@ -1174,7 +1343,7 @@ mod tests {
use turbo_bincode::TurboBincodeBuffer;
use turbo_tasks::TaskId;
use super::{SpecificTaskDataCategory, Storage, TrackOutcome};
use super::{SpecificTaskDataCategory, Storage, StorageOptions, TrackOutcome};
use crate::backing_storage::SnapshotItem;
fn non_transient_task(id: u32) -> TaskId {
......@@ -1184,7 +1353,7 @@ mod tests {
#[test]
fn new_task_is_pinned_during_construction() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let task_id = non_transient_task(1);
storage.initialize_new_task(task_id, None);
......@@ -1206,9 +1375,14 @@ mod tests {
meta: Some(TurboBincodeBuffer::default()),
data: None,
task_type_hash: None,
#[cfg(feature = "print_cache_item_size")]
stats: Default::default(),
}
}
/// An `inspect_snapshot_item` callback that ignores the items.
fn noop_inspect(_: &SnapshotItem) {}
/// Regression test: a task modified before a snapshot and then modified *again* during
/// snapshot iteration must serialize the pre-snapshot state and carry the during-snapshot
/// modification forward to the next cycle.
......@@ -1219,18 +1393,18 @@ mod tests {
/// 3. `take_snapshot` scans the shard: task has `any_modified()=true` → goes into the
/// `modified` list.
/// 4. **Between scan and iteration**: `track_modification` is called on the same category. This
/// is the `(true, true)` branch: already modified AND in snapshot mode. A snapshot copy of
/// the pre-second-modification state is stored in `snapshots` as `Some(copy)`, and
/// is the first modification during the snapshot, and the task is already modified, so the
/// pre-second-modification state is encoded and stored in `snapshots` as `Some(item)`, and
/// `data_modified_during_snapshot` is set.
/// 5. `SnapshotShardIter::next` processes the task from the `modified` list, detects
/// `any_modified_during_snapshot()=true`, finds the `Some(copy)` in `snapshots`, encodes the
/// pre-snapshot copy, clears the live modified flags, removes the snapshots entry, and
/// `any_modified_during_snapshot()=true`, finds the `Some(item)` in `snapshots`, yields the
/// pre-encoded item, clears the live modified flags, removes the snapshots entry, and
/// promotes `data_modified_during_snapshot → data_modified` for the next cycle.
// `end_snapshot` uses `parallel::for_each` which calls `block_in_place` internally,
// requiring a multi-threaded Tokio runtime.
#[tokio::test(flavor = "multi_thread")]
async fn modify_during_snapshot_clears_live_modified_flags() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let task_id = non_transient_task(1);
// Step 1: modify the task outside snapshot mode (data_modified = true).
......@@ -1246,11 +1420,11 @@ mod tests {
// Step 3: `take_snapshot` scans the shard. At this point the task has
// `any_modified()=true` and `any_modified_during_snapshot()=false`, so it
// goes into the `modified` list inside the returned `SnapshotShard`.
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, false);
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, &noop_inspect, false);
// Step 4: now that the scan is done but before we consume the iterator,
// modify the task again. We're still in snapshot mode, the task is already
// modified → `(true, true)` branch: creates a snapshot copy (carrying the
// modify the task again. We're still in snapshot mode and the task is already
// modified, so this encodes the pre-mutation state (using the
// modified bits) and sets `data_modified_during_snapshot=true`.
{
let mut guard = storage.access_mut(task_id);
......@@ -1259,7 +1433,7 @@ mod tests {
assert!(guard.flags.data_modified_during_snapshot())
}
// Step 5: consume the iterator. The iterator encodes from the pre-snapshot copy,
// Step 5: consume the iterator. The iterator yields the pre-encoded item,
// clears the live modified flags, removes the snapshots entry, and promotes
// `data_modified_during_snapshot → data_modified` for the next cycle.
let items: Vec<_> = shards
......@@ -1267,7 +1441,7 @@ mod tests {
.flat_map(|shard| shard.into_iter())
.collect();
// The pre-snapshot snapshot copy should have been encoded and returned.
// The pre-encoded snapshot item should have been returned.
assert_eq!(items.len(), 1);
assert_eq!(items[0].task_id(), task_id);
......@@ -1286,23 +1460,23 @@ mod tests {
);
}
/// Regression test for the `(true, false)` during-snapshot case: a task modified in one
/// category before a snapshot, then modified in a *different* category during snapshot
/// iteration, must not panic and must carry both modifications forward correctly.
/// Regression test for a during-snapshot modification of a different category: a task
/// modified in one category before a snapshot, then modified in a *different* category during
/// snapshot iteration, must not panic and must carry both modifications forward correctly.
///
/// Sequence of events:
/// 1. Task meta is modified (meta_modified = true).
/// 2. `start_snapshot` puts us in snapshot mode.
/// 3. `take_snapshot` scans the shard: task goes into the `modified` list.
/// 4. Task data is modified during snapshot → `(true, false)` branch: data was not previously
/// modified, so `snapshots` gets a `None` entry and `data_modified_during_snapshot` is set.
/// 4. Task data is modified during snapshot: it's the task's first modification during the
/// snapshot and meta is modified, so `snapshots` gets the encoded pre-mutation item (meta
/// only) and `data_modified_during_snapshot` is set.
/// 5. `SnapshotShardIter::next` processes the task: finds `any_modified_during_snapshot()`,
/// sees `None` in snapshots, encodes from live data (correct — live data for the
/// unmodified-before-snapshot category is still the pre-snapshot state), clears pre-snapshot
/// flags, and promotes `data_modified_during_snapshot → data_modified`.
/// yields the pre-encoded item, clears pre-snapshot flags, and promotes
/// `data_modified_during_snapshot → data_modified`.
#[tokio::test(flavor = "multi_thread")]
async fn modify_different_category_during_snapshot() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let task_id = non_transient_task(1);
// Step 1: modify meta only, outside snapshot mode.
......@@ -1318,15 +1492,19 @@ mod tests {
assert!(has_modifications);
// Step 3: take_snapshot — task goes into modified list (meta_modified = true).
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, false);
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, &noop_inspect, false);
// Step 4: modify data during snapshot. The `(true, false)` branch fires:
// data was not previously modified, so snapshots gets a None entry.
// Step 4: modify data during snapshot. Meta is part of the snapshot, so the task's
// pre-mutation state is copied into `snapshots`.
{
let mut guard = storage.access_mut(task_id);
let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
assert!(guard.flags.data_modified_during_snapshot());
assert!(!guard.flags.meta_modified_during_snapshot());
assert!(matches!(
storage.snapshots.get(&task_id).as_deref(),
Some(Some(_))
));
}
// Step 5: consume the iterator — must not panic.
......@@ -1361,7 +1539,7 @@ mod tests {
/// entry must be gone from the map by the time the snapshot is consumed.
#[tokio::test(flavor = "multi_thread")]
async fn drain_entries_removes_entry_from_map() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let task_id = non_transient_task(1);
// Modify the task outside snapshot mode so it lands in the modified list.
......@@ -1375,7 +1553,7 @@ mod tests {
assert!(has_modifications);
// Take the snapshot in drain mode.
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, true);
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, &noop_inspect, true);
// Consume the iterator: the task is serialized and then removed from the map.
let items: Vec<_> = shards
......@@ -1398,7 +1576,7 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn drain_entries_releases_drained_shards() {
// dashmap requires at least 2 shards.
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
// Insert and modify enough tasks to grow the shards' tables beyond their minimum.
let task_ids: Vec<_> = (1..=256).map(non_transient_task).collect();
......@@ -1417,7 +1595,7 @@ mod tests {
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, true);
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, &noop_inspect, true);
let items: Vec<_> = shards
.into_iter()
.flat_map(|shard| shard.into_iter())
......@@ -1444,7 +1622,7 @@ mod tests {
/// yielded.
#[tokio::test(flavor = "multi_thread")]
async fn drain_entries_removes_unmodified_during_take_snapshot() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let modified_id = non_transient_task(1);
let unmodified_id = non_transient_task(2);
......@@ -1461,7 +1639,7 @@ mod tests {
let (snapshot_guard, has_modifications) = storage.start_snapshot();
assert!(has_modifications);
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, true);
let shards = storage.take_snapshot(snapshot_guard, &dummy_process, &noop_inspect, true);
// 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.
......@@ -1486,7 +1664,7 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn undo_non_snapshot_reverses_flag_and_counter() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let task_id = non_transient_task(1);
{
......@@ -1510,7 +1688,7 @@ mod tests {
/// must NOT clear the real modification recorded by the first track.
#[tokio::test(flavor = "multi_thread")]
async fn undo_nochange_preserves_prior_modification() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let task_id = non_transient_task(1);
let mut guard = storage.access_mut(task_id);
......@@ -1531,7 +1709,7 @@ mod tests {
/// outcome must leave Data modified and the shard counter still non-zero.
#[tokio::test(flavor = "multi_thread")]
async fn undo_only_reverses_its_own_category() {
let storage = Storage::new(2, true);
let storage = Storage::new(StorageOptions::for_tests());
let task_id = non_transient_task(1);
{
......@@ -1549,12 +1727,12 @@ mod tests {
assert!(has_modifications);
}
/// During-snapshot `(true, false)` arm: a task unmodified-before-snapshot, tracked during
/// snapshot, inserts a `None` marker into `snapshots` and sets the `_during_snapshot` bit.
/// Undo must remove the marker and clear the bit.
/// A task with no modified category, tracked during snapshot, inserts a `None` marker into
/// `snapshots` and sets the `_during_snapshot` bit. Undo must remove the marker and clear the
/// bit.
#[tokio::test(flavor = "multi_thread")]
async fn undo_during_snapshot_true_false_removes_marker() {
let storage = Storage::new(2, true);
async fn undo_during_snapshot_unmodified_task_removes_marker() {
let storage = Storage::new(StorageOptions::for_tests());
let task_id = non_transient_task(1);
// Insert the task (unmodified) so it exists in the map.
let _ = storage.access_mut(task_id);
......@@ -1571,7 +1749,10 @@ mod tests {
}
));
assert!(guard.flags.data_modified_during_snapshot());
assert!(storage.snapshots.get(&task_id).is_some());
assert!(matches!(
storage.snapshots.get(&task_id).as_deref(),
Some(None)
));
guard.undo_track_modification(outcome);
assert!(!guard.flags.data_modified_during_snapshot());
......@@ -1581,13 +1762,13 @@ mod tests {
);
}
/// During-snapshot `(true, true)` arm: a task modified-before-snapshot, tracked again during
/// snapshot, stores a pre-mutation copy in `snapshots`. Undo must remove that copy and clear
/// the `_during_snapshot` bit, while leaving the pre-existing `modified` flag intact (it
/// belongs to the snapshot, not to this call).
/// A task modified before the snapshot, tracked again during snapshot, stores a pre-mutation
/// encoded item in `snapshots`. Undo must remove that item and clear the `_during_snapshot`
/// bit, while leaving the pre-existing `modified` flag intact (it belongs to the snapshot, not
/// to this call).
#[tokio::test(flavor = "multi_thread")]
async fn undo_during_snapshot_true_true_removes_copy_preserves_modified() {
let storage = Storage::new(2, true);
async fn undo_during_snapshot_modified_task_removes_item_preserves_modified() {
let storage = Storage::new(StorageOptions::for_tests());
let task_id = non_transient_task(1);
// Modify before snapshot so the category is part of the snapshot.
......@@ -1620,7 +1801,7 @@ mod tests {
);
assert!(
storage.snapshots.get(&task_id).is_none(),
"undo must remove the pre-mutation copy it inserted"
"undo must remove the pre-mutation item it inserted"
);
}
}
......@@ -21,6 +21,9 @@ pub enum SnapshotItem {
data: Option<TurboBincodeBuffer>,
/// Task type for new tasks that need to be added to the task cache
task_type_hash: Option<TaskTypeHash>,
/// Cache size statistics captured when the item was encoded.
#[cfg(feature = "print_cache_item_size")]
stats: Box<SnapshotItemStats>,
},
Delete {
task_id: TaskId,
......@@ -30,6 +33,18 @@ pub enum SnapshotItem {
},
}
/// Per-task cache size statistics, captured by `encode_snapshot_item` from the same task state
/// that was encoded, so pre-encoded (copy-on-write) items report what was actually persisted.
#[cfg(feature = "print_cache_item_size")]
#[derive(Default)]
pub struct SnapshotItemStats {
/// The task name, used as the stats grouping key.
pub task_name: String,
pub counts: crate::backend::storage_schema::MetaCounts,
/// Size of the encoded task output, if any.
pub output_size: usize,
}
impl SnapshotItem {
/// The task this item persists or tombstones. (Currently only used by tests, which assert on
/// the id of items yielded by the snapshot iterator.)
......
......@@ -276,6 +276,7 @@ impl TurboBackingStorage {
meta,
data,
task_type_hash,
..
} => {
let key = IntKey::new(*task_id);
let key = key.as_ref();
......
......@@ -898,18 +898,6 @@ impl GroupedFields {
// Code Generation Helpers
// =============================================================================
/// Generate inline field clone assignments: `snapshot.field = self.field.clone();`
fn gen_clone_inline_fields<'a>(fields: impl Iterator<Item = &'a FieldInfo>) -> Vec<TokenStream> {
fields
.map(|field| {
let field_name = &field.field_name;
quote! {
snapshot.#field_name = self.#field_name.clone();
}
})
.collect()
}
fn gen_restore_inline_field(field: &FieldInfo) -> TokenStream {
let field_name = &field.field_name;
if !field.filter_transient {
......@@ -3844,25 +3832,6 @@ fn generate_decode_lazy_fields(fields: &[&FieldInfo]) -> TokenStream {
}
}
/// Generate clone inline statements for a category.
fn gen_clone_inline_for_category(
grouped_fields: &GroupedFields,
category: Category,
) -> Vec<TokenStream> {
gen_clone_inline_fields(grouped_fields.persistent_inline(category))
}
/// Generate clone lazy match arms for a category.
fn gen_clone_lazy_arms_for_category(
grouped_fields: &GroupedFields,
category: Category,
) -> Vec<TokenStream> {
gen_lazy_match_arms(grouped_fields.persistent_lazy(category), |_, field| {
let variant_name = &field.variant_name;
quote! { snapshot.lazy.push(LazyField::#variant_name(data.clone())); }
})
}
/// Generate restore inline statements for a category.
fn gen_restore_inline_for_category(
grouped_fields: &GroupedFields,
......@@ -3874,11 +3843,9 @@ fn gen_restore_inline_for_category(
.collect()
}
/// Generate snapshot clone and restore methods for TaskStorage.
/// Generate snapshot restore methods for TaskStorage.
///
/// Generates:
/// - `clone_meta_snapshot(&self) -> TaskStorage` - Clone only persistent meta fields
/// - `clone_data_snapshot(&self) -> TaskStorage` - Clone only persistent data fields
/// - `restore_from(&mut self, source, category)` - Restore data by category from decoded storage
/// - `restore_meta_from(&mut self, source)` - Restore meta fields from source
/// - `restore_data_from(&mut self, source)` - Restore data fields from source
......@@ -3886,14 +3853,8 @@ fn gen_restore_inline_for_category(
fn generate_snapshot_restore_methods(grouped_fields: &GroupedFields) -> TokenStream {
let has_meta_flags = grouped_fields.persisted_meta_flags().next().is_some();
let has_data_flags = grouped_fields.persisted_data_flags().next().is_some();
let has_any_flags = has_meta_flags || has_data_flags;
// Generate field operations by category
let clone_meta_inline = gen_clone_inline_for_category(grouped_fields, Category::Meta);
let clone_data_inline = gen_clone_inline_for_category(grouped_fields, Category::Data);
let clone_meta_lazy_arms = gen_clone_lazy_arms_for_category(grouped_fields, Category::Meta);
let clone_data_lazy_arms = gen_clone_lazy_arms_for_category(grouped_fields, Category::Data);
let restore_meta_inline = gen_restore_inline_for_category(grouped_fields, Category::Meta);
let restore_data_inline = gen_restore_inline_for_category(grouped_fields, Category::Data);
......@@ -3912,15 +3873,6 @@ fn generate_snapshot_restore_methods(grouped_fields: &GroupedFields) -> TokenStr
.map(|(idx, f)| gen_restore_lazy_merge_arm(f, idx as u8))
.collect();
let clone_all_flags = if has_any_flags {
quote! {
// Clone all persisted flags
snapshot.flags.set_persisted_bits(self.flags.persisted_bits());
}
} else {
quote! {}
};
// Generate flags handling for restore - per category
let restore_meta_flags = if has_meta_flags {
quote! {
......@@ -3943,34 +3895,6 @@ fn generate_snapshot_restore_methods(grouped_fields: &GroupedFields) -> TokenStr
quote! {
#[automatically_derived]
impl TaskStorage {
/// Create a snapshot containing all persistent fields
pub fn clone_snapshot(&self) -> TaskStorage {
let mut snapshot = TaskStorage::new();
// Clone inline meta fields
#(#clone_meta_inline)*
// Clone inline data fields
#(#clone_data_inline)*
#clone_all_flags
// Clone all persistent lazy fields (both meta and data).
// (No pre-`reserve`: the schema has ≤24 lazy fields, so at most 3 grows
// (0→4→8→16→24) total — cheaper than complicating the public API surface
// of `TinyVec`.)
for field in &self.lazy {
match field {
#(#clone_data_lazy_arms)*
#(#clone_meta_lazy_arms)*
// Skip transient fields
_ => {}
}
}
snapshot
}
/// Restore persisted data from a decoded TaskStorage.
///
/// This is used during restore operations to copy decoded persisted data
......
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