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 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#[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 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 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 pub fn key_space(self) -> KeySpace {
140 match self {
141 SpecificTaskDataCategory::Meta => KeySpace::TaskMeta,
142 SpecificTaskDataCategory::Data => KeySpace::TaskData,
143 }
144 }
145}
146
147#[must_use = "a no-op mutation must undo its TrackOutcome; dropping it leaks an over-track"]
153pub enum TrackOutcome {
154 NoChange,
156 Tracked {
160 category: SpecificTaskDataCategory,
161 inserted_snapshot: bool,
162 },
163}
164
165impl TaskDataCategory {
166 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 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
192pub(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
229pub(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#[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 snapshots: FxDashMap<TaskId, Box<SnapshotItem>>,
330 map: FxDashMap<TaskId, Box<TaskStorage>>,
342 pub(crate) restored: Event,
347 pub task_cache: FxDashMap<CachedTaskTypeArc, TaskId>,
352}
353
354#[derive(Debug, Clone, Copy)]
356pub struct StorageOptions {
357 pub shard_amount: usize,
359 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 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 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 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 let _ =
430 task.track_modification(SpecificTaskDataCategory::Data, "persistent_task_type");
431 }
432 }
433 }
434
435 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 parallel::map_collect::<_, _, Vec<_>>(&shards, |&shard| {
484 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 modified_task && !is_deleted_new_task(task)
504 });
505 if shard_guard.is_empty() {
506 return None;
509 }
510 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 task.flags.set_meta_modified(false);
520 task.flags.set_data_modified(false);
521 continue;
522 }
523 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 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 pub fn start_snapshot(&self) -> SnapshotGuard<'_> {
566 self.snapshot_mode.store(true, Ordering::Release);
569 SnapshotGuard::new(self)
570 }
571
572 fn end_snapshot(&self) {
579 self.snapshot_mode.store(false, Ordering::Release);
580 self.snapshots.clear();
581 if self.snapshots.capacity() > 1024 {
583 self.snapshots.shrink_to_fit();
584 }
585 }
586
587 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 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 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 #[doc(hidden)]
627 pub fn resident_task_count_for_testing(&self) -> usize {
628 self.map.len()
629 }
630
631 pub fn shard_count(&self) -> usize {
635 self.map.shards().len()
636 }
637
638 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 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 #[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 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 pub(crate) fn drop_task_cache(&self) {
721 drop_contents(&self.task_cache);
722 }
723
724 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 let mut deferred_task_cache_removals: Vec<CachedTaskTypeArc> = Vec::new();
757 shard.retain(|(task_id, task)| {
758 if task_id.is_transient() && !task.flags.deleted() {
761 evicted.unevictable_reasons[UnevictableReason::Transient.index()] += 1;
762 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 evicted.unevictable_reasons
775 [UnevictableReason::MarkedForDeletion.index()] += 1;
776 return true;
777 }
778 evicted.full += 1;
783 return false;
784 }
785 let (key_evictability, value_evictability) = task.evictability();
786 match key_evictability {
787 KeyEvictability::Evictable => {
788 let task_type = task.get_persistent_task_type().unwrap();
792 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 }
804 TryLockAndRemove::WouldBlock => {
805 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 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 if reason != UnevictableReason::InProgress {
838 task.shrink_edge_sets();
839 }
840 }
841 }
842 true
843 });
844 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 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 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
885pub struct TaskEntryGuard<'a> {
891 storage: &'a Storage,
892 entry: dashmap::mapref::entry::OccupiedEntry<'a, TaskId, Box<TaskStorage>>,
893}
894
895impl<'a> TaskEntryGuard<'a> {
896 pub fn discard(self) {
898 self.entry.remove();
899 }
900
901 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 #[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 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 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 #[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 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
1044const SCRATCH_BUFFER_INITIAL_SIZE: usize = 4096;
1047
1048#[derive(Default)]
1057enum ScratchBufferSlot {
1058 #[default]
1060 Uninit,
1061 Taken,
1063 Available(TurboBincodeBuffer),
1065}
1066
1067pub struct SnapshotGuard<'l> {
1068 storage: &'l Storage,
1069 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
1122enum ShardWork {
1125 Keep(Vec<TaskId>),
1129 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 _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
1162pub 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 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 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 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 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
1230fn is_deleted_new_task(task: &TaskStorage) -> bool {
1233 task.flags.deleted() && task.flags.new_task()
1234}
1235
1236fn 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 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 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 #[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 #[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 #[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 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 fn noop_inspect(_: &SnapshotItem) {}
1387
1388 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 #[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 {
1431 let mut guard = storage.access_mut(task_id);
1432 let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1433 }
1434
1435 let snapshot_guard = storage.start_snapshot();
1437
1438 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 {
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 let items: Vec<_> = shards
1463 .into_iter()
1464 .flat_map(|shard| shard.into_iter())
1465 .collect();
1466
1467 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 #[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 {
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 let snapshot_guard = storage.start_snapshot();
1504
1505 let shards = take_snapshot(
1507 &storage,
1508 snapshot_guard,
1509 &dummy_process,
1510 &noop_inspect,
1511 false,
1512 );
1513
1514 {
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 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 assert!(!guard.flags.meta_modified());
1535 assert!(guard.flags.data_modified());
1537 assert!(!guard.flags.any_snapshot_pending());
1538 }
1539 }
1540
1541 #[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 {
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 let shards = take_snapshot(
1561 &storage,
1562 snapshot_guard,
1563 &dummy_process,
1564 &noop_inspect,
1565 true,
1566 );
1567
1568 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 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 #[tokio::test(flavor = "multi_thread")]
1587 async fn drain_entries_releases_drained_shards() {
1588 let storage = Storage::new(StorageOptions::for_tests());
1590
1591 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 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 #[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 {
1647 let mut guard = storage.access_mut(modified_id);
1648 let _ = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1649 }
1650 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 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 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 #[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 let _first = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1710 let second = guard.track_modification(SpecificTaskDataCategory::Data, "test");
1712 assert!(matches!(second, TrackOutcome::NoChange));
1713 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 #[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 }
1740
1741 #[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 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 #[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 {
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 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 #[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 #[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 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 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 #[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 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 #[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 {
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 {
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}