Skip to main content

turbo_tasks_backend/backend/
storage.rs

1use std::{
2    cell::Cell,
3    fmt::{Display, Formatter},
4    hash::{BuildHasher, Hash},
5    ops::{Deref, DerefMut},
6    sync::{
7        Arc,
8        atomic::{AtomicBool, Ordering},
9    },
10};
11
12use anyhow::{Context, Result};
13use dashmap::try_result::TryResult;
14use hashbrown::hash_table;
15use thread_local::ThreadLocal;
16use tracing::span::Id;
17use turbo_bincode::{TurboBincodeBuffer, new_turbo_bincode_decoder, new_turbo_bincode_encoder};
18use turbo_tasks::{FxDashMap, TaskId, cached_task_type::CachedTaskTypeArc, event::Event, parallel};
19
20use crate::{
21    backend::{
22        snapshot_coordinator::SnapshotPhase,
23        storage_schema::{
24            DropPartialOutcome, KeyEvictability, TaskStorage, UnevictableReason, ValueEvictability,
25        },
26    },
27    backing_storage::{SnapshotItem, compute_task_type_hash},
28    database::key_value_database::KeySpace,
29    utils::{
30        dash_map_drop_contents::drop_contents,
31        dash_map_entry::{TryLockAndRemove, try_lock_and_remove},
32        dash_map_multi::{RefMut, get_disjoint_mut},
33        shard_amount::compute_shard_amount,
34    },
35};
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum TaskDataCategory {
39    Meta,
40    Data,
41    All,
42}
43impl PartialOrd for TaskDataCategory {
44    /// `All` is greater than both `Meta` and `Data`; `Meta` and `Data` are unordered.
45    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
46        use std::cmp::Ordering::*;
47
48        use TaskDataCategory::All;
49        match (self, other) {
50            _ if self == other => Some(Equal),
51            (All, _) => Some(Greater),
52            (_, All) => Some(Less),
53            _ => None,
54        }
55    }
56}
57
58/// Counts of tasks evicted at each level.
59#[derive(Debug, Default)]
60pub struct EvictionCounts {
61    pub key_evictions: usize,
62    pub full: usize,
63    pub data_and_meta: usize,
64    pub data_only: usize,
65    pub meta_only: usize,
66    /// Per-reason counts of tasks we considered but could not evict, indexed by
67    /// `UnevictableReason::index()`.
68    pub unevictable_reasons: [usize; UnevictableReason::COUNT],
69}
70
71impl std::ops::AddAssign for EvictionCounts {
72    fn add_assign(&mut self, rhs: Self) {
73        self.key_evictions += rhs.key_evictions;
74        self.full += rhs.full;
75        self.data_and_meta += rhs.data_and_meta;
76        self.data_only += rhs.data_only;
77        self.meta_only += rhs.meta_only;
78        for i in 0..UnevictableReason::COUNT {
79            self.unevictable_reasons[i] += rhs.unevictable_reasons[i];
80        }
81    }
82}
83
84impl Display for EvictionCounts {
85    /// Compact `field=value,...` form used as a single tracing span field so that
86    /// adding a new counter or `UnevictableReason` variant doesn't require updating
87    /// the span field list.
88    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
89        let skipped: usize = self.unevictable_reasons.iter().sum();
90        write!(
91            f,
92            "task_cache_evictions={},full={},data_and_meta={},data_only={},meta_only={},skipped={}",
93            self.key_evictions,
94            self.full,
95            self.data_and_meta,
96            self.data_only,
97            self.meta_only,
98            skipped,
99        )?;
100        for reason in UnevictableReason::ALL {
101            write!(
102                f,
103                ",{}={}",
104                reason.span_name(),
105                self.unevictable_reasons[reason.index()],
106            )?;
107        }
108        Ok(())
109    }
110}
111
112impl TaskDataCategory {
113    pub fn includes_data(self) -> bool {
114        matches!(self, TaskDataCategory::Data | TaskDataCategory::All)
115    }
116
117    pub fn includes_meta(self) -> bool {
118        matches!(self, TaskDataCategory::Meta | TaskDataCategory::All)
119    }
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
123pub enum SpecificTaskDataCategory {
124    Meta,
125    Data,
126}
127
128impl From<SpecificTaskDataCategory> for TaskDataCategory {
129    fn from(category: SpecificTaskDataCategory) -> Self {
130        match category {
131            SpecificTaskDataCategory::Meta => TaskDataCategory::Meta,
132            SpecificTaskDataCategory::Data => TaskDataCategory::Data,
133        }
134    }
135}
136
137impl SpecificTaskDataCategory {
138    /// Returns the KeySpace for storing data of this category
139    pub fn key_space(self) -> KeySpace {
140        match self {
141            SpecificTaskDataCategory::Meta => KeySpace::TaskMeta,
142            SpecificTaskDataCategory::Data => KeySpace::TaskData,
143        }
144    }
145}
146
147/// Records exactly what a `track_modification` call changed, so that
148/// [`StorageWriteGuard::undo_track_modification`] can reverse it precisely when the mutation it
149/// guarded turns out to be a no-op.  This allows us to track modifications 'optimistically' and
150/// undo it if the modification turned out to be a no op.  Useful when dealing with datastructures
151/// like `AutoSet` that can efficiently say whether or not they were modified.
152#[must_use = "a no-op mutation must undo its TrackOutcome; dropping it leaks an over-track"]
153pub enum TrackOutcome {
154    /// Nothing was tracked: the category was already modified. Undo is a no-op.
155    NoChange,
156    /// `modified(category)` was set. `inserted_snapshot` is true if this call also inserted the
157    /// task's pre-mutation encoded state into the `snapshots` map (the task was captured by the
158    /// in-progress snapshot and not persisted yet).
159    Tracked {
160        category: SpecificTaskDataCategory,
161        inserted_snapshot: bool,
162    },
163}
164
165impl TaskDataCategory {
166    /// The categories captured by the in-progress snapshot that are not persisted yet.
167    fn from_snapshot_pending(task: &TaskStorage) -> Self {
168        Self::from_flags(
169            task.flags.meta_snapshot_pending(),
170            task.flags.data_snapshot_pending(),
171        )
172    }
173
174    /// The task's unpersisted modifications (used in drain mode, where nothing is captured
175    /// because the map is discarded right after the snapshot).
176    fn from_modified(task: &TaskStorage) -> Self {
177        Self::from_flags(task.flags.meta_modified(), task.flags.data_modified())
178    }
179
180    fn from_flags(meta: bool, data: bool) -> Self {
181        match (meta, data) {
182            (true, true) => Self::All,
183            (true, false) => Self::Meta,
184            (false, true) => Self::Data,
185            (false, false) => unreachable!(
186                "snapshots only persist modified tasks, so at least one category is set"
187            ),
188        }
189    }
190}
191
192/// Encodes task data, using the provided buffer as a scratch space.  Returns a new exactly sized
193/// buffer.
194/// This allows reusing the buffer across multiple encode calls to optimize allocations and
195/// resulting buffer sizes.
196///
197/// TODO: The `Result` return type is an artifact of the bincode `Encode` trait requiring
198/// fallible encoding. In practice, encoding to a `Vec` is infallible (no I/O), and the only
199/// real failure mode — a `TypedSharedReference` whose value type has no bincode impl — is a
200/// programmer error caught by the panic in the caller. Consider making the bincode encoding trait
201/// infallible (i.e. returning `()` instead of `Result<(), EncodeError>`) to eliminate the
202/// spurious `Result` threading throughout the encode path.
203pub(crate) fn encode_task_contents(
204    task: TaskId,
205    data: &TaskStorage,
206    category: SpecificTaskDataCategory,
207    scratch_buffer: &mut TurboBincodeBuffer,
208) -> Result<Box<[u8]>> {
209    scratch_buffer.clear();
210    let mut encoder = new_turbo_bincode_encoder(scratch_buffer);
211    data.encode(category, &mut encoder)?;
212
213    if cfg!(feature = "verify_serialization") {
214        TaskStorage::new()
215            .decode(
216                category,
217                &mut new_turbo_bincode_decoder(&scratch_buffer[..]),
218            )
219            .with_context(|| {
220                format!(
221                    "expected to be able to decode serialized data for '{category:?}' information \
222                     for {task}"
223                )
224            })?;
225    }
226    Ok(Box::from(&scratch_buffer[..]))
227}
228
229/// Converts a task's current state into the [`SnapshotItem`] that persistence writes for it.
230///
231/// Only the categories in `category` are encoded. A `new_task` (per the task's flag) additionally
232/// carries its task type hash so it can be added to the task cache. A GC-deleted task becomes a
233/// [`SnapshotItem::Delete`] tombstone.
234///
235/// This is shared by the regular snapshot path and by [`StorageWriteGuard::track_modification`],
236/// which encodes a task eagerly when it is about to be mutated while a snapshot that captured it
237/// has not persisted it yet. Consistency checks run where items are yielded instead (see
238/// `SnapshotShardIter`), since this may run in the middle of an operation.
239pub(crate) fn encode_snapshot_item(
240    task_id: TaskId,
241    inner: &TaskStorage,
242    category: TaskDataCategory,
243    buffer: &mut TurboBincodeBuffer,
244) -> Result<SnapshotItem> {
245    if task_id.is_transient() {
246        unreachable!("transient task_ids should never be enqueued to be persisted");
247    }
248
249    if inner.flags.deleted() {
250        let task_type_hash = compute_task_type_hash(
251            inner
252                .get_persistent_task_type()
253                .expect("a GC-deleted task must have a task type"),
254        );
255        return Ok(SnapshotItem::Delete {
256            task_id,
257            task_type_hash,
258        });
259    }
260
261    let meta = if category.includes_meta() {
262        Some(
263            encode_task_contents(task_id, inner, SpecificTaskDataCategory::Meta, buffer)
264                .context("failed to encode task meta data")?,
265        )
266    } else {
267        None
268    };
269
270    let data = if category.includes_data() {
271        Some(
272            encode_task_contents(task_id, inner, SpecificTaskDataCategory::Data, buffer)
273                .context("failed to encode task data")?,
274        )
275    } else {
276        None
277    };
278
279    let task_type_hash = if inner.flags.new_task() {
280        let task_type = inner.get_persistent_task_type().expect(
281            "It is not possible for a new_task to not have a persistent_task_type.  Task creation \
282             for persistent tasks uses a single ExecutionContextImpl for creating the task (which \
283             sets new_task) and connect_child (which sets persistent_task_type) and take_snapshot \
284             waits for all operations to complete before we start snapshotting.  So task creation \
285             will always set the task_type.",
286        );
287        Some(compute_task_type_hash(task_type))
288    } else {
289        None
290    };
291
292    Ok(SnapshotItem::Put {
293        task_id,
294        meta,
295        data,
296        task_type_hash,
297        #[cfg(feature = "print_cache_item_size")]
298        stats: Box::new(snapshot_item_stats(inner)),
299    })
300}
301
302/// Captures the cache size statistics of the task state being encoded.
303#[cfg(feature = "print_cache_item_size")]
304fn snapshot_item_stats(inner: &TaskStorage) -> crate::backing_storage::SnapshotItemStats {
305    crate::backing_storage::SnapshotItemStats {
306        task_name: inner
307            .get_persistent_task_type()
308            .map(|t| t.to_string())
309            .unwrap_or_else(|| "<unknown>".to_string()),
310        counts: inner.meta_counts(),
311        output_size: inner.get_output().map_or(0, |output| {
312            turbo_bincode::turbo_bincode_encode(&output).map_or(0, |data| data.len())
313        }),
314    }
315}
316
317pub struct Storage {
318    snapshot_mode: AtomicBool,
319    /// Copy-on-write snapshots of tasks that are currently enqueued for persistence (they have
320    /// `*_snapshot_pending` flags) and then modified.
321    /// Captured as `SnapshotItem` to defend against interior mutability in tasks carrying `State`.
322    /// Entries are removed when the iterator persists the task, and any left over (persisting
323    /// failed) are cleared when the snapshot ends, so the map is empty outside of snapshots.
324    ///
325    /// Lock Ordering: `snapshots` locks are acquired **after** `map` locks (see the comment on
326    /// `map` below). Holding a `snapshots` shard write lock and then trying to take a `map` shard
327    /// write lock is forbidden — it would deadlock against `track_modification_internal` /
328    /// `SnapshotShardIter::next`, which take map first.
329    snapshots: FxDashMap<TaskId, Box<SnapshotItem>>,
330    /// The main storage map
331    ///
332    /// Lock Ordering: Task creation acquires a `task_cache` lock and then inserts into this map.
333    /// Because both datastructures are sharded on different keys, the locks are not 'strictly'
334    /// ordered but we should treat them as such
335    /// Acquiring locks in the opposite order should be defensive
336    ///
337    /// Lock Ordering vs. `snapshots`: `map` locks are acquired **before** `snapshots` locks.
338    /// `track_modification_internal` and `SnapshotShardIter::next` both
339    /// hold a `map` shard write lock (via `StorageWriteGuard` / `map.get_mut`) and then take a
340    /// `snapshots` shard lock.
341    map: FxDashMap<TaskId, Box<TaskStorage>>,
342    /// A shared event notified whenever any task finishes restoring (successfully or not).
343    ///
344    /// Threads waiting for another thread's in-progress restore subscribe to this event,
345    /// then re-check the specific task's `restoring`/`restored` bits after waking.
346    pub(crate) restored: Event,
347    /// Maps `CachedTaskType` → `TaskId` for deduplication of persistent task creation.
348    /// This is backed by the TaskCache table in the database.
349    ///
350    /// LockOrdering: See the comments on [`map`](Self::map).
351    pub task_cache: FxDashMap<CachedTaskTypeArc, TaskId>,
352}
353
354/// Options for [`Storage::new`].
355#[derive(Debug, Clone, Copy)]
356pub struct StorageOptions {
357    /// Number of shards of the task map.
358    pub shard_amount: usize,
359    /// Preallocate a small task map instead of a large one (e.g. for tests or short-lived
360    /// instances).
361    pub small_preallocation: bool,
362}
363
364impl Default for StorageOptions {
365    fn default() -> Self {
366        Self {
367            shard_amount: compute_shard_amount(None, false),
368            small_preallocation: false,
369        }
370    }
371}
372
373#[cfg(test)]
374impl StorageOptions {
375    /// Small storage for unit tests.
376    pub(crate) fn for_tests() -> Self {
377        Self {
378            shard_amount: 2,
379            small_preallocation: true,
380        }
381    }
382}
383
384impl Storage {
385    pub fn new(options: StorageOptions) -> Self {
386        let StorageOptions {
387            shard_amount,
388            small_preallocation,
389        } = options;
390        let map_capacity: usize = if small_preallocation {
391            1024
392        } else {
393            1024 * 1024
394        };
395
396        let map = FxDashMap::with_capacity_and_hasher_and_shard_amount(
397            map_capacity,
398            Default::default(),
399            shard_amount,
400        );
401        Self {
402            snapshot_mode: AtomicBool::new(false),
403            snapshots: FxDashMap::with_capacity_and_hasher_and_shard_amount(
404                // We expect very few updates to this map since it will only happen when updates
405                // race with snapshots.  This never happens in a build and only rarely happens in
406                // dev sessions
407                0,
408                Default::default(),
409                shard_amount,
410            ),
411            map,
412            restored: Event::new(|| || "Storage::restored".to_string()),
413            task_cache: FxDashMap::default(),
414        }
415    }
416
417    /// Mark a newly allocated task as restored (skip DB queries) and new (include in persistence
418    /// snapshots). Optionally sets the `persistent_task_type` eagerly so it's available for
419    /// persistence snapshots without needing to propagate it through `connect_child`.
420    pub fn initialize_new_task(&self, task_id: TaskId, task_type: Option<CachedTaskTypeArc>) {
421        let mut task = self.access_mut(task_id);
422        task.flags.set_restored(TaskDataCategory::All);
423        task.flags.set_new_task(true);
424        task.gc_pin_for_construction();
425        if let Some(task_type) = task_type {
426            task.set_persistent_task_type(task_type);
427            if !task_id.is_transient() {
428                // Unconditional track: a new task's type is always a real persistable change.
429                let _ =
430                    task.track_modification(SpecificTaskDataCategory::Data, "persistent_task_type");
431            }
432        }
433    }
434
435    /// Captures every modified task and returns iterators that persist them. Ends snapshot mode
436    /// when the returned `SnapshotGuard` (held by each shard) is dropped.
437    ///
438    /// Requiring the `SnapshotPhase` ensures the capture runs while operations are excluded, so it
439    /// is consistent: for each modified task it records the modified categories as
440    /// `*_snapshot_pending` and clears the live `modified` flags. Modifications after the
441    /// exclusion then land on the task as normal modifications for the next snapshot, and only
442    /// captured tasks that are modified before they are persisted need a copy-on-write snapshot
443    /// (see `Storage::snapshots`). Encoding happens later, in the returned iterators, which may
444    /// outlive the phase.
445    ///
446    /// `process` is called with the task storage and the categories to encode. It receives a
447    /// mutable scratch buffer that can be reused across iterations to avoid repeated allocations.
448    ///
449    /// `inspect_snapshot_item` allows gathering statistics about encoded items
450    ///
451    /// The returned iterators are guaranteed to be non-empty. If persisting stops before a
452    /// captured task is yielded (it failed), dropping the shard clears the task's
453    /// `*_snapshot_pending` flags: a failed persist disables persistence for the session.
454    ///
455    /// When `drain_entries` is true (shutdown only), the scan drains the map: unmodified entries
456    /// are erased and freed immediately, and the modified entries are moved out into the
457    /// returned shard iterators, which free each task's memory as it is serialized rather than
458    /// after the whole batch is written.
459    pub fn take_snapshot<
460        'l,
461        P: for<'a> Fn(
462                TaskId,
463                &'a TaskStorage,
464                TaskDataCategory,
465                &mut TurboBincodeBuffer,
466            ) -> SnapshotItem
467            + Sync,
468        I: Fn(&SnapshotItem) + Sync,
469    >(
470        &'l self,
471        _phase: &SnapshotPhase<'_>,
472        guard: SnapshotGuard<'l>,
473        process: &'l P,
474        inspect_snapshot_item: &'l I,
475        drain_entries: bool,
476    ) -> Vec<SnapshotShard<'l, P, I>> {
477        let guard = Arc::new(guard);
478
479        let shards: Vec<_> = self.map.shards().iter().collect();
480
481        // The number of shards is much larger than the number of threads, so the effect of the
482        // locks held is negligible.
483        parallel::map_collect::<_, _, Vec<_>>(&shards, |&shard| {
484            // Scan the shard once, building the work this shard's iterator will perform. The two
485            // modes carry different data so that `next` has no per-item `drain` branch:
486            // - keep mode collects the modified `TaskId`s and looks them up again while iterating.
487            // - drain mode erases the unmodified entries here and then moves the remaining
488            //   (modified-only) table out of the map, so the iterator owns and drains it directly.
489            let work = {
490                let mut shard_guard = shard.write();
491                if drain_entries {
492                    shard_guard.retain(|(key, task)| {
493                        let modified_task = task.flags.any_modified();
494                        if modified_task {
495                            debug_assert!(
496                                !key.is_transient(),
497                                "found a modified transient task: {key:?}"
498                            );
499                        }
500                        // Unmodified entries are not part of the snapshot, and neither are deleted
501                        // tasks that were never persisted. Remove and free them now so the table we
502                        // move out below holds only entries to persist.
503                        modified_task && !is_deleted_new_task(task)
504                    });
505                    if shard_guard.is_empty() {
506                        // The shard held only unmodified entries, which we've now erased and freed.
507                        // No iterator is created for an empty shard.
508                        return None;
509                    }
510                    // Move the modified-only table out of the map. Iterating it frees each task box
511                    // as it is serialized, and the shard's table allocation is released here.
512                    ShardWork::Drain(std::mem::take(&mut *shard_guard).into_iter())
513                } else {
514                    let mut modified = Vec::new();
515                    for (key, task) in shard_guard.iter_mut() {
516                        if is_deleted_new_task(task) {
517                            // Nothing on disk to write or tombstone. Clear its flags and let
518                            // eviction free the entry.
519                            task.flags.set_meta_modified(false);
520                            task.flags.set_data_modified(false);
521                            continue;
522                        }
523                        // Only check modified flags — transient tasks never have modified flags set
524                        // (track_modification guards against it), so this naturally excludes them.
525                        // new_task always comes with modified flags (set_persistent_task_type calls
526                        // track_modification), so any_modified() is sufficient.
527                        if task.flags.any_modified() {
528                            debug_assert!(
529                                !key.is_transient(),
530                                "found a modified transient task: {key:?}"
531                            );
532                            debug_assert!(!task.flags.any_snapshot_pending());
533                            // Capture: move the modified categories to `*_snapshot_pending`.
534                            // `new_task` stays set until the task is persisted; it can't be set
535                            // again on an existing task, so it still reflects the capture.
536                            let flags = &mut task.flags;
537                            flags.set_meta_snapshot_pending(flags.meta_modified());
538                            flags.set_data_snapshot_pending(flags.data_modified());
539                            flags.set_meta_modified(false);
540                            flags.set_data_modified(false);
541                            modified.push(*key);
542                        }
543                    }
544                    if modified.is_empty() {
545                        return None;
546                    }
547                    ShardWork::Keep(modified)
548                }
549            };
550
551            Some(SnapshotShard {
552                work,
553                storage: self,
554                process,
555                inspect_snapshot_item,
556                _guard: guard.clone(),
557            })
558        })
559        .into_iter()
560        .flatten()
561        .collect()
562    }
563
564    /// Enter snapshot mode and return a guard that will call `end_snapshot` on drop.
565    pub fn start_snapshot(&self) -> SnapshotGuard<'_> {
566        // Enter snapshot mode so track_modification copies captured tasks
567        // (copy-on-write) before mutating them.
568        self.snapshot_mode.store(true, Ordering::Release);
569        SnapshotGuard::new(self)
570    }
571
572    /// End snapshot mode.
573    ///
574    /// Captured tasks are persisted by the shard iterators, which also remove their `snapshots`
575    /// entries. If persisting failed, the dropped shards already cleared the pending flags of
576    /// unyielded tasks, so no new entries can appear; the ones left behind are dropped here
577    /// (persistence is disabled for the session after a failure).
578    fn end_snapshot(&self) {
579        self.snapshot_mode.store(false, Ordering::Release);
580        self.snapshots.clear();
581        // If we are saving a non-trivial amount of memory just clear it out.
582        if self.snapshots.capacity() > 1024 {
583            self.snapshots.shrink_to_fit();
584        }
585    }
586
587    /// Returns true if actively snapshotting.
588    fn snapshot_mode(&self) -> bool {
589        self.snapshot_mode.load(Ordering::Acquire)
590    }
591
592    pub fn access_mut(&self, key: TaskId) -> StorageWriteGuard<'_> {
593        let inner = match self.map.entry(key) {
594            dashmap::mapref::entry::Entry::Occupied(e) => e.into_ref(),
595            dashmap::mapref::entry::Entry::Vacant(e) => e.insert(Box::new(TaskStorage::new())),
596        };
597        StorageWriteGuard {
598            storage: self,
599            inner: inner.into(),
600        }
601    }
602
603    /// Like [`Self::access_mut`], but keeps the map entry so the caller can still remove it.
604    pub fn access_entry_mut(&self, key: TaskId) -> TaskEntryGuard<'_> {
605        let entry = match self.map.entry(key) {
606            dashmap::mapref::entry::Entry::Occupied(e) => e,
607            dashmap::mapref::entry::Entry::Vacant(e) => {
608                e.insert_entry(Box::new(TaskStorage::new()))
609            }
610        };
611        TaskEntryGuard {
612            storage: self,
613            entry,
614        }
615    }
616
617    /// Read-only access to an already resident task. Returns `None` if the task isnt in memory
618    /// resident. The closure runs while a shard read lock is held, so it must be cheap and must
619    /// not re-enter the map.
620    pub fn with_task<R>(&self, key: TaskId, f: impl FnOnce(&TaskStorage) -> R) -> Option<R> {
621        let task = self.map.get(&key)?;
622        Some(f(task.value()))
623    }
624
625    /// The number of tasks resident in the map.
626    #[doc(hidden)]
627    pub fn resident_task_count_for_testing(&self) -> usize {
628        self.map.len()
629    }
630
631    /// The number of shards in the resident map. GC seeds one `ScanShard` job per index; the slice
632    /// returned by `map.shards()` is fixed for the map's lifetime, so an index is a stable handle
633    /// to one shard.
634    pub fn shard_count(&self) -> usize {
635        self.map.shards().len()
636    }
637
638    /// Scans a **single** shard by index, invoking `on_candidate` for each resident task whose
639    /// storage passes [`TaskStorage::gc_collectible`].
640    pub fn gc_scan_shard(&self, index: usize, mut on_candidate: impl FnMut(TaskId)) {
641        let shard = self.map.shards()[index].read();
642        for (task_id, task) in shard.iter() {
643            if task.gc_collectible() {
644                on_candidate(*task_id);
645            }
646        }
647    }
648
649    /// Return the set of all known live roots.
650    pub fn gc_scan_roots(&self) -> impl Iterator<Item = TaskId> {
651        let per_shard: Vec<Vec<TaskId>> =
652            parallel::map_collect(&(0..self.shard_count()).collect::<Vec<_>>(), |&index| {
653                let mut roots = Vec::new();
654                let shard = self.map.shards()[index].read();
655                for (task_id, task) in shard.iter() {
656                    if !task_id.is_transient() && task.gc_is_root() {
657                        roots.push(*task_id);
658                    }
659                }
660                roots
661            });
662
663        per_shard.into_iter().flatten()
664    }
665
666    /// Captures the aggregation edges of all resident tasks, for verification of the aggregation
667    /// graph. Only meaningful when no aggregation updates run concurrently.
668    #[cfg(any(test, feature = "verify_aggregation_graph"))]
669    pub fn aggregation_edges_for_verification(
670        &self,
671    ) -> Vec<crate::backend::operation::TaskAggregationEdges> {
672        let mut result = Vec::new();
673        for shard in self.map.shards() {
674            let shard = shard.read();
675            for (task_id, task) in shard.iter() {
676                result.extend(task.aggregation_edges_for_verification(*task_id));
677            }
678        }
679        result
680    }
681
682    pub fn access_pair_mut(
683        &self,
684        key1: TaskId,
685        key2: TaskId,
686    ) -> (StorageWriteGuard<'_>, StorageWriteGuard<'_>) {
687        let (a, b) = get_disjoint_mut(&self.map, key1, key2, || Box::new(TaskStorage::new()));
688        (
689            StorageWriteGuard {
690                storage: self,
691                inner: a,
692            },
693            StorageWriteGuard {
694                storage: self,
695                inner: b,
696            },
697        )
698    }
699
700    /// Locks the resident task `key`, if that is possible without blocking, also while the caller
701    /// holds another task's guard. Returns `None` when `key`'s shard is locked (also when it's the
702    /// shard of a task the caller holds: shard locks aren't reentrant), or when `key` isn't
703    /// resident (it is not inserted).
704    pub fn try_access_mut(&self, key: TaskId) -> Option<StorageWriteGuard<'_>> {
705        match self.map.try_get_mut(&key) {
706            TryResult::Present(inner) => Some(StorageWriteGuard {
707                storage: self,
708                inner: inner.into(),
709            }),
710            TryResult::Absent | TryResult::Locked => None,
711        }
712    }
713
714    pub fn drop_contents(&self) {
715        drop_contents(&self.map);
716        drop_contents(&self.snapshots);
717    }
718
719    /// Drop the `task_cache` map, freeing its memory.
720    pub(crate) fn drop_task_cache(&self) {
721        drop_contents(&self.task_cache);
722    }
723
724    /// Evict tasks from in-memory storage after a successful snapshot.
725    ///
726    /// Iterates all tasks and applies the eviction level returned by
727    /// `TaskStorage::evictability()`:
728    /// - `Full`: remove from map entirely
729    /// - `DataAndMeta`: drop both data and meta fields, keep task in map
730    /// - `DataOnly`: drop data fields only
731    /// - `MetaOnly`: drop meta fields only
732    /// - `No`: skip
733    ///
734    /// Must be called when NOT in snapshot mode (i.e., after `end_snapshot()`).
735    pub fn evict_after_snapshot(&self, parent_span: Option<Id>) -> EvictionCounts {
736        let span = tracing::trace_span!(
737            parent: parent_span,
738            "evict_after_snapshot",
739            total_task_cache_keys = self.task_cache.len(),
740            total_map_keys = self.map.len(),
741            counts = tracing::field::Empty,
742        )
743        .entered();
744        debug_assert!(
745            !self.snapshot_mode(),
746            "evict_after_snapshot must not be called during snapshot mode"
747        );
748
749        let counts: Vec<EvictionCounts> = parallel::map_collect(self.map.shards(), |shard| {
750            let mut shard = shard.write();
751            let mut evicted = EvictionCounts::default();
752            // task_cache removals that we couldn't perform inline because the target shard
753            // was contended. We defer them until after the map shard lock is released to
754            // avoid a lock cycle with get_or_create_persistent_task, which takes task_cache
755            // before map. Allocated lazily on first conflict.
756            let mut deferred_task_cache_removals: Vec<CachedTaskTypeArc> = Vec::new();
757            shard.retain(|(task_id, task)| {
758                // Transient tasks can not be evicted at all, unless they are fully
759                // delete by the GC.
760                if task_id.is_transient() && !task.flags.deleted() {
761                    evicted.unevictable_reasons[UnevictableReason::Transient.index()] += 1;
762                    // A task that is executing would only inflate its forward sets again.
763                    if !task.is_in_progress() {
764                        task.shrink_edge_sets();
765                    }
766                    return true;
767                }
768                if task.flags.deleted() {
769                    if !task.flags.new_task() && task.flags.any_modified() {
770                        // Its tombstone is still pending. Its neighbours' halves of the torn-down
771                        // edges reach disk with the next snapshot, so dropping it now would leave
772                        // its last snapshot live on disk, to be restored later as a live task with
773                        // dangling edges.
774                        evicted.unevictable_reasons
775                            [UnevictableReason::MarkedForDeletion.index()] += 1;
776                        return true;
777                    }
778                    // Tombstoned, or never persisted: nothing on disk to protect. GC already
779                    // removed it from `task_cache`, so nothing can hand out its
780                    // id, and `task_by_type` finds nothing once the tombstone
781                    // is committed.
782                    evicted.full += 1;
783                    return false;
784                }
785                let (key_evictability, value_evictability) = task.evictability();
786                match key_evictability {
787                    KeyEvictability::Evictable => {
788                        // The task type is persisted to backing storage (new_task = false),
789                        // so task_cache is a pure perf cache. Remove it now; it will be
790                        // re-populated by task_by_type() on the next cache miss.
791                        let task_type = task.get_persistent_task_type().unwrap();
792                        // Only try to acquire the lock, if we cannot just remove at the end
793                        // Because `get_or_create_task` acquires 'task_cache' then `storage.map` and
794                        // we do the opposite we need to be defensive here.  Attempting here is just
795                        // an optimization to avoid pushing into `deferred_task_cache_removals`
796                        match try_lock_and_remove(&self.task_cache, task_type.as_ref()) {
797                            TryLockAndRemove::Removed => {
798                                evicted.key_evictions += 1;
799                            }
800                            TryLockAndRemove::NotFound => {
801                                // Generally this should be rare, it more or less implies something
802                                // else is concurrently holding the Arc
803                            }
804                            TryLockAndRemove::WouldBlock => {
805                                // Contention, to avoid a deadlock just defer
806                                deferred_task_cache_removals.push(task_type.clone());
807                            }
808                        }
809                    }
810                    KeyEvictability::AlreadyEvicted | KeyEvictability::Unevictable => {}
811                }
812                match value_evictability {
813                    ValueEvictability::Evictable { meta, data } => {
814                        match task.drop_partial(data, meta) {
815                            DropPartialOutcome::Empty => {
816                                evicted.full += 1;
817                                return false;
818                            }
819                            DropPartialOutcome::HasResidue => {
820                                // The category that stays resident keeps its edge sets.
821                                task.shrink_edge_sets();
822                                if data && meta {
823                                    evicted.data_and_meta += 1;
824                                } else if data {
825                                    evicted.data_only += 1;
826                                } else {
827                                    debug_assert!(meta);
828                                    evicted.meta_only += 1;
829                                }
830                            }
831                        }
832                    }
833                    ValueEvictability::Unevictable(reason) => {
834                        evicted.unevictable_reasons[reason.index()] += 1;
835                        // Kept in memory as it is: flatten its edge sets, unless it is executing
836                        // (or about to), when it would only inflate its forward sets again.
837                        if reason != UnevictableReason::InProgress {
838                            task.shrink_edge_sets();
839                        }
840                    }
841                }
842                true
843            });
844            // Shrink the shard if it's less than half full, to reclaim slack capacity
845            // after bulk evictions. We already hold the write lock, so this is free
846            // from a locking perspective. TaskId hashing is cheap (it's just an integer).
847            let len = shard.len();
848            if shard.capacity() > len * 2 {
849                shard.shrink_to(len, |(k, _v)| self.map.hasher().hash_one(k));
850            }
851            // Release the map shard lock before draining deferred removals so that a thread
852            // holding a task_cache shard lock and waiting on this map shard can make progress.
853            drop(shard);
854            for task_type in deferred_task_cache_removals {
855                if self.task_cache.remove(task_type.as_ref()).is_some() {
856                    evicted.key_evictions += 1;
857                }
858            }
859            evicted
860        });
861
862        let mut totals = EvictionCounts::default();
863        for evicted in counts {
864            totals += evicted;
865        }
866        // Shrink task_cache only when we evicted more entries than remain — i.e. the map
867        // is less than half full. Rehashing each surviving CachedTaskType isn't free, so
868        // we gate it on meaningful slack. Within that, walk shards in parallel and shrink
869        // each one independently if it is itself less than half full.
870        if totals.key_evictions > self.task_cache.len() {
871            parallel::for_each(self.task_cache.shards(), |shard| {
872                let mut shard = shard.write();
873                let len = shard.len();
874                if shard.capacity() > len * 2 {
875                    shard.shrink_to(len, |(k, _v)| self.task_cache.hasher().hash_one(k));
876                }
877            });
878        }
879        span.record("counts", tracing::field::display(&totals));
880
881        totals
882    }
883}
884
885/// A write guard that still owns its map entry, so the task can be removed under the lock that is
886/// already held.
887///
888/// Use [`Storage::access_entry_mut`] to obtain one. Convert it with [`Self::into_write_guard`] once
889/// removal is no longer a possibility, or call [`Self::discard`] to drop the entry outright.
890pub struct TaskEntryGuard<'a> {
891    storage: &'a Storage,
892    entry: dashmap::mapref::entry::OccupiedEntry<'a, TaskId, Box<TaskStorage>>,
893}
894
895impl<'a> TaskEntryGuard<'a> {
896    /// Removes this task's entry.
897    pub fn discard(self) {
898        self.entry.remove();
899    }
900
901    /// Gives up the ability to remove the entry, yielding an ordinary write guard.
902    pub fn into_write_guard(self) -> StorageWriteGuard<'a> {
903        StorageWriteGuard {
904            storage: self.storage,
905            inner: self.entry.into_ref().into(),
906        }
907    }
908}
909
910impl Deref for TaskEntryGuard<'_> {
911    type Target = TaskStorage;
912    fn deref(&self) -> &Self::Target {
913        self.entry.get()
914    }
915}
916
917impl DerefMut for TaskEntryGuard<'_> {
918    fn deref_mut(&mut self) -> &mut Self::Target {
919        self.entry.get_mut()
920    }
921}
922
923pub struct StorageWriteGuard<'a> {
924    storage: &'a Storage,
925    inner: RefMut<'a, TaskId, Box<TaskStorage>>,
926}
927
928impl StorageWriteGuard<'_> {
929    /// Tracks mutation of this task.
930    #[inline(always)]
931    pub fn track_modification(
932        &mut self,
933        category: SpecificTaskDataCategory,
934        #[allow(unused_variables)] name: &str,
935    ) -> TrackOutcome {
936        debug_assert!(
937            !self.inner.key().is_transient(),
938            "transient task_ids should never be enqueued to be persisted"
939        );
940        self.track_modification_internal(
941            category,
942            #[cfg(feature = "trace_task_modification")]
943            name,
944        )
945    }
946
947    fn track_modification_internal(
948        &mut self,
949        category: SpecificTaskDataCategory,
950        #[cfg(feature = "trace_task_modification")] name: &str,
951    ) -> TrackOutcome {
952        // Transient tasks are never persisted, so tracking modifications is meaningless.
953        // All callers (TaskGuard, initialize_new_task) already
954        // guard against this, but we enforce it here as defense-in-depth.
955        debug_assert!(
956            !self.inner.key().is_transient(),
957            "track_modification called on transient task {:?}",
958            self.inner.key()
959        );
960        if self.inner.flags.is_modified(category) {
961            return TrackOutcome::NoChange;
962        }
963        #[cfg(feature = "trace_task_modification")]
964        let _span = tracing::trace_span!("mark_modified", name).entered();
965        // If the in-progress snapshot captured this task and hasn't persisted it yet, freeze the
966        // captured categories before this mutation lands (copy-on-write). Only the first
967        // modification after the capture needs to do this; later ones find the entry. Pending
968        // flags only exist during snapshot mode: tasks a failed persist didn't reach are cleared
969        // when their shard drops, before the snapshot ends.
970        let inserted_snapshot =
971            self.inner.flags.any_snapshot_pending() && self.maybe_encode_for_snapshot();
972        self.inner.flags.set_modified(category, true);
973        TrackOutcome::Tracked {
974            category,
975            inserted_snapshot,
976        }
977    }
978
979    /// Stores a copy-on-write snapshot of the task's captured, not yet persisted
980    /// (`*_snapshot_pending`) categories in `snapshots`, for the racing persistence to write
981    /// instead of the live data. Returns whether it inserted one: `false` if the task already
982    /// has an entry (an earlier modification after the capture made it).
983    #[cold]
984    fn maybe_encode_for_snapshot(&self) -> bool {
985        let task_id = *self.inner.key();
986        if self.storage.snapshots.contains_key(&task_id) {
987            return false;
988        }
989        let mut buffer = TurboBincodeBuffer::new();
990        let item = encode_snapshot_item(
991            task_id,
992            &self.inner,
993            TaskDataCategory::from_snapshot_pending(&self.inner),
994            &mut buffer,
995        )
996        .unwrap_or_else(|err| panic!("Serializing task {task_id} for a snapshot failed: {err:?}"));
997        self.storage.snapshots.insert(task_id, Box::new(item));
998        true
999    }
1000
1001    /// Reverse a [`TrackOutcome`] produced by [`Self::track_modification`] when the mutation it
1002    /// guarded changed nothing persistable.
1003    ///
1004    /// # Correctness
1005    ///
1006    /// The `outcome` MUST be applied to the **same `StorageWriteGuard`** that produced it, with the
1007    /// map shard write lock held continuously in between — i.e. `track_modification`, the mutation,
1008    /// and `undo_track_modification` all run within one guard's lifetime. The guard holds its shard
1009    /// write lock for its whole lifetime, so this guarantees no other thread observed the tracked
1010    /// state, and that `inserted_snapshot` still describes reality (the `snapshots` entry is only
1011    /// mutated under that lock). Because it records whether *this* call created the state, undo
1012    /// never clears a flag or snapshot entry that a
1013    /// prior modification owns.
1014    pub fn undo_track_modification(&mut self, outcome: TrackOutcome) {
1015        match outcome {
1016            TrackOutcome::NoChange => {}
1017            TrackOutcome::Tracked {
1018                category,
1019                inserted_snapshot,
1020            } => {
1021                self.inner.flags.set_modified(category, false);
1022                if inserted_snapshot {
1023                    self.storage.snapshots.remove(self.inner.key());
1024                }
1025            }
1026        }
1027    }
1028}
1029
1030impl Deref for StorageWriteGuard<'_> {
1031    type Target = TaskStorage;
1032
1033    fn deref(&self) -> &Self::Target {
1034        &self.inner
1035    }
1036}
1037
1038impl DerefMut for StorageWriteGuard<'_> {
1039    fn deref_mut(&mut self) -> &mut Self::Target {
1040        &mut self.inner
1041    }
1042}
1043
1044/// How big of a buffer to allocate initially. Based on metrics from a large
1045/// application this should cover about 98% of values with no resizes.
1046const SCRATCH_BUFFER_INITIAL_SIZE: usize = 4096;
1047
1048/// State machine for a per-thread scratch buffer slot.
1049///
1050/// Transitions:
1051/// - `Uninit` → `Taken` (first take)
1052/// - `Available` → `Taken` (subsequent takes)
1053/// - `Taken` → `Available` (return)
1054///
1055/// Any other transition is a bug (e.g. double-take or double-return).
1056#[derive(Default)]
1057enum ScratchBufferSlot {
1058    /// No buffer has been allocated on this thread yet.
1059    #[default]
1060    Uninit,
1061    /// The buffer is currently checked out.
1062    Taken,
1063    /// The buffer is available for reuse.
1064    Available(TurboBincodeBuffer),
1065}
1066
1067pub struct SnapshotGuard<'l> {
1068    storage: &'l Storage,
1069    /// Per-thread scratch buffers for encoding task data. Buffers are taken
1070    /// by `SnapshotShardIter` on creation and returned on drop, allowing reuse
1071    /// across multiple shards processed by the same thread. When the guard is
1072    /// dropped (after all iterators are done), the `ThreadLocal` drops too,
1073    /// freeing all buffers.
1074    scratch_buffers: ThreadLocal<Cell<ScratchBufferSlot>>,
1075}
1076
1077impl<'l> SnapshotGuard<'l> {
1078    fn new(storage: &'l Storage) -> Self {
1079        Self {
1080            storage,
1081            scratch_buffers: ThreadLocal::new(),
1082        }
1083    }
1084
1085    fn take_scratch_buffer(&self) -> TurboBincodeBuffer {
1086        let cell = self.scratch_buffers.get_or_default();
1087        match cell.take() {
1088            ScratchBufferSlot::Available(buf) => {
1089                cell.set(ScratchBufferSlot::Taken);
1090                buf
1091            }
1092            ScratchBufferSlot::Uninit => {
1093                cell.set(ScratchBufferSlot::Taken);
1094                TurboBincodeBuffer::with_capacity(SCRATCH_BUFFER_INITIAL_SIZE)
1095            }
1096            ScratchBufferSlot::Taken => {
1097                panic!("scratch buffer taken twice without being returned");
1098            }
1099        }
1100    }
1101
1102    fn return_scratch_buffer(&self, buffer: TurboBincodeBuffer) {
1103        let cell = self.scratch_buffers.get_or_default();
1104        match cell.take() {
1105            ScratchBufferSlot::Taken => cell.set(ScratchBufferSlot::Available(buffer)),
1106            ScratchBufferSlot::Available(_) => {
1107                panic!("scratch buffer returned without being taken (already available)");
1108            }
1109            ScratchBufferSlot::Uninit => {
1110                panic!("scratch buffer returned without being taken (uninit)");
1111            }
1112        }
1113    }
1114}
1115
1116impl Drop for SnapshotGuard<'_> {
1117    fn drop(&mut self) {
1118        self.storage.end_snapshot();
1119    }
1120}
1121
1122/// The work a single shard's iterator performs, with the snapshot mode encoded in the data rather
1123/// than a runtime flag re-checked per item. Built by `take_snapshot`'s scan.
1124enum ShardWork {
1125    /// Normal snapshot: the tasks captured by the scan. Each is looked up in the map while
1126    /// iterating and persisted from its copy-on-write snapshot (if it was modified since the
1127    /// capture) or from its live state, then its `*_snapshot_pending` flags are cleared.
1128    Keep(Vec<TaskId>),
1129    /// Shutdown drain: the scan already erased the unmodified entries and moved the remaining
1130    /// (modified-only) shard table out of the map. The iterator owns that table and drains it
1131    /// directly, freeing each task box as it is serialized. No second map lookup, no flag
1132    /// bookkeeping (the whole map is discarded right after this snapshot).
1133    Drain(hash_table::IntoIter<(TaskId, Box<TaskStorage>)>),
1134}
1135
1136pub struct SnapshotShard<'l, P, I> {
1137    work: ShardWork,
1138    storage: &'l Storage,
1139    process: &'l P,
1140    inspect_snapshot_item: &'l I,
1141    /// Held for its `Drop` impl — ensures snapshot mode ends when all shards are done.
1142    _guard: Arc<SnapshotGuard<'l>>,
1143}
1144
1145impl<'l, P, I> IntoIterator for SnapshotShard<'l, P, I>
1146where
1147    P: Fn(TaskId, &TaskStorage, TaskDataCategory, &mut TurboBincodeBuffer) -> SnapshotItem + Sync,
1148    I: Fn(&SnapshotItem) + Sync,
1149{
1150    type Item = SnapshotItem;
1151    type IntoIter = SnapshotShardIter<'l, P, I>;
1152
1153    fn into_iter(self) -> Self::IntoIter {
1154        let buffer = self._guard.take_scratch_buffer();
1155        SnapshotShardIter {
1156            shard: self,
1157            buffer,
1158        }
1159    }
1160}
1161
1162/// Iterator over a single shard's snapshot items. Holds a thread-local scratch
1163/// buffer for the duration of iteration and returns it on drop.
1164pub struct SnapshotShardIter<'l, P, I> {
1165    shard: SnapshotShard<'l, P, I>,
1166    buffer: TurboBincodeBuffer,
1167}
1168
1169impl<'l, P, I> Iterator for SnapshotShardIter<'l, P, I>
1170where
1171    P: Fn(TaskId, &TaskStorage, TaskDataCategory, &mut TurboBincodeBuffer) -> SnapshotItem + Sync,
1172    I: Fn(&SnapshotItem) + Sync,
1173{
1174    type Item = SnapshotItem;
1175
1176    fn next(&mut self) -> Option<Self::Item> {
1177        let process = self.shard.process;
1178        let inspect_snapshot_item = self.shard.inspect_snapshot_item;
1179        let buffer = &mut self.buffer;
1180        match &mut self.shard.work {
1181            ShardWork::Keep(captured) => {
1182                // Pop only once the task is done: if encoding or inspection panics, the task
1183                // stays in `captured` so dropping the shard clears its pending flags.
1184                let &task_id = captured.last()?;
1185                let storage = self.shard.storage;
1186                let mut inner = storage.map.get_mut(&task_id).unwrap();
1187                debug_assert_persistable(&inner);
1188                // If the task was modified since the capture, `track_modification` already encoded
1189                // its captured state; persist that instead of the (newer) live data.
1190                let item = match storage.snapshots.remove(&task_id) {
1191                    Some((_, item)) => *item,
1192                    None => process(
1193                        task_id,
1194                        &inner,
1195                        TaskDataCategory::from_snapshot_pending(&inner),
1196                        buffer,
1197                    ),
1198                };
1199                inspect_snapshot_item(&item);
1200                // The captured state is persisted. Modifications since the capture (if any) are
1201                // already tracked by the live `modified` flags.
1202                inner.flags.set_meta_snapshot_pending(false);
1203                inner.flags.set_data_snapshot_pending(false);
1204                inner.flags.set_new_task(false);
1205                captured.pop();
1206                Some(item)
1207            }
1208            ShardWork::Drain(entries) => {
1209                // Shutdown only: the scan already moved this shard's modified entries out of the
1210                // map, so we own each `Box<TaskStorage>` here. Serialize from a borrow of the owned
1211                // box and let it drop at the end of this branch — freeing the task's memory as it
1212                // is persisted rather than after the whole batch is written. We skip the flag
1213                // bookkeeping the normal path does, since the entire map is discarded right after
1214                // this snapshot.
1215                let (task_id, inner) = entries.next()?;
1216                debug_assert_persistable(&inner);
1217                let item = process(
1218                    task_id,
1219                    &inner,
1220                    TaskDataCategory::from_modified(&inner),
1221                    buffer,
1222                );
1223                inspect_snapshot_item(&item);
1224                Some(item)
1225            }
1226        }
1227    }
1228}
1229
1230/// Whether `task` was collected by GC before it was ever persisted. It has nothing on disk, so the
1231/// snapshot skips it and eviction drops it.
1232fn is_deleted_new_task(task: &TaskStorage) -> bool {
1233    task.flags.deleted() && task.flags.new_task()
1234}
1235
1236/// Consistency check for a task the snapshot iterators are about to yield. Runs here rather than
1237/// in `encode_snapshot_item`, which copy-on-write may call in the middle of an operation.
1238fn debug_assert_persistable(inner: &TaskStorage) {
1239    debug_assert!(
1240        !is_deleted_new_task(inner),
1241        "a scanned GC-deleted task must be persisted; the capture skips never-persisted ones"
1242    );
1243}
1244
1245impl<P, I> Drop for SnapshotShardIter<'_, P, I> {
1246    fn drop(&mut self) {
1247        self.shard
1248            ._guard
1249            .return_scratch_buffer(std::mem::take(&mut self.buffer));
1250    }
1251}
1252
1253impl<P, I> Drop for SnapshotShard<'_, P, I> {
1254    /// Tasks still in a `Keep` list were captured but not persisted: persisting stopped early
1255    /// (it failed or panicked). Persisting is disabled for the session after that, so clear their
1256    /// pending flags now. This runs before `end_snapshot` (each shard holds a guard reference), so
1257    /// pending flags never outlive snapshot mode and copy-on-write doesn't need to check it.
1258    fn drop(&mut self) {
1259        if let ShardWork::Keep(captured) = &self.work {
1260            for task_id in captured {
1261                if let Some(mut inner) = self.storage.map.get_mut(task_id) {
1262                    inner.flags.set_meta_snapshot_pending(false);
1263                    inner.flags.set_data_snapshot_pending(false);
1264                }
1265            }
1266        }
1267    }
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272    use turbo_bincode::TurboBincodeBuffer;
1273    use turbo_tasks::TaskId;
1274
1275    use super::{
1276        SnapshotGuard, SnapshotShard, SpecificTaskDataCategory, Storage, StorageOptions,
1277        TaskDataCategory, TaskStorage, TrackOutcome, UnevictableReason, encode_task_contents,
1278    };
1279    use crate::{
1280        backend::snapshot_coordinator::SnapshotCoordinator, backing_storage::SnapshotItem,
1281        data::OutputValue,
1282    };
1283
1284    fn non_transient_task(id: u32) -> TaskId {
1285        // TRANSIENT_TASK_BIT is 0x2000_0000; any id without that bit is non-transient.
1286        TaskId::new(id).expect("id must be non-zero")
1287    }
1288
1289    #[test]
1290    fn new_task_is_pinned_during_construction() {
1291        let storage = Storage::new(StorageOptions::for_tests());
1292        let task_id = non_transient_task(1);
1293
1294        storage.initialize_new_task(task_id, None);
1295
1296        let task = storage.access_mut(task_id);
1297        assert_eq!(task.gc_transient_ref_count(), 1);
1298        assert!(!task.gc_collectible());
1299    }
1300
1301    /// A never-persisted task that GC deleted has nothing on disk, so eviction drops it even while
1302    /// it is still modified (no snapshot ran, as after an interrupted GC pass).
1303    // `evict_after_snapshot` uses `parallel::map_collect`, which requires a multi-threaded runtime.
1304    #[tokio::test(flavor = "multi_thread")]
1305    async fn gc_deleted_new_task_is_evicted_while_modified() {
1306        let storage = Storage::new(StorageOptions::for_tests());
1307        let task_id = non_transient_task(1);
1308        {
1309            let mut guard = storage.access_mut(task_id);
1310            guard.flags.set_new_task(true);
1311            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "teardown");
1312            guard.flags.set_deleted(true);
1313        }
1314
1315        storage.evict_after_snapshot(None);
1316        assert!(storage.with_task(task_id, |_| ()).is_none());
1317    }
1318
1319    /// A snapshot skips a never-persisted task that GC deleted: there is nothing on disk to write
1320    /// or tombstone. A shard holding only such tasks yields nothing.
1321    #[tokio::test(flavor = "multi_thread")]
1322    async fn snapshot_skips_gc_deleted_new_task() {
1323        let storage = Storage::new(StorageOptions::for_tests());
1324        let task_id = non_transient_task(1);
1325        {
1326            let mut guard = storage.access_mut(task_id);
1327            guard.flags.set_new_task(true);
1328            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "teardown");
1329            guard.flags.set_deleted(true);
1330        }
1331
1332        let snapshot_guard = storage.start_snapshot();
1333        let shards = take_snapshot(
1334            &storage,
1335            snapshot_guard,
1336            &dummy_process,
1337            &noop_inspect,
1338            false,
1339        );
1340        assert_eq!(shards.into_iter().flatten().count(), 0);
1341
1342        let guard = storage.access_mut(task_id);
1343        assert!(!guard.flags.any_modified());
1344        assert!(!guard.flags.any_snapshot_pending());
1345    }
1346
1347    /// A persisted task that GC deleted keeps its tombstone pending until a snapshot writes it, so
1348    /// eviction must leave it resident, as after an interrupted GC pass.
1349    #[tokio::test(flavor = "multi_thread")]
1350    async fn gc_deleted_task_with_pending_tombstone_survives_eviction() {
1351        let storage = Storage::new(StorageOptions::for_tests());
1352        let task_id = non_transient_task(1);
1353        {
1354            let mut guard = storage.access_mut(task_id);
1355            let _ = guard.track_modification(SpecificTaskDataCategory::Meta, "gc_deleted");
1356            guard.flags.set_deleted(true);
1357        }
1358
1359        let counts = storage.evict_after_snapshot(None);
1360        assert!(storage.with_task(task_id, |_| ()).is_some());
1361        assert_eq!(
1362            counts.unevictable_reasons[UnevictableReason::MarkedForDeletion.index()],
1363            1
1364        );
1365    }
1366
1367    /// A process fn that returns a non-empty SnapshotItem so the iterator doesn't
1368    /// silently skip items via the "encoding failed" error path.
1369    fn dummy_process(
1370        task_id: TaskId,
1371        _: &super::TaskStorage,
1372        _: TaskDataCategory,
1373        _: &mut TurboBincodeBuffer,
1374    ) -> SnapshotItem {
1375        SnapshotItem::Put {
1376            task_id,
1377            meta: Some(Box::default()),
1378            data: None,
1379            task_type_hash: None,
1380            #[cfg(feature = "print_cache_item_size")]
1381            stats: Default::default(),
1382        }
1383    }
1384
1385    /// An `inspect_snapshot_item` callback that ignores the items.
1386    fn noop_inspect(_: &SnapshotItem) {}
1387
1388    /// Calls `Storage::take_snapshot` inside a snapshot phase of a local coordinator, standing in
1389    /// for the backend's operation exclusion.
1390    fn take_snapshot<'l, P, I>(
1391        storage: &'l Storage,
1392        guard: SnapshotGuard<'l>,
1393        process: &'l P,
1394        inspect_snapshot_item: &'l I,
1395        drain_entries: bool,
1396    ) -> Vec<SnapshotShard<'l, P, I>>
1397    where
1398        P: Fn(TaskId, &TaskStorage, TaskDataCategory, &mut TurboBincodeBuffer) -> SnapshotItem
1399            + Sync,
1400        I: Fn(&SnapshotItem) + Sync,
1401    {
1402        let coordinator = SnapshotCoordinator::new();
1403        let phase = coordinator
1404            .try_begin_snapshot()
1405            .expect("no operations are running");
1406        storage.take_snapshot(&phase, guard, process, inspect_snapshot_item, drain_entries)
1407    }
1408
1409    /// Regression test: a task modified before a snapshot and then modified *again* during
1410    /// snapshot iteration must serialize the captured state and carry the new modification
1411    /// forward to the next cycle.
1412    ///
1413    /// Sequence of events:
1414    /// 1. Task is modified (data_modified = true).
1415    /// 2. `start_snapshot` puts us in snapshot mode.
1416    /// 3. `take_snapshot` captures the task: `data_modified` moves to `data_snapshot_pending`.
1417    /// 4. **Between capture and iteration**: `track_modification` is called on the same category.
1418    ///    The task is pending and has no copy-on-write snapshot yet, so its captured state is
1419    ///    encoded into `snapshots`, and `data_modified` is set again.
1420    /// 5. `SnapshotShardIter::next` yields the pre-encoded item, removes the snapshots entry, and
1421    ///    clears the pending flag. `data_modified` stays set for the next cycle.
1422    // `take_snapshot` uses `parallel::map_collect` which calls `block_in_place` internally,
1423    // requiring a multi-threaded Tokio runtime.
1424    #[tokio::test(flavor = "multi_thread")]
1425    async fn modify_during_snapshot_clears_live_modified_flags() {
1426        let storage = Storage::new(StorageOptions::for_tests());
1427        let task_id = non_transient_task(1);
1428
1429        // Step 1: modify the task outside snapshot mode (data_modified = true).
1430        {
1431            let mut guard = storage.access_mut(task_id);
1432            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1433        }
1434
1435        // Step 2: enter snapshot mode.
1436        let snapshot_guard = storage.start_snapshot();
1437
1438        // Step 3: `take_snapshot` captures the task.
1439        let shards = take_snapshot(
1440            &storage,
1441            snapshot_guard,
1442            &dummy_process,
1443            &noop_inspect,
1444            false,
1445        );
1446        {
1447            let guard = storage.access_mut(task_id);
1448            assert!(!guard.flags.data_modified());
1449            assert!(guard.flags.data_snapshot_pending());
1450        }
1451
1452        // Step 4: now that the capture is done but before we consume the iterator,
1453        // modify the task again: the captured state is frozen into `snapshots`.
1454        {
1455            let mut guard = storage.access_mut(task_id);
1456            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1457            assert!(guard.flags.data_modified());
1458            assert!(storage.snapshots.contains_key(&task_id));
1459        }
1460
1461        // Step 5: consume the iterator.
1462        let items: Vec<_> = shards
1463            .into_iter()
1464            .flat_map(|shard| shard.into_iter())
1465            .collect();
1466
1467        // The pre-encoded snapshot item should have been returned.
1468        assert_eq!(items.len(), 1);
1469        assert_eq!(items[0].task_id(), task_id);
1470
1471        {
1472            let guard = storage.access_mut(task_id);
1473            assert!(guard.flags.data_modified());
1474            assert!(!guard.flags.any_snapshot_pending());
1475        }
1476    }
1477
1478    /// A task modified in one category before a snapshot, then modified in a *different* category
1479    /// during snapshot iteration, must not panic and must carry the new modification forward.
1480    ///
1481    /// Sequence of events:
1482    /// 1. Task meta is modified (meta_modified = true).
1483    /// 2. `start_snapshot` puts us in snapshot mode.
1484    /// 3. `take_snapshot` captures the task (meta pending).
1485    /// 4. Task data is modified → the captured meta is frozen into `snapshots` and `data_modified`
1486    ///    is set as a normal modification.
1487    /// 5. `SnapshotShardIter::next` yields the pre-encoded item (meta only; data stays live) and
1488    ///    clears the pending flag.
1489    #[tokio::test(flavor = "multi_thread")]
1490    async fn modify_different_category_during_snapshot() {
1491        let storage = Storage::new(StorageOptions::for_tests());
1492        let task_id = non_transient_task(1);
1493
1494        // Step 1: modify meta only, outside snapshot mode.
1495        {
1496            let mut guard = storage.access_mut(task_id);
1497            let _ = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
1498            assert!(guard.flags.meta_modified());
1499            assert!(!guard.flags.data_modified());
1500        }
1501
1502        // Step 2: enter snapshot mode.
1503        let snapshot_guard = storage.start_snapshot();
1504
1505        // Step 3: take_snapshot captures the task.
1506        let shards = take_snapshot(
1507            &storage,
1508            snapshot_guard,
1509            &dummy_process,
1510            &noop_inspect,
1511            false,
1512        );
1513
1514        // Step 4: modify data during snapshot.
1515        {
1516            let mut guard = storage.access_mut(task_id);
1517            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1518            assert!(guard.flags.data_modified());
1519            assert!(!guard.flags.meta_modified());
1520        }
1521
1522        // Step 5: consume the iterator — must not panic.
1523        let items: Vec<_> = shards
1524            .into_iter()
1525            .flat_map(|shard| shard.into_iter())
1526            .collect();
1527
1528        assert_eq!(items.len(), 1);
1529        assert_eq!(items[0].task_id(), task_id);
1530
1531        {
1532            let guard = storage.access_mut(task_id);
1533            // meta was persisted by this snapshot.
1534            assert!(!guard.flags.meta_modified());
1535            // data is dirty for the next cycle.
1536            assert!(guard.flags.data_modified());
1537            assert!(!guard.flags.any_snapshot_pending());
1538        }
1539    }
1540
1541    /// With `drain_entries = true` (shutdown path), the modified entries are moved out of the map
1542    /// (during the scan) and serialized by the iterator, freeing each task's memory as it is
1543    /// persisted rather than retaining it until the whole snapshot is written. Either way the
1544    /// entry must be gone from the map by the time the snapshot is consumed.
1545    #[tokio::test(flavor = "multi_thread")]
1546    async fn drain_entries_removes_entry_from_map() {
1547        let storage = Storage::new(StorageOptions::for_tests());
1548        let task_id = non_transient_task(1);
1549
1550        // Modify the task outside snapshot mode so it lands in the modified list.
1551        {
1552            let mut guard = storage.access_mut(task_id);
1553            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1554        }
1555        assert!(storage.map.get(&task_id).is_some());
1556
1557        let snapshot_guard = storage.start_snapshot();
1558
1559        // Take the snapshot in drain mode.
1560        let shards = take_snapshot(
1561            &storage,
1562            snapshot_guard,
1563            &dummy_process,
1564            &noop_inspect,
1565            true,
1566        );
1567
1568        // Consume the iterator: the task is serialized and then removed from the map.
1569        let items: Vec<_> = shards
1570            .into_iter()
1571            .flat_map(|shard| shard.into_iter())
1572            .collect();
1573
1574        assert_eq!(items.len(), 1);
1575        assert_eq!(items[0].task_id(), task_id);
1576
1577        // The entry must be gone from the map now that it has been persisted.
1578        assert!(
1579            storage.map.get(&task_id).is_none(),
1580            "task entry should be removed from the map after being persisted in drain mode"
1581        );
1582    }
1583
1584    /// In drain mode, fully consuming the iterators should release each drained shard's table
1585    /// allocation entirely (reset-to-empty in `SnapshotShardIter::drop`), not just shrink it.
1586    #[tokio::test(flavor = "multi_thread")]
1587    async fn drain_entries_releases_drained_shards() {
1588        // dashmap requires at least 2 shards.
1589        let storage = Storage::new(StorageOptions::for_tests());
1590
1591        // Insert and modify enough tasks to grow the shards' tables beyond their minimum.
1592        let task_ids: Vec<_> = (1..=256).map(non_transient_task).collect();
1593        for &task_id in &task_ids {
1594            let mut guard = storage.access_mut(task_id);
1595            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1596        }
1597        let grown_capacity: usize = storage
1598            .map
1599            .shards()
1600            .iter()
1601            .map(|s| s.read().capacity())
1602            .sum();
1603        assert!(grown_capacity >= task_ids.len());
1604
1605        let snapshot_guard = storage.start_snapshot();
1606
1607        let shards = take_snapshot(
1608            &storage,
1609            snapshot_guard,
1610            &dummy_process,
1611            &noop_inspect,
1612            true,
1613        );
1614        let items: Vec<_> = shards
1615            .into_iter()
1616            .flat_map(|shard| shard.into_iter())
1617            .collect();
1618        assert_eq!(items.len(), task_ids.len());
1619
1620        // Every shard is now empty and its table allocation has been released (capacity 0),
1621        // since the reset swaps in the allocation-free default table.
1622        for shard in storage.map.shards() {
1623            let shard = shard.read();
1624            assert_eq!(shard.len(), 0);
1625            assert_eq!(
1626                shard.capacity(),
1627                0,
1628                "drained shard should have released its table allocation"
1629            );
1630        }
1631    }
1632
1633    /// In drain mode, `take_snapshot`'s scan removes *both* kinds of entry from the map: unmodified
1634    /// entries are erased and freed (never serialized), and the remaining modified-only table is
1635    /// moved out into the shard iterators (to be serialized, then freed as each is consumed). So
1636    /// the map is already empty when `take_snapshot` returns, and only the modified task is
1637    /// yielded.
1638    #[tokio::test(flavor = "multi_thread")]
1639    async fn drain_entries_removes_unmodified_during_take_snapshot() {
1640        let storage = Storage::new(StorageOptions::for_tests());
1641        let modified_id = non_transient_task(1);
1642        let unmodified_id = non_transient_task(2);
1643
1644        // One modified task (gets serialized) and one unmodified task (e.g. restored from disk but
1645        // never dirtied) that just occupies memory and must not be serialized.
1646        {
1647            let mut guard = storage.access_mut(modified_id);
1648            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1649        }
1650        // `access_mut` inserts an entry; leaving it without track_modification keeps it unmodified.
1651        let _ = storage.access_mut(unmodified_id);
1652        assert!(storage.map.get(&unmodified_id).is_some());
1653
1654        let snapshot_guard = storage.start_snapshot();
1655
1656        let shards = take_snapshot(
1657            &storage,
1658            snapshot_guard,
1659            &dummy_process,
1660            &noop_inspect,
1661            true,
1662        );
1663
1664        // The scan moved the modified table out and freed the unmodified entry, so both ids are
1665        // already absent from the map before any iterator is consumed.
1666        assert!(
1667            storage.map.get(&unmodified_id).is_none(),
1668            "unmodified entry should be removed during take_snapshot in drain mode"
1669        );
1670        assert!(
1671            storage.map.get(&modified_id).is_none(),
1672            "modified entry should be moved out of the map during take_snapshot in drain mode"
1673        );
1674
1675        // Consuming the iterators yields only the modified task (the unmodified one was never part
1676        // of the snapshot).
1677        let items: Vec<_> = shards
1678            .into_iter()
1679            .flat_map(|shard| shard.into_iter())
1680            .collect();
1681        assert_eq!(items.len(), 1);
1682        assert_eq!(items[0].task_id(), modified_id);
1683    }
1684
1685    #[tokio::test(flavor = "multi_thread")]
1686    async fn undo_non_snapshot_reverses_flag_and_counter() {
1687        let storage = Storage::new(StorageOptions::for_tests());
1688        let task_id = non_transient_task(1);
1689
1690        {
1691            let mut guard = storage.access_mut(task_id);
1692            let outcome = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1693            assert!(guard.flags.data_modified());
1694            guard.undo_track_modification(outcome);
1695            assert!(!guard.flags.data_modified());
1696            assert!(!guard.flags.any_modified());
1697        }
1698    }
1699
1700    /// A second track on an already-modified category returns `NoChange`; undoing it is a no-op and
1701    /// must NOT clear the real modification recorded by the first track.
1702    #[tokio::test(flavor = "multi_thread")]
1703    async fn undo_nochange_preserves_prior_modification() {
1704        let storage = Storage::new(StorageOptions::for_tests());
1705        let task_id = non_transient_task(1);
1706
1707        let mut guard = storage.access_mut(task_id);
1708        // First track is the real modification.
1709        let _first = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1710        // Second track on the same category changes nothing.
1711        let second = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1712        assert!(matches!(second, TrackOutcome::NoChange));
1713        // Undoing the no-op must leave the prior modification intact.
1714        guard.undo_track_modification(second);
1715        assert!(
1716            guard.flags.data_modified(),
1717            "undoing a NoChange outcome must not clear a real prior modification"
1718        );
1719    }
1720
1721    /// Undo only reverses the category it tracked: tracking Data then Meta, undoing only the Meta
1722    /// outcome must leave Data modified and the shard counter still non-zero.
1723    #[tokio::test(flavor = "multi_thread")]
1724    async fn undo_only_reverses_its_own_category() {
1725        let storage = Storage::new(StorageOptions::for_tests());
1726        let task_id = non_transient_task(1);
1727
1728        {
1729            let mut guard = storage.access_mut(task_id);
1730            let _data = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1731            let meta = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
1732            assert!(guard.flags.meta_modified());
1733            guard.undo_track_modification(meta);
1734            assert!(!guard.flags.meta_modified());
1735            assert!(guard.flags.data_modified());
1736        }
1737
1738        // Data is still modified, so the counter is still non-zero.
1739    }
1740
1741    /// A task wholly outside the snapshot (not captured) that is modified during the snapshot is
1742    /// tracked as a normal modification: `modified` is set and counted, no `snapshots` entry is
1743    /// created. Undo reverses both.
1744    #[tokio::test(flavor = "multi_thread")]
1745    async fn modify_outside_snapshot_during_snapshot_is_normal() {
1746        let storage = Storage::new(StorageOptions::for_tests());
1747        let anchor = non_transient_task(1);
1748        let task_id = non_transient_task(2);
1749        {
1750            let mut guard = storage.access_mut(anchor);
1751            let _ = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
1752        }
1753        // Insert the task (unmodified) so it exists in the map.
1754        let _ = storage.access_mut(task_id);
1755
1756        let snapshot_guard = storage.start_snapshot();
1757        let shards = take_snapshot(
1758            &storage,
1759            snapshot_guard,
1760            &dummy_process,
1761            &noop_inspect,
1762            false,
1763        );
1764        assert!(storage.snapshot_mode());
1765
1766        let mut guard = storage.access_mut(task_id);
1767        let outcome = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1768        assert!(matches!(
1769            outcome,
1770            TrackOutcome::Tracked {
1771                inserted_snapshot: false,
1772                ..
1773            }
1774        ));
1775        assert!(guard.flags.data_modified());
1776        assert!(!guard.flags.any_snapshot_pending());
1777        assert!(!storage.snapshots.contains_key(&task_id));
1778
1779        guard.undo_track_modification(outcome);
1780        assert!(!guard.flags.data_modified());
1781        drop(guard);
1782        let items: Vec<_> = shards.into_iter().flatten().collect();
1783        assert_eq!(items.len(), 1);
1784    }
1785
1786    /// A captured task tracked again before being persisted stores a pre-mutation encoded item in
1787    /// `snapshots`. Undo must remove that item and the new `modified` flag/count, while leaving
1788    /// the captured (pending) state intact.
1789    #[tokio::test(flavor = "multi_thread")]
1790    async fn undo_after_copy_on_write_removes_item_preserves_pending() {
1791        let storage = Storage::new(StorageOptions::for_tests());
1792        let task_id = non_transient_task(1);
1793
1794        // Modify before snapshot so the category is captured.
1795        {
1796            let mut guard = storage.access_mut(task_id);
1797            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1798        }
1799
1800        let snapshot_guard = storage.start_snapshot();
1801        let shards = take_snapshot(
1802            &storage,
1803            snapshot_guard,
1804            &dummy_process,
1805            &noop_inspect,
1806            false,
1807        );
1808
1809        {
1810            let mut guard = storage.access_mut(task_id);
1811            let outcome = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1812            assert!(matches!(
1813                outcome,
1814                TrackOutcome::Tracked {
1815                    inserted_snapshot: true,
1816                    ..
1817                }
1818            ));
1819            assert!(storage.snapshots.contains_key(&task_id));
1820
1821            guard.undo_track_modification(outcome);
1822            assert!(!guard.flags.data_modified());
1823            assert!(
1824                guard.flags.data_snapshot_pending(),
1825                "the captured modification belongs to the snapshot and must survive undo"
1826            );
1827            assert!(
1828                !storage.snapshots.contains_key(&task_id),
1829                "undo must remove the pre-mutation item it inserted"
1830            );
1831        }
1832
1833        // The captured state is still persisted (from the live task, since no entry remains).
1834        let items: Vec<_> = shards.into_iter().flatten().collect();
1835        assert_eq!(items.len(), 1);
1836        assert!(!storage.access_mut(task_id).flags.any_snapshot_pending());
1837    }
1838
1839    /// The capture runs inside the operation exclusion: it moves the modified flags to
1840    /// `*_snapshot_pending`, keeps `new_task` until persistence, and resets the shard counters.
1841    #[tokio::test(flavor = "multi_thread")]
1842    async fn take_snapshot_captures_mask_and_clears_live_bits() {
1843        let storage = Storage::new(StorageOptions::for_tests());
1844        let task_id = non_transient_task(1);
1845        {
1846            let mut guard = storage.access_mut(task_id);
1847            guard.flags.set_new_task(true);
1848            let _ = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
1849        }
1850
1851        let snapshot_guard = storage.start_snapshot();
1852        let process = |id: TaskId,
1853                       inner: &TaskStorage,
1854                       category: TaskDataCategory,
1855                       buffer: &mut TurboBincodeBuffer| {
1856            assert_eq!(category, TaskDataCategory::Meta);
1857            dummy_process(id, inner, category, buffer)
1858        };
1859        let shards = take_snapshot(&storage, snapshot_guard, &process, &noop_inspect, false);
1860        {
1861            let guard = storage.access_mut(task_id);
1862            assert!(!guard.flags.any_modified());
1863            assert!(guard.flags.meta_snapshot_pending());
1864            assert!(!guard.flags.data_snapshot_pending());
1865            assert!(guard.flags.new_task());
1866        }
1867
1868        let items: Vec<_> = shards.into_iter().flatten().collect();
1869        assert_eq!(items.len(), 1);
1870        let guard = storage.access_mut(task_id);
1871        assert!(!guard.flags.any_snapshot_pending());
1872        assert!(!guard.flags.new_task());
1873        assert!(!guard.flags.any_modified());
1874    }
1875
1876    /// When persisting fails, the shards are dropped before every captured task is yielded.
1877    /// Persisting is then disabled for the session, so the leftovers are not restored: dropping a
1878    /// shard clears the pending flags of its unyielded tasks (before snapshot mode ends), and
1879    /// ending the snapshot drops their copy-on-write items.
1880    #[tokio::test(flavor = "multi_thread")]
1881    async fn dropping_shards_early_leaves_no_copy_on_write_items() {
1882        let storage = Storage::new(StorageOptions::for_tests());
1883        let task_ids: Vec<_> = (1..=8).map(non_transient_task).collect();
1884        for &task_id in &task_ids {
1885            let mut guard = storage.access_mut(task_id);
1886            // Both categories, so the check below covers both pending flags.
1887            let _ = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
1888            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1889        }
1890        let frozen = task_ids[0];
1891
1892        let snapshot_guard = storage.start_snapshot();
1893        let shards = take_snapshot(
1894            &storage,
1895            snapshot_guard,
1896            &dummy_process,
1897            &noop_inspect,
1898            false,
1899        );
1900        {
1901            let mut guard = storage.access_mut(frozen);
1902            let _ = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
1903        }
1904        assert!(storage.snapshots.contains_key(&frozen));
1905
1906        // Consume one item from the first shard, then drop everything.
1907        let mut shards = shards.into_iter();
1908        let mut first = shards.next().unwrap().into_iter();
1909        let yielded = first
1910            .next()
1911            .expect("the first shard is not empty")
1912            .task_id();
1913        drop(first);
1914        drop(shards);
1915
1916        assert!(!storage.snapshot_mode());
1917        assert!(storage.snapshots.is_empty());
1918        for &task_id in &task_ids {
1919            assert!(
1920                !storage.access_mut(task_id).flags.any_snapshot_pending(),
1921                "dropping the shards clears the pending flags of unyielded task {task_id:?}"
1922            );
1923        }
1924
1925        let leftover = *task_ids
1926            .iter()
1927            .find(|&&id| id != frozen && id != yielded)
1928            .expect("some captured tasks were not yielded");
1929        let mut guard = storage.access_mut(leftover);
1930        let outcome = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
1931        assert!(matches!(
1932            outcome,
1933            TrackOutcome::Tracked {
1934                inserted_snapshot: false,
1935                ..
1936            }
1937        ));
1938        assert!(guard.flags.meta_modified());
1939        drop(guard);
1940        assert!(storage.snapshots.is_empty());
1941    }
1942
1943    /// A panic while encoding a captured task (e.g. a value type without a bincode impl) unwinds
1944    /// out of the shard iterator. The task being encoded must still be cleaned up when the shards
1945    /// drop, like the tasks that weren't reached yet.
1946    #[cfg_attr(target_family = "wasm", ignore = "no unwinding on wasm")]
1947    #[tokio::test(flavor = "multi_thread")]
1948    async fn panic_while_encoding_clears_pending_flags() {
1949        let storage = Storage::new(StorageOptions::for_tests());
1950        let task_ids: Vec<_> = (1..=8).map(non_transient_task).collect();
1951        for &task_id in &task_ids {
1952            let mut guard = storage.access_mut(task_id);
1953            let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1954        }
1955        let poisoned = task_ids[2];
1956        let process = |task_id: TaskId,
1957                       inner: &TaskStorage,
1958                       category: TaskDataCategory,
1959                       buffer: &mut TurboBincodeBuffer| {
1960            assert_ne!(task_id, poisoned, "simulated encoding failure");
1961            dummy_process(task_id, inner, category, buffer)
1962        };
1963
1964        let snapshot_guard = storage.start_snapshot();
1965        let shards = take_snapshot(&storage, snapshot_guard, &process, &noop_inspect, false);
1966        let mut panicked = false;
1967        for shard in shards {
1968            let mut iter = shard.into_iter();
1969            loop {
1970                match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| iter.next())) {
1971                    Ok(Some(_)) => {}
1972                    Ok(None) => break,
1973                    Err(_) => {
1974                        panicked = true;
1975                        break;
1976                    }
1977                }
1978            }
1979            // Dropping the shard after the panic is what `snapshot_and_persist` does when it
1980            // unwinds.
1981            drop(iter);
1982        }
1983        assert!(panicked);
1984
1985        assert!(!storage.snapshot_mode());
1986        assert!(storage.snapshots.is_empty());
1987        for &task_id in &task_ids {
1988            assert!(
1989                !storage.access_mut(task_id).flags.any_snapshot_pending(),
1990                "task {task_id:?} kept its pending flags after the panic"
1991            );
1992        }
1993    }
1994
1995    /// Mixed-category race: meta is part of the snapshot, data is not. The first during-snapshot
1996    /// change hits data, then meta is changed too. The persisted meta must be the pre-snapshot
1997    /// meta, data must stay live (not persisted in this cycle), and both categories must be dirty
1998    /// for the next cycle.
1999    #[tokio::test(flavor = "multi_thread")]
2000    async fn modify_other_category_then_snapshot_category_during_snapshot() {
2001        fn output(id: u32) -> OutputValue {
2002            OutputValue::Output(non_transient_task(id))
2003        }
2004
2005        let storage = Storage::new(StorageOptions::for_tests());
2006        let task_id = non_transient_task(1);
2007
2008        // Meta is modified before the snapshot; data is clean.
2009        {
2010            let mut guard = storage.access_mut(task_id);
2011            guard.set_output(output(2));
2012            let _ = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
2013        }
2014        let expected_meta = {
2015            let mut pre = TaskStorage::new();
2016            pre.set_output(output(2));
2017            encode_task_contents(
2018                task_id,
2019                &pre,
2020                SpecificTaskDataCategory::Meta,
2021                &mut TurboBincodeBuffer::new(),
2022            )
2023            .unwrap()
2024        };
2025
2026        let snapshot_guard = storage.start_snapshot();
2027        let process = |id: TaskId,
2028                       inner: &TaskStorage,
2029                       category: TaskDataCategory,
2030                       buffer: &mut TurboBincodeBuffer| {
2031            assert_ne!(
2032                id, task_id,
2033                "a task with a pre-encoded snapshot item must not be encoded again"
2034            );
2035            dummy_process(id, inner, category, buffer)
2036        };
2037        let shards = take_snapshot(&storage, snapshot_guard, &process, &noop_inspect, false);
2038
2039        // During the snapshot: data first (not part of the snapshot), then meta.
2040        {
2041            let mut guard = storage.access_mut(task_id);
2042            let outcome = guard.track_modification(SpecificTaskDataCategory::Data, "test");
2043            assert!(matches!(
2044                outcome,
2045                TrackOutcome::Tracked {
2046                    inserted_snapshot: true,
2047                    ..
2048                }
2049            ));
2050            let outcome = guard.track_modification(SpecificTaskDataCategory::Meta, "test");
2051            assert!(matches!(
2052                outcome,
2053                TrackOutcome::Tracked {
2054                    inserted_snapshot: false,
2055                    ..
2056                }
2057            ));
2058            guard.set_output(output(3));
2059        }
2060
2061        let items: Vec<_> = shards
2062            .into_iter()
2063            .flat_map(|shard| shard.into_iter())
2064            .collect();
2065        assert_eq!(items.len(), 1);
2066        let SnapshotItem::Put { meta, data, .. } = &items[0] else {
2067            panic!("expected a Put item");
2068        };
2069        assert_eq!(meta.as_deref(), Some(&expected_meta[..]));
2070        assert!(data.is_none(), "data was not part of this snapshot");
2071
2072        let guard = storage.access_mut(task_id);
2073        assert!(guard.flags.meta_modified(), "meta change carried forward");
2074        assert!(guard.flags.data_modified(), "data change carried forward");
2075        assert!(!guard.flags.any_snapshot_pending());
2076        drop(guard);
2077        assert!(storage.snapshots.get(&task_id).is_none());
2078    }
2079}