vercel/next.js · #101748

turbo-tasks-backend: delay collectible propagation until tasks are clean

sokra · merged Nov 17, 202620 files · 876 + / 35 −
crates/next-napi-bindings/src/next_api/endpoint.rs4 + / 2 −
@@ -300,8 +300,10 @@ async fn endpoint_client_changed_with_issues_operation(     endpoint_op: OperationVc<OptionEndpoint>, ) -> Result<Vc<Completion>> {     let changed_op = endpoint_client_changed_operation(endpoint_op);-    let Err(err) = changed_op.connect().await else {-        return Ok(changed_op.connect());+    // Collectibles are only stable after a strongly consistent read of their source.+    let err = match changed_op.resolve().strongly_consistent().await {+        Ok(changed) => return Ok(*changed),+        Err(err) => err,     };     let filter = issue_filter_from_endpoint(endpoint_op).await;     let issues = get_issues(changed_op, &filter).await?;
turbopack/crates/turbo-tasks-backend/benches/collectibles.rs2 + / 1 −
@@ -100,7 +100,8 @@ async fn emitting_operation(count: u32) -> Result<Vc<()>> { async fn collecting_operation(count: u32, take: bool, iteration: u32) -> Result<Vc<u32>> {     let _ = iteration;     let source = emitting_operation(count);-    source.connect().await?;+    // Collectibles are only stable after a strongly consistent read of their source.+    source.read_strongly_consistent().await?;     let collectibles = if take {         source.take_collectibles::<Box<dyn ValueToString>>()     } else {
turbopack/crates/turbo-tasks-backend/src/backend/mod.rs44 + / 1 −
@@ -532,6 +532,31 @@ impl TurboTasksBackend {         Some(get_aggregation_number(&task))     } +    /// The number of collectibles with changes that `task` hasn't sent to its uppers yet, because+    /// the task is dirty (see delayed collectible propagation in `aggregation_update.rs`).+    #[doc(hidden)]+    pub fn pending_collectibles_count_for_testing(+        &self,+        task: TaskId,+        turbo_tasks: &TurboTasks<TurboTasksBackend>,+    ) -> Option<usize> {+        let mut ctx = self.execute_context(turbo_tasks);+        let task = ctx.try_task(task, TaskDataCategory::Meta)?;+        Some(task.pending_collectibles_len())+    }++    /// Whether `task` is dirty (in any session).+    #[doc(hidden)]+    pub fn is_dirty_for_testing(+        &self,+        task: TaskId,+        turbo_tasks: &TurboTasks<TurboTasksBackend>,+    ) -> Option<bool> {+        let mut ctx = self.execute_context(turbo_tasks);+        let task = ctx.try_task(task, TaskDataCategory::Meta)?;+        Some(task.is_dirty().is_some())+    }+     /// The GC roots set as currently persisted on disk (task id -> [`TtlCounter`]).     #[doc(hidden)]     pub fn persisted_gc_roots_for_testing(&self) -> Vec<(TaskId, TtlCounter)> {@@ -3918,14 +3943,26 @@ impl TurboTasksBackend {                     if value > 0 {                         if let Some((flag, _)) = collectibles.get_mut(&collectible) {                             *flag = true-                        } else {+                        } else if task.get_pending_collectibles(&collectible).is_none() {+                            // A pending collectible hasn't been sent to the uppers yet. That's only+                            // allowed while the task is dirty, which+                            // `check_pending_collectibles_invariant` checks.                             panic!(                                 "Task {} has a collectible {:?} that is not in any upper task",                                 task_id, collectible                             );                         }                     }                 }+                // A negative pending change is a collectible the uppers still see, but that is no+                // longer emitted (or aggregated) by this task.+                for (&collectible, &count) in task.iter_pending_collectibles() {+                    if count < 0+                        && let Some((flag, _)) = collectibles.get_mut(&collectible)+                    {+                        *flag = true+                    }+                }                  let is_dirty = task.has_dirty();                 let has_dirty_container = task.has_dirty_containers();@@ -3949,6 +3986,12 @@ impl TurboTasksBackend {                 }                 drop(task); +                if let Err(message) =+                    operation::check_pending_collectibles_invariant(&mut ctx, task_id)+                {+                    panic!("{message}");+                }+                 if should_be_in_upper {                     for upper_id in uppers {                         let upper = ctx.task(upper_id, TaskDataCategory::All);
turbopack/crates/turbo-tasks-backend/src/backend/operation/aggregation_update.rs479 + / 1 −
@@ -148,6 +148,103 @@ pub fn is_root_node(aggregation_number: u32) -> bool {     aggregation_number == u32::MAX } +/// Whether the task counts as dirty for strongly consistent reads, i.e. as a dirty container that+/// is not clean in the current session in all of its uppers.+fn is_effectively_dirty(task: &TaskGuard<'_>) -> bool {+    task.is_dirty().is_some() || task.has_dirty_containers()+}++/// Delayed collectible propagation: decides which collectible changes of `update`, an update of+/// the contribution of `task` to its uppers, are sent now. Must be called under the lock of `task`,+/// after its dirty state has been updated, for every outgoing update of the task that changes+/// collectibles or can make the task clean.+///+/// - While the task is dirty (itself or through its children), the collectible changes are moved+///   into the task's `pending_collectibles`, where positive and negative changes of the same+///   collectible cancel out. Only the dirty state part of `update` is sent. This also applies when+///   the task has no uppers yet: a task that is executing can temporarily have many collectibles+///   that it removes again before it's clean, and these shouldn't be propagated.+/// - Once the task is clean, the pending changes are netted with the changes of `update` and added+///   to it, so `update` stays normalized (one entry per collectible). The update that makes the+///   task clean always passes here, so they are sent together with it. Without uppers, the update+///   isn't sent, which drops the pending changes: nobody has seen the contribution.+///+/// A dirty subgraph often changes the same collectibles back and forth before it is clean again,+/// e.g. a task that takes the collectibles of a recomputed child cancels the child's changes when+/// it re-executes. Delaying the changes avoids propagating them through all uppers twice.+///+/// This keeps the invariant that a task with pending collectibles is a dirty container (not clean+/// in the current session) in all its uppers, so these uppers aren't clean either. A strongly+/// consistent read waits until the task it reads is clean, so it never misses pending changes.+/// Collectibles are only stable after a strongly consistent read of their source: a read that+/// isn't strongly consistent may miss changes that are still pending in the dirty subgraph.+///+/// [`AggregatedDataUpdate::from_task`] subtracts the pending changes, so that new and removed+/// uppers see the same contribution as the existing uppers.+pub fn stage_outgoing_collectibles(task: &mut TaskGuard<'_>, update: &mut AggregatedDataUpdate) {+    let has_pending = !task.is_pending_collectibles_empty();+    if update.collectibles_update.is_empty() && !has_pending {+        return;+    }+    let is_dirty = is_effectively_dirty(task);+    if !is_dirty && !has_pending {+        // Clean and nothing pending: send the changes as they are.+        return;+    }+    for (collectible, count) in take(&mut update.collectibles_update) {+        let _ = task.update_pending_collectibles_count(collectible, count);+    }+    if !is_dirty && let Some(pending) = task.take_pending_collectibles() {+        update.collectibles_update.extend(pending);+    }+}++/// Checks the invariant of delayed collectible propagation for `task_id` (see+/// [`stage_outgoing_collectibles`]): a task with pending collectibles is effectively dirty and is+/// listed as an effectively dirty container (dirty, not clean in the current session) in every+/// upper. Used by `verify_aggregation_graph`, which runs while the graph is idle.+#[cfg(any(test, feature = "verify_aggregation_graph"))]+pub fn check_pending_collectibles_invariant(+    ctx: &mut ExecuteContext<'_>,+    task_id: TaskId,+) -> Result<(), String> {+    let (pending, is_dirty, upper_ids) = {+        let task = ctx.task(task_id, TaskDataCategory::Meta);+        if task.is_pending_collectibles_empty() {+            return Ok(());+        }+        (+            task.pending_collectibles_len(),+            is_effectively_dirty(&task),+            get_uppers(&task),+        )+    };+    if !is_dirty {+        return Err(format!(+            "Task {task_id} has {pending} pending collectibles, but is not dirty"+        ));+    }+    for upper_id in upper_ids {+        let upper = ctx.task(upper_id, TaskDataCategory::Meta);+        let dirty = upper+            .get_aggregated_dirty_containers(&task_id)+            .copied()+            .unwrap_or_default();+        let clean = upper+            .get_aggregated_current_session_clean_containers(&task_id)+            .copied()+            .unwrap_or_default();+        if dirty <= 0 || dirty <= clean {+            return Err(format!(+                "Task {task_id} has {pending} pending collectibles, but is not a dirty container \+                 of its upper {upper_id} (dirty count {dirty}, current session clean count \+                 {clean})"+            ));+        }+    }+    Ok(())+}+ /// Returns a list of tasks that are considered as "following" the task. fn get_followers_with_aggregation_number(     task: &TaskGuard<'_>,@@ -451,10 +548,16 @@ impl AggregationUpdateJob {         )     } +    /// Creates a job that sends `update` to the uppers of `task`. Callers that send collectible+    /// changes or can make the task clean must pass `update` through+    /// [`stage_outgoing_collectibles`] first.     pub fn data_update(         task: &mut TaskGuard<'_>,         update: AggregatedDataUpdate,     ) -> Option<AggregationUpdateJob> {+        if update.is_empty() {+            return None;+        }         let upper_ids: SmallVec<_> = get_uppers(task);         if !upper_ids.is_empty() {             Some(@@ -516,7 +619,9 @@ impl AggregatedDataUpdate {         let aggregation = get_aggregation_number(task);         let mut dirty_count = 0;         let mut current_session_clean_count = 0;-        let collectibles_update = if is_aggregating_node(aggregation) {+        // Whether `collectibles_update` can contain more than one entry per collectible.+        let mut need_optimize = false;+        let mut collectibles_update = if is_aggregating_node(aggregation) {             dirty_count = task                 .get_aggregated_dirty_container_count()                 .copied()@@ -536,10 +641,19 @@ impl AggregatedDataUpdate {                     collectibles_update.push((*collectible, 1));                 }             }+            // A collectible can be listed twice: own and aggregated.+            need_optimize =+                !task.is_collectibles_empty() && !task.is_aggregated_collectibles_empty();             collectibles_update         } else {             task.iter_collectibles().map(|(&k, &v)| (k, v)).collect()         };+        // The uppers haven't seen the pending changes yet (see `stage_outgoing_collectibles`), so+        // subtract them.+        if !task.is_pending_collectibles_empty() {+            collectibles_update.extend(task.iter_pending_collectibles().map(|(&k, &v)| (k, -v)));+            need_optimize = true;+        }         let (dirty, current_session_clean) = task.dirty_state();         if dirty {             dirty_count += 1;@@ -549,6 +663,12 @@ impl AggregatedDataUpdate {         }          let mut result = Self::new().collectibles_update(collectibles_update);+        // Duplicate entries must net out before the update is applied: otherwise a collectible+        // could disappear and appear again in the upper, which invalidates its readers. Not all+        // callers optimize the update (`balance_edge` applies it while holding both locks).+        if need_optimize {+            result = result.optimize();+        }         if dirty_count > 0 {             result = result.dirty_container_update(                 task.id(),@@ -862,6 +982,7 @@ impl AggregatedDataUpdate {                 result.collectibles_update.push((*collectible, -1));             }         }+        stage_outgoing_collectibles(task, &mut result);         result     } @@ -5536,6 +5657,363 @@ mod follower_debt_tests {     } } +/// Deterministic tests of delayed collectible propagation (see `stage_outgoing_collectibles`).+#[cfg(test)]+mod delayed_collectibles_tests {+    use smallvec::smallvec;+    use turbo_tasks::{TaskPriority, TurboTasks};++    use super::{+        AggregatedDataUpdate, AggregationUpdateQueue, check_pending_collectibles_invariant,+        follower_debt_tests::{+            FOLLOWER, INNER, UPPER, add, aggregated, balance, collectible, id, remove, run,+            setup_with_data, uppers,+        },+        stage_outgoing_collectibles,+    };+    use crate::{+        backend::{+            TaskDataCategory, TurboTasksBackend,+            operation::{ExecuteContext, UpdateCollectibleOperation},+            storage_schema::TaskStorageAccessors,+        },+        data::{AggregationNumber, CellRef, CollectibleRef, Dirtyness},+    };++    fn set_dirty(tt: &TurboTasks<TurboTasksBackend>, task: u32, dirty: bool) {+        let mut ctx = ExecuteContext::new(tt);+        let job = {+            let mut task = ctx.task(id(task), TaskDataCategory::All);+            task.update_dirty_state(dirty.then_some(Dirtyness::Dirty {+                parent_priority: TaskPriority::leaf(),+                #[cfg(feature = "task_dirty_cause")]+                cause: turbo_tasks::TaskDirtyCause::InitialDirty,+            }))+        };+        if let Some(job) = job {+            let mut queue = AggregationUpdateQueue::new_without_optimizations();+            queue.push(job);+            queue.execute(&mut ctx);+        }+    }++    fn emit(tt: &TurboTasks<TurboTasksBackend>, task: u32, count: i32) {+        UpdateCollectibleOperation::run(id(task), collectible(), count, ExecuteContext::new(tt));+    }++    fn pending(tt: &TurboTasks<TurboTasksBackend>, task: u32) -> i32 {+        let mut ctx = ExecuteContext::new(tt);+        let task = ctx.task(id(task), TaskDataCategory::Meta);+        task.get_pending_collectibles(&collectible())+            .copied()+            .unwrap_or_default()+    }++    fn has_dirty_containers(tt: &TurboTasks<TurboTasksBackend>, task: u32) -> bool {+        let mut ctx = ExecuteContext::new(tt);+        let task = ctx.task(id(task), TaskDataCategory::Meta);+        task.has_dirty_containers()+    }++    #[tokio::test(flavor = "multi_thread")]+    async fn changes_net_while_dirty_and_flush_with_clean() {+        let tt = setup_with_data(&[(1, UPPER), (2, INNER)], false);+        run(&tt, [add(1, 2)]);+        set_dirty(&tt, 2, true);+        assert!(has_dirty_containers(&tt, 1));++        emit(&tt, 2, 1);+        assert_eq!((aggregated(&tt, 1), pending(&tt, 2)), (0, 1));+        emit(&tt, 2, -1);+        assert_eq!((aggregated(&tt, 1), pending(&tt, 2)), (0, 0));+        emit(&tt, 2, 1);+        assert_eq!((aggregated(&tt, 1), pending(&tt, 2)), (0, 1));++        set_dirty(&tt, 2, false);+        assert!(!has_dirty_containers(&tt, 1));+        assert_eq!((aggregated(&tt, 1), pending(&tt, 2)), (1, 0));+    }++    #[tokio::test(flavor = "multi_thread")]+    async fn edges_use_the_published_contribution() {+        let tt = setup_with_data(&[(1, UPPER), (2, INNER), (3, UPPER)], false);+        run(&tt, [add(1, 2)]);+        set_dirty(&tt, 2, true);+        emit(&tt, 2, 1);++        run(&tt, [add(3, 2)]);+        assert_eq!((aggregated(&tt, 1), aggregated(&tt, 3)), (0, 0));++        set_dirty(&tt, 2, false);+        assert_eq!((aggregated(&tt, 1), aggregated(&tt, 3)), (1, 1));++        run(&tt, [remove(3, 2)]);+        assert_eq!((aggregated(&tt, 1), aggregated(&tt, 3)), (1, 0));+    }++    #[tokio::test(flavor = "multi_thread")]+    async fn dirty_children_delay_changes_until_clean() {+        // 3 is dirty, which makes 2 a task with a dirty container, while 2 itself is clean.+        let tt = setup_with_data(&[(1, UPPER + 1), (2, UPPER), (3, INNER)], false);+        run(&tt, [add(1, 2), add(2, 3)]);+        set_dirty(&tt, 3, true);+        assert!(has_dirty_containers(&tt, 2));++        emit(&tt, 2, 1);+        assert_eq!((aggregated(&tt, 1), pending(&tt, 2)), (0, 1));++        // The child becoming clean makes 2 clean, which sends the pending changes.+        set_dirty(&tt, 3, false);+        assert!(!has_dirty_containers(&tt, 1));+        assert_eq!((aggregated(&tt, 1), pending(&tt, 2)), (1, 0));+    }++    /// A task that read the collectibles of an upper, so it is invalidated when they change.+    const READER: u32 = 999;++    /// Registers `READER` as a dependent of the collectibles of `upper`.+    fn add_reader(tt: &TurboTasks<TurboTasksBackend>, upper: u32) {+        let mut ctx = ExecuteContext::new(tt);+        let mut task = ctx.task(id(upper), TaskDataCategory::All);+        let _ = task.add_collectibles_dependents((collectible().collectible_type, id(READER)));+    }++    /// Whether `READER` was invalidated.+    fn reader_is_dirty(tt: &TurboTasks<TurboTasksBackend>) -> bool {+        let mut ctx = ExecuteContext::new(tt);+        let task = ctx.task(id(READER), TaskDataCategory::All);+        task.get_dirty().is_some()+    }++    fn set_aggregation_number(tt: &TurboTasks<TurboTasksBackend>, task: u32, number: u32) {+        let mut ctx = ExecuteContext::new(tt);+        let mut task = ctx.task(id(task), TaskDataCategory::All);+        task.set_aggregation_number(AggregationNumber {+            base: number,+            distance: 0,+            effective: number,+        });+    }++    /// A task that becomes an inner task of a new upper while it has pending changes contributes+    /// only its published collectibles. Its own collectibles and the subtracted pending changes+    /// must net out before they are applied, so the new upper never sees the unpublished+    /// collectible appear and disappear again, which would invalidate its readers.+    #[tokio::test(flavor = "multi_thread")]+    async fn new_inner_edge_nets_out_pending_changes() {+        // 2 is a follower of 1, and an inner task of 3, so changes of 2 are staged for 3.+        let tt = setup_with_data(+            &[(1, UPPER), (2, FOLLOWER), (3, FOLLOWER + 1), (READER, 0)],+            false,+        );+        run(&tt, [add(1, 2), add(3, 2)]);+        set_dirty(&tt, 2, true);+        emit(&tt, 2, 1);+        assert_eq!(pending(&tt, 2), 1);+        add_reader(&tt, 1);++        // Lowering the aggregation number of 2 turns the follower edge into an inner edge.+        set_aggregation_number(&tt, 2, INNER);+        run(&tt, [balance(1, 2)]);+        assert_eq!(uppers(&tt, 2), vec![(id(1), 1), (id(3), 1)]);+        assert_eq!((aggregated(&tt, 1), aggregated(&tt, 3)), (0, 0));+        assert!(+            !reader_is_dirty(&tt),+            "the unpublished collectible must not invalidate the reader"+        );++        set_dirty(&tt, 2, false);+        assert_eq!((aggregated(&tt, 1), aggregated(&tt, 3)), (1, 1));+        assert!(reader_is_dirty(&tt), "publishing invalidates the reader");+    }++    /// A dirty task without uppers delays its changes too: an executing task can temporarily have+    /// collectibles that it removes again before it's clean.+    #[tokio::test(flavor = "multi_thread")]+    async fn changes_without_uppers_are_delayed_until_clean() {+        let tt = setup_with_data(&[(1, UPPER), (2, INNER)], false);+        set_dirty(&tt, 2, true);+        emit(&tt, 2, 1);+        assert_eq!(pending(&tt, 2), 1);++        // A new upper sees only the published contribution.+        run(&tt, [add(1, 2)]);+        assert_eq!((aggregated(&tt, 1), pending(&tt, 2)), (0, 1));++        set_dirty(&tt, 2, false);+        assert_eq!((aggregated(&tt, 1), pending(&tt, 2)), (1, 0));+    }++    /// Without uppers, becoming clean drops the pending changes: nobody has seen them.+    #[tokio::test(flavor = "multi_thread")]+    async fn clean_without_uppers_drops_pending_changes() {+        let tt = setup_with_data(&[(1, UPPER), (2, INNER)], false);+        set_dirty(&tt, 2, true);+        emit(&tt, 2, 1);+        assert_eq!(pending(&tt, 2), 1);+        set_dirty(&tt, 2, false);+        assert_eq!(pending(&tt, 2), 0);++        // The collectible is still part of the contribution of 2.+        run(&tt, [add(1, 2)]);+        assert_eq!(aggregated(&tt, 1), 1);+    }++    /// `from_task` subtracts each pending count once, even when an aggregating task lists a+    /// collectible twice (own and aggregated), and adds pending removals.+    #[tokio::test(flavor = "multi_thread")]+    async fn from_task_nets_pending_changes() {+        let tt = setup_with_data(&[(2, UPPER)], false);+        let other = other_collectible();+        let mut ctx = ExecuteContext::new(&tt);+        let mut task = ctx.task(id(2), TaskDataCategory::All);+        let _ = task.update_collectibles_positive_crossing(collectible(), 1);+        task.update_aggregated_collectibles(collectible(), |_| Some(1));+        let _ = task.update_pending_collectibles_count(collectible(), 1);+        let _ = task.update_pending_collectibles_count(other, -1);+        let mut update = AggregatedDataUpdate::from_task(&mut task).collectibles_update;+        update.sort_by_key(|(collectible, _)| collectible.cell.task);+        assert_eq!(update.as_slice(), [(collectible(), 1), (other, 1)]);+    }++    /// When both the own and the aggregated entry of a collectible are pending, `from_task` must+    /// not leave opposite entries for it.+    #[tokio::test(flavor = "multi_thread")]+    async fn from_task_combines_own_and_aggregated_entries() {+        let tt = setup_with_data(&[(2, UPPER)], false);+        let mut ctx = ExecuteContext::new(&tt);+        let mut task = ctx.task(id(2), TaskDataCategory::All);+        let _ = task.update_collectibles_positive_crossing(collectible(), 1);+        task.update_aggregated_collectibles(collectible(), |_| Some(1));+        let _ = task.update_pending_collectibles_count(collectible(), 2);+        let update = AggregatedDataUpdate::from_task(&mut task).collectibles_update;+        assert!(update.is_empty(), "{update:?}");+    }++    /// Edge balancing of an aggregating task whose own and aggregated entries are both pending+    /// doesn't invalidate the readers of the new upper, which already sees the collectible from+    /// another inner task.+    #[tokio::test(flavor = "multi_thread")]+    async fn new_inner_edge_with_own_and_aggregated_pending_changes() {+        let tt = setup_with_data(+            &[(1, UPPER), (2, FOLLOWER), (3, FOLLOWER + 1), (READER, 0)],+            false,+        );+        run(&tt, [add(1, 2), add(3, 2)]);+        set_dirty(&tt, 2, true);+        {+            let mut ctx = ExecuteContext::new(&tt);+            let mut task = ctx.task(id(2), TaskDataCategory::All);+            let _ = task.update_collectibles_positive_crossing(collectible(), 1);+            task.update_aggregated_collectibles(collectible(), |_| Some(1));+            let _ = task.update_pending_collectibles_count(collectible(), 2);+        }+        {+            // Another inner task of 1 contributes the collectible already.+            let mut ctx = ExecuteContext::new(&tt);+            let mut task = ctx.task(id(1), TaskDataCategory::All);+            task.update_aggregated_collectibles(collectible(), |_| Some(1));+        }+        add_reader(&tt, 1);++        // Still aggregating, but lower than 1, so the follower edge becomes an inner edge.+        set_aggregation_number(&tt, 2, UPPER / 2);+        run(&tt, [balance(1, 2)]);+        assert_eq!(uppers(&tt, 2), vec![(id(1), 1), (id(3), 1)]);+        assert_eq!(aggregated(&tt, 1), 1);+        assert!(+            !reader_is_dirty(&tt),+            "the unpublished collectible must not invalidate the reader"+        );+    }++    /// A clean flush nets the update's changes with the pending ones: one non-zero entry per+    /// collectible.+    #[tokio::test(flavor = "multi_thread")]+    async fn clean_flush_combines_update_and_pending_changes() {+        let tt = setup_with_data(&[(1, UPPER), (2, INNER)], false);+        run(&tt, [add(1, 2)]);+        let other = other_collectible();+        let third = CollectibleRef {+            cell: CellRef {+                task: id(1002),+                ..collectible().cell+            },+            ..collectible()+        };+        let mut ctx = ExecuteContext::new(&tt);+        let mut task = ctx.task(id(2), TaskDataCategory::All);+        let _ = task.update_pending_collectibles_count(collectible(), 1);+        let _ = task.update_pending_collectibles_count(other, 1);+        let mut update = AggregatedDataUpdate::new()+            .collectibles_update(smallvec![(collectible(), -1), (third, 1)]);+        stage_outgoing_collectibles(&mut task, &mut update);+        let mut update = update.collectibles_update;+        update.sort_by_key(|(collectible, _)| collectible.cell.task);+        assert_eq!(update.as_slice(), [(other, 1), (third, 1)]);+        assert!(task.is_pending_collectibles_empty());+    }++    fn other_collectible() -> CollectibleRef {+        CollectibleRef {+            cell: CellRef {+                task: id(1001),+                ..collectible().cell+            },+            ..collectible()+        }+    }++    fn check(tt: &TurboTasks<TurboTasksBackend>, task: u32) -> Result<(), String> {+        let mut ctx = ExecuteContext::new(tt);+        check_pending_collectibles_invariant(&mut ctx, id(task))+    }++    #[tokio::test(flavor = "multi_thread")]+    async fn invariant_check_accepts_pending_changes_of_dirty_tasks() {+        let tt = setup_with_data(&[(1, UPPER), (2, INNER)], false);+        run(&tt, [add(1, 2)]);+        set_dirty(&tt, 2, true);+        emit(&tt, 2, 1);+        assert_eq!(pending(&tt, 2), 1);+        assert_eq!(check(&tt, 2), Ok(()));+        set_dirty(&tt, 2, false);+        assert_eq!(check(&tt, 2), Ok(()));+    }++    #[tokio::test(flavor = "multi_thread")]+    async fn invariant_check_reports_pending_changes_of_clean_tasks() {+        let tt = setup_with_data(&[(1, UPPER), (2, INNER)], false);+        run(&tt, [add(1, 2)]);+        {+            let mut ctx = ExecuteContext::new(&tt);+            let mut task = ctx.task(id(2), TaskDataCategory::Meta);+            let _ = task.update_pending_collectibles_count(collectible(), 1);+        }+        let error = check(&tt, 2).unwrap_err();+        assert!(error.contains("is not dirty"), "{error}");+    }++    #[tokio::test(flavor = "multi_thread")]+    async fn invariant_check_reports_pending_changes_missing_in_upper() {+        let tt = setup_with_data(&[(1, UPPER), (2, INNER)], false);+        run(&tt, [add(1, 2)]);+        {+            // Dirty and pending, but the dirty state was never sent to the upper.+            let mut ctx = ExecuteContext::new(&tt);+            let mut task = ctx.task(id(2), TaskDataCategory::All);+            task.set_dirty(Dirtyness::Dirty {+                parent_priority: TaskPriority::leaf(),+                #[cfg(feature = "task_dirty_cause")]+                cause: turbo_tasks::TaskDirtyCause::InitialDirty,+            });+            let _ = task.update_pending_collectibles_count(collectible(), 1);+        }+        let error = check(&tt, 2).unwrap_err();+        assert!(error.contains("not a dirty container"), "{error}");+    }+}+ /// Deterministic tests of the deferred removal queue: within one queue, edge removals are /// processed after additions and balancing. #[cfg(test)]
turbopack/crates/turbo-tasks-backend/src/backend/operation/cleanup_old_edges.rs4 + / 4 −
@@ -14,6 +14,7 @@ use crate::{                 AggregationUpdateJob, AggregationUpdateQueue, InnerOfUppersLostFollowersJob,                 get_aggregation_number, get_uppers, is_aggregating_node,             },+            stage_outgoing_collectibles,         },         storage_schema::{ActivenessAccessors, TaskStorageAccessors},     },@@ -256,10 +257,9 @@ fn cleanup_old_edges_inner(                         collectible_type: ty,                     });                 }-                queue.extend(AggregationUpdateJob::data_update(-                    &mut task,-                    AggregatedDataUpdate::new().collectibles_update(collectibles),-                ));+                let mut update = AggregatedDataUpdate::new().collectibles_update(collectibles);+                stage_outgoing_collectibles(&mut task, &mut update);+                queue.extend(AggregationUpdateJob::data_update(&mut task, update));             }             OutdatedEdge::CellDependency { dependent, cell } => {                 {
turbopack/crates/turbo-tasks-backend/src/backend/operation/mod.rs6 + / 2 −
@@ -29,6 +29,8 @@ use turbo_tasks::{ pub use self::aggregation_edge::{TaskAggregationEdges, verify_aggregation_edges}; #[cfg(not(target_family = "wasm"))] pub use self::aggregation_update::aggregation_queue;+#[cfg(feature = "verify_aggregation_graph")]+pub use self::aggregation_update::check_pending_collectibles_invariant; pub use self::aggregation_update::{AggregationUpdateQueue, ComputeDirtyAndCleanUpdate}; use crate::{     backend::{@@ -1621,7 +1623,9 @@ impl<'a> TaskGuard<'a> {         }         result             .aggregated_update(task_id)-            .and_then(|aggregated_update| {+            .and_then(|mut aggregated_update| {+                // Becoming clean sends the pending collectible changes.+                stage_outgoing_collectibles(self, &mut aggregated_update);                 AggregationUpdateJob::data_update(self, aggregated_update)             })     }@@ -1922,7 +1926,7 @@ impl TaskStorageAccessors for TaskGuard<'_> { pub use self::{     aggregation_update::{         AggregatedDataUpdate, AggregationUpdateJob, CollectiblesUpdateVec, get_aggregation_number,-        get_uppers, is_aggregating_node, is_root_node,+        get_uppers, is_aggregating_node, is_root_node, stage_outgoing_collectibles,     },     cleanup_old_edges::{         OutdatedEdge, capture_all_edges, cleanup_old_edges, cleanup_old_edges_deletions_only,
turbopack/crates/turbo-tasks-backend/src/backend/operation/update_collectible.rs4 + / 5 −
@@ -8,7 +8,7 @@ use crate::{         TaskDataCategory,         operation::{             AggregatedDataUpdate, AggregationUpdateJob, AggregationUpdateQueue,-            CollectiblesUpdateVec, ExecuteContext,+            CollectiblesUpdateVec, ExecuteContext, stage_outgoing_collectibles,         },         storage_schema::TaskStorageAccessors,     },@@ -92,10 +92,9 @@ impl UpdateCollectibleOperation {             }         }         if !collectibles.is_empty() {-            queue.extend(AggregationUpdateJob::data_update(-                &mut task,-                AggregatedDataUpdate::new().collectibles_update(collectibles),-            ));+            let mut update = AggregatedDataUpdate::new().collectibles_update(collectibles);+            stage_outgoing_collectibles(&mut task, &mut update);+            queue.extend(AggregationUpdateJob::data_update(&mut task, update));         }          drop(task);
turbopack/crates/turbo-tasks-backend/src/backend/storage_schema.rs7 + / 0 −
@@ -113,6 +113,13 @@ struct TaskStorageSchema {     #[field(storage = "counter_map", category = "meta", filter_transient)]     aggregated_collectibles: CounterMap<CollectibleRef, i32, 1>, +    /// Changes of this task's contribution to its uppers' aggregated collectibles that haven't+    /// been sent to the uppers yet: while the task is dirty, these changes are netted here and+    /// sent once, together with the update that makes the task clean (see+    /// `aggregation_update::stage_outgoing_collectibles`).+    #[field(storage = "counter_map", category = "meta", filter_transient)]+    pending_collectibles: CounterMap<CollectibleRef, i32, 1>,+     /// Outdated collectibles to be cleaned up (transient).     #[field(storage = "counter_map", category = "transient", shrink_on_completion)]     outdated_collectibles: CounterMap<CollectibleRef, i32, 1>,
turbopack/crates/turbo-tasks-backend/tests/collectibles.rs7 + / 5 −
@@ -20,7 +20,7 @@ async fn test_transitive_emitting() {         #[turbo_tasks::function(operation, root)]         async fn operation() -> Result<Vc<()>> {             let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!(""));-            let result_val = result_op.connect().await?;+            let result_val = result_op.read_strongly_consistent().await?;             let list = result_op.peek_collectibles::<Box<dyn ValueToString>>();             assert_eq!(list.len(), 2);             let mut expected = ["123", "42"].into_iter().collect::<FxHashSet<_>>();@@ -69,7 +69,7 @@ async fn test_multi_emitting() {         #[turbo_tasks::function(operation, root)]         async fn operation() -> Result<Vc<()>> {             let result_op = my_multi_emitting_function();-            let result_val = result_op.connect().await?;+            let result_val = result_op.read_strongly_consistent().await?;             let list = result_op.peek_collectibles::<Box<dyn ValueToString>>();             assert_eq!(list.len(), 2);             let mut expected = ["123", "42"].into_iter().collect::<FxHashSet<_>>();@@ -182,7 +182,8 @@ struct Collectibles(AutoSet<ResolvedVc<Box<dyn ValueToString>>>); async fn my_collecting_function() -> Result<Vc<Thing>> {     let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!(""));     let result_vc = result_op.connect();-    result_vc.await?;+    // Collectibles are only stable after a strongly consistent read of their source.+    result_op.read_strongly_consistent().await?;     result_op.drop_collectibles::<Box<dyn ValueToString>>();     Ok(result_vc) }@@ -219,11 +220,12 @@ async fn my_transitive_emitting_function(key: RcStr, key2: RcStr) -> Result<Vc<T }  #[turbo_tasks::function(operation, root)]-fn my_transitive_emitting_function_collectibles(+async fn my_transitive_emitting_function_collectibles(     key: RcStr,     key2: RcStr, ) -> Result<Vc<Collectibles>> {     let result_op = my_transitive_emitting_function(key, key2);+    result_op.read_strongly_consistent().await?;     Ok(Vc::cell(         result_op.peek_collectibles::<Box<dyn ValueToString>>(),     ))@@ -238,7 +240,7 @@ async fn my_transitive_emitting_function_with_child_scope(     let _ = key3;     let thing_op = my_transitive_emitting_function(key, key2);     let thing_vc = thing_op.connect();-    thing_vc.await?;+    thing_op.read_strongly_consistent().await?;     let list = thing_op.peek_collectibles::<Box<dyn ValueToString>>();     assert_eq!(list.len(), 2);     Ok(thing_vc)
turbopack/crates/turbo-tasks-backend/tests/collectibles_pending_restart.rsadded258 + / 0 −
@@ -0,0 +1,258 @@+#![feature(arbitrary_self_types)]+#![feature(arbitrary_self_types_pointers)]+#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this++//! Collectible changes that are delayed while a task is dirty (its `pending_collectibles`) must+//! survive a restart: they are persisted with the task and sent to the uppers once the task is+//! clean in a later session, neither lost nor applied twice.+//!+//! The changes are delayed in an aggregating task with a dirty child. The child can't finish in+//! the session that delays the changes, so it is still dirty when that session shuts down and the+//! pending changes are part of the snapshot written on shutdown.++mod util;++use std::{+    sync::atomic::{AtomicBool, Ordering},+    time::Duration,+};++use anyhow::Result;+use turbo_rcstr::RcStr;+use turbo_tasks::{+    CollectiblesSource, ResolvedVc, State, TaskId, ValueToString, Vc, emit, run_once,+};++use crate::util::{create_tt, reopen_tt_with_gc};++/// Children of [`middle`] that don't emit anything. They give [`middle`] enough children to make+/// it an aggregating node, which is where the changes of its children are delayed.+const FILLERS: u32 = 256;++/// While set, the emitter of `b` never finishes.+static BLOCK_B: AtomicBool = AtomicBool::new(false);++#[turbo_tasks::value(transparent)]+struct Input(State<u32>);++#[turbo_tasks::function(operation, root)]+fn create_input(name: RcStr) -> Vc<Input> {+    let _ = name;+    Input(State::new(0)).cell()+}++#[turbo_tasks::value]+struct Thing(RcStr);++#[turbo_tasks::value_impl]+impl ValueToString for Thing {+    #[turbo_tasks::function]+    fn to_string(&self) -> Vc<RcStr> {+        Vc::cell(self.0.clone())+    }+}++/// A separate task per name and value, so that a changed value is a different collectible rather+/// than a changed cell of the same collectible.+#[turbo_tasks::function]+fn thing(name: RcStr, value: u32) -> Vc<Thing> {+    Thing(format!("{name} {value}").into()).cell()+}++/// Emits `<name> <value of input>`.+#[turbo_tasks::function]+async fn emitter(name: RcStr, input: ResolvedVc<Input>) -> Result<Vc<()>> {+    let value = *input.await?.get();+    if name == "b" && BLOCK_B.load(Ordering::SeqCst) {+        // Keeps the emitter of `b` dirty until the session ends.+        std::future::pending::<()>().await;+    }+    emit(ResolvedVc::upcast::<Box<dyn ValueToString>>(+        thing(name, value).to_resolved().await?,+    ));+    Ok(Vc::cell(()))+}++#[turbo_tasks::function]+fn filler(index: u32) -> Vc<u32> {+    Vc::cell(index)+}++/// Returns the task id of the emitter of `b`.+#[turbo_tasks::function]+async fn middle(a: ResolvedVc<Input>, b: ResolvedVc<Input>) -> Result<Vc<u32>> {+    let a_emitter = emitter(rcstr("a"), *a);+    a_emitter.await?;+    let b_emitter = emitter(rcstr("b"), *b);+    b_emitter.await?;+    for index in 0..FILLERS {+        filler(index).await?;+    }+    Ok(Vc::cell(*task_id_of(b_emitter)))+}++#[turbo_tasks::value(transparent)]+struct TaskIds((u32, u32));++/// Returns the task ids of `middle` and of the emitter of `b`. Getting them from the calls in the+/// graph doesn't add any edges to the graph.+#[turbo_tasks::function(operation, root)]+async fn source(a: ResolvedVc<Input>, b: ResolvedVc<Input>) -> Result<Vc<TaskIds>> {+    let middle = middle(*a, *b);+    let b_emitter_id = *middle.await?;+    Ok(Vc::cell((*task_id_of(middle), b_emitter_id)))+}++#[turbo_tasks::value(transparent)]+struct Names(Vec<RcStr>);++/// The collectibles of [`source`], read after a strongly consistent read of it.+#[turbo_tasks::function(operation, root)]+async fn collect(a: ResolvedVc<Input>, b: ResolvedVc<Input>) -> Result<Vc<Names>> {+    let source = source(a, b);+    source.read_strongly_consistent().await?;+    let mut names = Vec::new();+    for collectible in source.peek_collectibles::<Box<dyn ValueToString>>() {+        names.push((*collectible.to_string().await?).clone());+    }+    names.sort();+    Ok(Vc::cell(names))+}++/// Another root that only reads the emitter of `a`, so `a` can be recomputed without reading the+/// tasks that contain it in [`source`].+#[turbo_tasks::function(operation, root)]+async fn only_a(a: ResolvedVc<Input>) -> Result<Vc<()>> {+    emitter(rcstr("a"), *a).await?;+    Ok(Vc::cell(()))+}++fn rcstr(s: &str) -> RcStr {+    s.into()+}++fn task_id_of<T>(vc: Vc<T>) -> TaskId {+    Vc::into_raw(vc)+        .try_get_task_id()+        .expect("a function call should be backed by a task")+}++async fn inputs() -> Result<(ResolvedVc<Input>, ResolvedVc<Input>)> {+    let a = create_input(rcstr("a"))+        .resolve()+        .strongly_consistent()+        .await?;+    let b = create_input(rcstr("b"))+        .resolve()+        .strongly_consistent()+        .await?;+    Ok((a, b))+}++async fn read_collected(a: ResolvedVc<Input>, b: ResolvedVc<Input>) -> Result<Vec<RcStr>> {+    Ok(collect(a, b).read_strongly_consistent().await?.to_vec())+}++fn names(names: &[&str]) -> Vec<RcStr> {+    names.iter().map(|&name| name.into()).collect()+}++#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn pending_collectibles_survive_a_restart() {+    let (tt, dir) = create_tt("pending_collectibles_survive_a_restart");++    // Session 1: build the graph.+    let (middle_id, b_emitter_id) = run_once(tt.clone(), async move {+        let (a, b) = inputs().await?;+        assert_eq!(read_collected(a, b).await?, names(&["a 0", "b 0"]));+        let (middle_id, b_emitter_id) = *source(a, b).read_strongly_consistent().await?;+        anyhow::Ok((+            TaskId::try_from(middle_id)?,+            TaskId::try_from(b_emitter_id)?,+        ))+    })+    .await+    .unwrap();+    tt.stop_and_wait().await;+    drop(tt);++    // Session 2: invalidate the emitter of `b`, which can't finish in this session, so it stays+    // dirty and `middle` has a dirty child. Then recompute the emitter of `a` through another root.+    // Its changes reach `middle` while `middle` has the dirty child, so `middle` delays them.+    BLOCK_B.store(true, Ordering::SeqCst);+    let tt = reopen_tt_with_gc(&dir);+    let tt2 = tt.clone();+    run_once(tt.clone(), async move {+        let (a, b) = inputs().await?;+        b.await?.set(1);+        a.await?.set(1);+        only_a(a).read_strongly_consistent().await?;+        assert_eq!(+            tt2.backend().is_dirty_for_testing(b_emitter_id, &tt2),+            Some(true),+            "the emitter of b must still be dirty"+        );+        // The read of `only_a` can finish before the changes have been applied to `middle`, its+        // other upper.+        let mut attempts = 0;+        while tt2+            .backend()+            .pending_collectibles_count_for_testing(middle_id, &tt2)+            .is_none_or(|pending| pending == 0)+        {+            attempts += 1;+            assert!(+                attempts < 500,+                "middle must have pending collectible changes before the restart"+            );+            tokio::time::sleep(Duration::from_millis(10)).await;+        }+        anyhow::Ok(())+    })+    .await+    .unwrap();+    // The shutdown snapshot persists the pending changes of `middle`.+    tokio::time::timeout(Duration::from_secs(30), tt.stop_and_wait())+        .await+        .expect("stop_and_wait hung on the blocked emitter of b");+    drop(tt);+    BLOCK_B.store(false, Ordering::SeqCst);++    // Session 3: the pending changes are restored from the snapshot.+    let tt = reopen_tt_with_gc(&dir);+    let tt2 = tt.clone();+    run_once(tt.clone(), async move {+        assert_eq!(+            tt2.backend().is_dirty_for_testing(b_emitter_id, &tt2),+            Some(true),+            "the emitter of b must be restored as dirty"+        );+        assert!(+            tt2.backend()+                .pending_collectibles_count_for_testing(middle_id, &tt2)+                .is_some_and(|pending| pending > 0),+            "the pending collectible changes of middle must be restored"+        );++        let (a, b) = inputs().await?;+        // Reading the source strongly consistently recomputes the emitter of `b`, which makes+        // `middle` clean and sends its pending changes. Losing them would keep `a 0`.+        assert_eq!(read_collected(a, b).await?, names(&["a 1", "b 1"]));+        assert_eq!(+            tt2.backend()+                .pending_collectibles_count_for_testing(middle_id, &tt2),+            Some(0),+            "middle must have sent its pending changes"+        );++        // Changing `a` again removes `a 1`. If the pending changes were applied twice, `a 1` would+        // still be counted once and stay visible.+        a.await?.set(2);+        assert_eq!(read_collected(a, b).await?, names(&["a 2", "b 1"]));+        anyhow::Ok(())+    })+    .await+    .unwrap();++    tt.stop_and_wait().await;+}
turbopack/crates/turbo-tasks-backend/tests/collectibles_read_race.rs3 + / 1 −
@@ -125,7 +125,9 @@ struct DriverResult(Vec<(u32, Vec<RcStr>)>);  #[turbo_tasks::function(operation, root)] async fn driver(generation: ResolvedVc<Generation>) -> Result<Vc<DriverResult>> {-    emitter(generation).connect().await?;+    // Collectibles are only stable after a strongly consistent read of their source. The readers+    // still race with the collectibles change: they re-execute as soon as the generation changes.+    emitter(generation).read_strongly_consistent().await?;     let readers = (0..READERS)         .map(|index| reader(*generation, index))         .collect::<Vec<_>>();
turbopack/crates/turbo-tasks-backend/tests/collectibles_take_batch.rs5 + / 4 −
@@ -130,7 +130,8 @@ async fn emit_keep(count: u32) -> Result<()> { #[turbo_tasks::function(operation, root)] async fn taking_operation(input: ResolvedVc<ChangingInput>, drop: bool) -> Result<Vc<u32>> {     let child = child_operation(input);-    let count = *child.connect().await?;+    // Collectibles are only stable after a strongly consistent read of their source.+    let count = *child.read_strongly_consistent().await?;     let taken = if drop {         child.drop_collectibles::<Box<dyn ValueToString>>();         0@@ -149,7 +150,7 @@ struct Strings(Vec<String>); #[turbo_tasks::function(operation, root)] async fn outer_taking_operation(input: ResolvedVc<ChangingInput>) -> Result<Vc<Strings>> {     let taking = taking_operation(input, false);-    taking.connect().await?;+    taking.read_strongly_consistent().await?;     let mut taken = Vec::new();     for collectible in taking.take_collectibles::<Box<dyn ValueToString>>() {         taken.push(collectible.to_string().await?.to_string());@@ -166,7 +167,7 @@ fn empty_operation() -> Vc<()> { #[turbo_tasks::function(operation, root)] async fn empty_taking_operation() -> Result<Vc<u32>> {     let empty = empty_operation();-    empty.connect().await?;+    empty.read_strongly_consistent().await?;     Ok(Vc::cell(         empty.take_collectibles::<Box<dyn ValueToString>>().len() as u32,     ))@@ -187,7 +188,7 @@ async fn upper_operation( ) -> Result<Vc<UpperRead>> {     let _ = upper;     let taking = taking_operation(input, drop);-    let taken = *taking.connect().await?;+    let taken = *taking.read_strongly_consistent().await?;     let mut visible = Vec::new();     for collectible in taking.peek_collectibles::<Box<dyn ValueToString>>() {         visible.push(collectible.to_string().await?.to_string());
turbopack/crates/turbo-tasks-backend/tests/collectibles_take_many_uppers.rs3 + / 2 −
@@ -93,7 +93,8 @@ async fn emit_keep(count: u32) -> Result<()> { #[turbo_tasks::function(operation, root)] async fn taking_operation(input: ResolvedVc<ChangingInput>) -> Result<Vc<u32>> {     let child = child_operation(input);-    let count = *child.connect().await?;+    // Collectibles are only stable after a strongly consistent read of their source.+    let count = *child.read_strongly_consistent().await?;     let taken = child.take_collectibles::<Box<dyn ValueToString>>();     emit_keep(count).await?;     Ok(Vc::cell(taken.len() as u32))@@ -110,7 +111,7 @@ struct UpperRead { async fn upper_operation(input: ResolvedVc<ChangingInput>, upper: u32) -> Result<Vc<UpperRead>> {     let _ = upper;     let taking = taking_operation(input);-    let taken = *taking.connect().await?;+    let taken = *taking.read_strongly_consistent().await?;     let mut visible = Vec::new();     for collectible in taking.peek_collectibles::<Box<dyn ValueToString>>() {         visible.push(collectible.to_string().await?.to_string());
turbopack/crates/turbo-tasks-backend/tests/recompute_collectibles.rs2 + / 1 −
@@ -104,7 +104,8 @@ async fn compute(         return Ok(compute(input, input2, innerness - 1).connect());     }     let operation = inner_compute(input, input2);-    let value = *operation.connect().await?;+    // Collectibles are only stable after a strongly consistent read of their source.+    let value = *operation.read_strongly_consistent().await?;     let collectibles = operation.peek_collectibles::<Box<dyn ValueToString>>();     if collectibles.len() != 1 {         bail!("expected 1 collectible, found {}", collectibles.len());
turbopack/crates/turbo-tasks-macros/src/derive/task_storage_macro.rs32 + / 0 −
@@ -2601,6 +2601,31 @@ fn generate_countermap_ops(field: &FieldInfo) -> TokenStream {         quote! { #ref_expr.iter() }     }; +    // Generate take body: removes the whole map. Only tracks modification if the map is non-empty+    // (tracking is a no-op for transient fields).+    let take_name = field.prefixed_ident("take");+    let take_body = if is_option {+        let extractor = field.lazy_extractor_closure();+        let unwraper = field.lazy_unwrap_closure();+        quote! {+            let (idx, val) = self.typed().find_lazy_ref(#extractor)?;+            if val.is_empty() {+                return None;+            }+            #track_modification+            Some(self.typed_mut().lazy_take_at(idx, #unwraper))+        }+    } else {+        let typed_take_name = field.take_ident();+        quote! {+            if self.#is_empty_name() {+                return None;+            }+            #track_modification+            Some(self.typed_mut().#typed_take_name())+        }+    };+     // Generate signed-type-specific methods only for i32     let signed_methods = if is_signed {         let update_positive_crossing_name = field.infixed_ident("update", "positive_crossing");@@ -2845,6 +2870,13 @@ fn generate_countermap_ops(field: &FieldInfo) -> TokenStream {             #iter_body         } +        #[doc = "Remove the full counter map and return it."]+        #[doc = "Only tracks modification if the map is non-empty."]+        fn #take_name(&mut self) -> Option<#field_type> {+            #check_access+            #take_body+        }+         #signed_methods     } }
turbopack/crates/turbo-tasks/src/collectibles.rs5 + / 0 −
@@ -3,6 +3,11 @@ use auto_hash_map::AutoSet; use crate::{ResolvedVc, VcValueTrait};  /// Implemented on `OperationVc` and `RawVc`.+///+/// Collectibles are only stable after a strongly consistent read of their source (e.g.+/// [`OperationVc::read_strongly_consistent`][crate::OperationVc::read_strongly_consistent]). After+/// a read that isn't strongly consistent, collectibles of tasks in the source's subgraph that are+/// still being recomputed may not be visible yet. pub trait CollectiblesSource {     fn drop_collectibles<T: VcValueTrait>(self);     fn take_collectibles<T: VcValueTrait>(self) -> AutoSet<ResolvedVc<T>>;
turbopack/crates/turbo-tasks/src/effect.rs2 + / 2 −
@@ -297,8 +297,8 @@ impl EffectStateStorage { /// #[turbo_tasks::function(operation)] /// async fn some_turbo_tasks_operation_with_effects(args: Args) -> Result<Vc<OutputWithEffects>> { ///     let operation = some_turbo_tasks_operation(args);-///     // we must first read the operation to populate the collectibles-///     let output = operation.connect().await?;+///     // collectibles are only stable after a strongly consistent read of their source+///     let output = operation.read_strongly_consistent().await?; ///     // read the effects from the collectibles ///     let effects = take_effects(operation).await?; ///     Ok(OutputWithEffects { output, effects }.cell())
turbopack/crates/turbopack-core/src/module_graph/mod.rs2 + / 1 −
@@ -2675,7 +2675,8 @@ pub mod tests {     async fn import_trace_issues_operation(         trace_operation: OperationVc<ImportTraceTestResult>,     ) -> Result<Vc<ImportTraceIssues>> {-        let _ = trace_operation.connect().await?;+        // Collectibles are only stable after a strongly consistent read of their source.+        let _ = trace_operation.read_strongly_consistent().await?;         let issues = trace_operation             .peek_issues()             .iter()
turbopack/crates/turbopack-dev-server/src/update/stream.rs5 + / 2 −
@@ -175,18 +175,21 @@ async fn get_update_stream_item_operation(             let resolved_content = static_content.content;             let from = from.get().to_resolved().await?;             let update_op = versioned_content_update_operation(resolved_content, from);+            // Collectibles are only stable after a strongly consistent read of their source.+            let update = update_op.read_strongly_consistent().await?;              extend_issues(&mut plain_issues, peek_issues(update_op).await?);              Ok(UpdateStreamItem::Found {-                update: update_op.connect().await?,+                update,                 issues: plain_issues,             }             .cell())         }         ResolveSourceRequestResult::HttpProxy(proxy_result_op) => {             let proxy_result_vc = proxy_result_op.connect();-            let proxy_result_value = proxy_result_vc.await?;+            // Collectibles are only stable after a strongly consistent read of their source.+            let proxy_result_value = proxy_result_op.read_strongly_consistent().await?;              if proxy_result_value.status == 404 {                 return Ok(UpdateStreamItem::NotFound.cell());
turbopack/crates/turbopack-tests/tests/execution.rs2 + / 1 −
@@ -254,7 +254,8 @@ async fn run(resource: PathBuf, snapshot_mode: IssueSnapshotMode) -> Result<JsRe         snapshot_mode: IssueSnapshotMode,     ) -> Result<Vc<JsResultWithEffects>> {         let op = run_inner_operation(resource, snapshot_mode);-        let result = op.connect().await?.clone();+        // Collectibles are only stable after a strongly consistent read of their source.+        let result = op.read_strongly_consistent().await?.clone();         let effects = take_effects(op).await?;         Ok(JsResultWithEffects { result, effects }.cell())     }