From 71703856c8efc83a3730b5f054b66960eccce39c Mon Sep 17 00:00:00 2001 From: Luke Sandberg Date: Sat, 21 Nov 2026 16:00:50 -0800 Subject: [PATCH 1/2] turbo-tasks: fail executions that use a cell of a task GC collected mid-execution Co-Authored-By: Claude Opus 5.5 --- .../turbo-tasks-backend/src/backend/mod.rs | 52 +++-- .../src/backend/operation/update_cell.rs | 18 +- .../tests/gc_in_progress_reader.rs | 195 ++++++++++++++++++ turbopack/crates/turbo-tasks/src/backend.rs | 13 +- turbopack/crates/turbo-tasks/src/manager.rs | 38 +++- .../turbo-tasks/src/vc/keyed_read_ref.rs | 7 +- .../turbo-tasks/src/vc/lazy_read_ref.rs | 7 +- turbopack/crates/turbo-tasks/src/vc/mod.rs | 3 +- 8 files changed, 298 insertions(+), 35 deletions(-) create mode 100644 turbopack/crates/turbo-tasks-backend/tests/gc_in_progress_reader.rs diff --git a/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs b/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs index 9babab362b69..372b90f535b6 100644 --- a/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs +++ b/turbopack/crates/turbo-tasks-backend/src/backend/mod.rs @@ -1256,12 +1256,20 @@ impl TurboTasksBackend { task_id: TaskId, cell: CellId, turbo_tasks: &TurboTasks, - ) { + ) -> Result<()> { let mut ctx = self.execute_context(turbo_tasks); - let mut task = ctx.task(task_id, TaskDataCategory::Data); + // The caller can hold a reference to a cell of a task that GC collected while it was + // executing (e.g. its parent dropped both). Fail like a read of that cell would. + let Some(mut task) = ctx.try_task(task_id, TaskDataCategory::Data) else { + return Err(collected_task_read_error( + task_id, + "drop_task_cell_content_hint", + )); + }; // Only drop the content, if it's there. A later read recomputes the task, exactly like // after a `final_read_hint` read. let _ = task.remove_cell_data(&cell, &get_value_type(cell.type_id()).persistence); + Ok(()) } /// Refines the [`CellKeyKind::Provisional`] dependency of `reader` on `cell` of `task_id` @@ -1273,6 +1281,11 @@ impl TurboTasksBackend { /// dependents), the [`CellKeyKind::Provisional`] dependency is kept, conservatively depending /// on the whole cell. /// + /// Fails when the cell's task no longer exists. GC doesn't wait for executions to finish, and + /// it ignores cell dependents, so it collects the task of a cell that `reader` is still using + /// when the task's parent drops it. That usually means `reader` is being dropped by its own + /// parent as well, so the caller fails the execution. + /// /// [`CellKeyKind::Provisional`]: turbo_tasks::CellKeyKind::Provisional /// [`CellKeyKind::Hash`]: turbo_tasks::CellKeyKind::Hash fn refine_provisional_cell_dependency( @@ -1283,28 +1296,40 @@ impl TurboTasksBackend { id: u32, key_hashes: impl IntoIterator, turbo_tasks: &TurboTasks, - ) { + ) -> Result<()> { if !self.should_track_dependencies() || reader == task_id { - return; + return Ok(()); } let mut ctx = self.execute_context(turbo_tasks); - let (mut task, mut reader_task) = ctx.task_pair(task_id, reader, TaskDataCategory::All); - let immutable = task.immutable() && !cfg!(feature = "verify_immutable"); - if !immutable && !task.cell_data_contains(&cell) { - return; - } - let reverse = CellRef { task: reader, cell }; let target = CellRef { task: task_id, cell, }; let provisional = CellKey::provisional(id); + // GC removed both halves of the edge when it collected the task. Drop the reader's half + // anyway, so nothing is left behind if it didn't. Checking existence first is race-free: + // the context excludes GC until it's dropped, and `task_pair` restores an evicted task. + if ctx.try_task(task_id, TaskDataCategory::All).is_none() { + let mut reader_task = ctx.task(reader, TaskDataCategory::Data); + reader_task.remove_cell_dependencies_keyed(&(target, provisional)); + reader_task.remove_outdated_cell_dependencies_keyed(&(target, provisional)); + return Err(collected_task_read_error( + task_id, + "refine_provisional_cell_dependency", + )); + } + let (mut task, mut reader_task) = ctx.task_pair(task_id, reader, TaskDataCategory::All); + let immutable = task.immutable() && !cfg!(feature = "verify_immutable"); + if !immutable && !task.cell_data_contains(&cell) { + return Ok(()); + } + let reverse = CellRef { task: reader, cell }; task.remove_keyed_cell_dependent(&(reverse, provisional)); reader_task.remove_cell_dependencies_keyed(&(target, provisional)); reader_task.remove_outdated_cell_dependencies_keyed(&(target, provisional)); // Immutable tasks never need dependency edges and can never be invalidated. if immutable { - return; + return Ok(()); } // Many readers can refine their dependencies on the same cell at once, all serialized on // the owner task's lock. So the owner side is updated first, and the owner is released @@ -1336,6 +1361,7 @@ impl TurboTasksBackend { let _ = reader_task.add_cell_dependencies_keyed((target, key)); } } + Ok(()) } /// Converts all [`CellKeyKind::Provisional`] dependencies of `reader` that are still present @@ -4263,7 +4289,7 @@ impl Backend for TurboTasksBackend { id: u32, key_hashes: impl IntoIterator, turbo_tasks: &TurboTasks, - ) { + ) -> Result<()> { self.refine_provisional_cell_dependency(task_id, cell, reader, id, key_hashes, turbo_tasks) } @@ -4281,7 +4307,7 @@ impl Backend for TurboTasksBackend { task_id: TaskId, cell: CellId, turbo_tasks: &TurboTasks, - ) { + ) -> Result<()> { self.drop_task_cell_content_hint(task_id, cell, turbo_tasks) } diff --git a/turbopack/crates/turbo-tasks-backend/src/backend/operation/update_cell.rs b/turbopack/crates/turbo-tasks-backend/src/backend/operation/update_cell.rs index 18e031cfed18..10229d8f13f9 100644 --- a/turbopack/crates/turbo-tasks-backend/src/backend/operation/update_cell.rs +++ b/turbopack/crates/turbo-tasks-backend/src/backend/operation/update_cell.rs @@ -631,14 +631,16 @@ mod invalidate_cell_dependents_tests { let _ = dependent.add_cell_dependencies_keyed((cell_ref(), CellKey::provisional(0))); } - tt.backend().refine_provisional_cell_dependency( - task(CELL_TASK), - cell_ref().cell, - task(DEPENDENT), - 0, - [1u64], - &tt, - ); + tt.backend() + .refine_provisional_cell_dependency( + task(CELL_TASK), + cell_ref().cell, + task(DEPENDENT), + 0, + [1u64], + &tt, + ) + .unwrap(); let mut ctx = ExecuteContext::new(&tt); let dependent = ctx.task(task(DEPENDENT), TaskDataCategory::All); diff --git a/turbopack/crates/turbo-tasks-backend/tests/gc_in_progress_reader.rs b/turbopack/crates/turbo-tasks-backend/tests/gc_in_progress_reader.rs new file mode 100644 index 000000000000..1854360421d3 --- /dev/null +++ b/turbopack/crates/turbo-tasks-backend/tests/gc_in_progress_reader.rs @@ -0,0 +1,195 @@ +#![feature(arbitrary_self_types)] +#![feature(arbitrary_self_types_pointers)] +#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this + +//! GC can collect a task while another task is in the middle of an execution that uses one of its +//! cells. +//! +//! GC only excludes backend operations, not task executions, and it never collects a task that is +//! in progress. But the collectibility check ignores cell dependents, so the task *owning* a cell +//! that an in-progress execution holds (through a `ResolvedVc` argument or a `KeyedReadRef`) is +//! collected as soon as its own parent drops it. The realistic case is a reader whose parent is +//! dropping both of them: the reader keeps running, and its remaining accesses to the collected +//! owner must fail the reader's execution instead of panicking in the backend. +//! +//! Each test holds the reader in its execution, disconnects the owner, collects it and evicts it +//! (a full snapshot drops the collected task from memory), and then releases the reader. + +mod gc_fixture; +mod util; + +use std::{sync::LazyLock, time::Duration}; + +use anyhow::Result; +use rustc_hash::FxHashMap; +use tokio::sync::Notify; +use turbo_tasks::{OperationVc, ResolvedVc, Vc, VcValueType}; + +use crate::{ + gc_fixture::{Constant, Selector, create_constant, create_selector}, + util::create_tt, +}; + +/// The message of the error a read of a collected task fails with (see +/// `collected_task_read_error` in the backend). +const COLLECTED_TASK_ERROR: &str = "no longer exists (it was garbage collected)"; + +#[turbo_tasks::value(transparent, cell = "keyed")] +struct Map(FxHashMap); + +/// The owner of the cell the reader uses. It reads `constant` so it is mutable: reads of an +/// immutable task record no dependency, and so would never be refined. +#[turbo_tasks::function] +async fn owner(constant: ResolvedVc) -> Result> { + let base = *constant.await?.get(); + Ok(Vc::cell(FxHashMap::from_iter([(1, base + 1)]))) +} + +/// The owner's only parent. Flipping the selector drops the owner without invalidating it. +#[turbo_tasks::function(operation, root)] +async fn select_owner( + selector: ResolvedVc, + constant: ResolvedVc, +) -> Result> { + Ok(if *selector.await?.get() { + Vc::cell(FxHashMap::default()) + } else { + owner(*constant) + }) +} + +/// Signals between a test and the reader task it holds in its execution. +struct Gate { + /// The reader has reached the point where it waits. + reached: Notify, + /// The test lets the reader continue. + release: Notify, +} + +impl Gate { + fn new() -> Self { + Self { + reached: Notify::new(), + release: Notify::new(), + } + } + + /// Called by the reader: signals the test, then waits until it is released. + async fn wait(&self) { + self.reached.notify_one(); + self.release.notified().await; + } +} + +static KEYED_READER_GATE: LazyLock = LazyLock::new(Gate::new); +static DROP_HINT_GATE: LazyLock = LazyLock::new(Gate::new); + +/// Holds a `KeyedReadRef` of the owner's cell across the gate. Dropping it afterwards refines the +/// provisional dependency the read created, which touches the (by then collected) owner. +#[turbo_tasks::function(operation, root)] +async fn keyed_reader_op(map: ResolvedVc) -> Result> { + let reader = map.keyed_reader().await?; + let value = reader.get(&1).copied().unwrap_or_default(); + KEYED_READER_GATE.wait().await; + drop(reader); + Ok(Vc::cell(value)) +} + +/// Holds a `ResolvedVc` to the owner's cell across the gate, then hints that its content can be +/// dropped. +#[turbo_tasks::function(operation, root)] +async fn drop_hint_op(map: ResolvedVc) -> Result> { + DROP_HINT_GATE.wait().await; + map.drop_content_hint().await?; + Ok(Vc::cell(())) +} + +/// Runs `reader` (an operation that waits on `gate` while holding a reference to the owner's cell) +/// across the collection of the owner, and returns its result. +async fn run_reader_across_owner_collection( + name: &str, + gate: &'static Gate, + reader: fn(ResolvedVc) -> OperationVc, +) -> Result<()> { + let (tt, _persistence_dir) = create_tt(name); + + // Build the owner and resolve its cell. + let (selector_op, selector_vc, constant_vc, map) = turbo_tasks::run_once(tt.clone(), async { + let selector_op = create_selector(false); + let selector_vc = selector_op.resolve().strongly_consistent().await?; + let constant_vc = create_constant().resolve().strongly_consistent().await?; + let map = select_owner(selector_vc, constant_vc) + .resolve() + .strongly_consistent() + .await?; + anyhow::Ok((selector_op, selector_vc, constant_vc, map)) + }) + .await + .unwrap(); + + // Start the reader and wait until it holds the reference. + let reader_result = tokio::spawn(turbo_tasks::run_once(tt.clone(), async move { + reader(map).read_strongly_consistent().await?; + Ok(()) + })); + tokio::time::timeout(Duration::from_secs(10), gate.reached.notified()) + .await + .expect("the reader should reach the gate"); + + // Disconnect the owner, then collect it and drop it from memory. + turbo_tasks::run_once(tt.clone(), async move { + selector_op.read_strongly_consistent().await?.set(true); + select_owner(selector_vc, constant_vc) + .read_strongly_consistent() + .await?; + anyhow::Ok(()) + }) + .await + .unwrap(); + let outcome = tt.backend().snapshot_and_evict_for_testing(&tt); + let (gc_stats, _) = outcome.gc.expect("GC is enabled"); + assert!( + gc_stats.collected >= 1, + "the disconnected owner should be collected while the reader is in progress" + ); + + // Let the reader finish its execution against the collected owner. + gate.release.notify_one(); + tokio::time::timeout(Duration::from_secs(10), reader_result) + .await + .expect("the reader should finish") + .expect("the reader task should not panic") +} + +fn assert_fails_with_collected_task_error(result: Result<()>) { + let error = result.expect_err("the reader should fail"); + let message = format!("{error:?}"); + assert!( + message.contains(COLLECTED_TASK_ERROR), + "expected a collected task error, got: {message}" + ); +} + +/// Dropping a `KeyedReadRef` whose cell's owner was collected fails the reader. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn refining_a_keyed_read_of_a_collected_task_fails_the_reader() { + let result = run_reader_across_owner_collection( + "refining_a_keyed_read_of_a_collected_task_fails_the_reader", + &KEYED_READER_GATE, + keyed_reader_op, + ) + .await; + assert_fails_with_collected_task_error(result); +} + +/// A content drop hint for a cell whose owner was collected fails the task giving the hint. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn drop_content_hint_of_a_collected_task_fails_the_caller() { + let result = run_reader_across_owner_collection( + "drop_content_hint_of_a_collected_task_fails_the_caller", + &DROP_HINT_GATE, + drop_hint_op, + ) + .await; + assert_fails_with_collected_task_error(result); +} diff --git a/turbopack/crates/turbo-tasks/src/backend.rs b/turbopack/crates/turbo-tasks/src/backend.rs index 4fd512afa2c9..d1d16f4f8e84 100644 --- a/turbopack/crates/turbo-tasks/src/backend.rs +++ b/turbopack/crates/turbo-tasks/src/backend.rs @@ -706,6 +706,9 @@ pub trait Backend: Sized + Sync + Send { /// /// Must only be called from within the same execution of `reader` that created the /// dependency. + /// + /// Fails when `task` no longer exists because it was garbage collected while `reader` was + /// executing. The caller fails that execution with the error. fn refine_provisional_cell_dependency( &self, task: TaskId, @@ -714,7 +717,7 @@ pub trait Backend: Sized + Sync + Send { id: u32, key_hashes: impl IntoIterator, turbo_tasks: &TurboTasks, - ); + ) -> Result<()>; /// INVALIDATION: Be careful with this, it will not track dependencies, so /// using it could break cache invalidation. @@ -729,8 +732,9 @@ pub trait Backend: Sized + Sync + Send { /// backend may drop it to free memory. A later read of a dropped cell recomputes the owning /// task, like after a `final_read_hint` read. /// - /// The task must exist. The cell content doesn't need to be present (e.g. it was already - /// dropped); this never reads or recomputes it. + /// The cell content doesn't need to be present (e.g. it was already dropped); this never + /// reads or recomputes it. Fails, like a read would, when the task no longer exists because it + /// was garbage collected. /// /// This doesn't track any dependency. The default implementation does nothing. fn drop_task_cell_content_hint( @@ -738,7 +742,8 @@ pub trait Backend: Sized + Sync + Send { _task_id: TaskId, _cell: CellId, _turbo_tasks: &TurboTasks, - ) { + ) -> Result<()> { + Ok(()) } /// INVALIDATION: Be careful with this, when reader is None, it will not track dependencies, so diff --git a/turbopack/crates/turbo-tasks/src/manager.rs b/turbopack/crates/turbo-tasks/src/manager.rs index 533dbeb596a0..88df6624b3b0 100644 --- a/turbopack/crates/turbo-tasks/src/manager.rs +++ b/turbopack/crates/turbo-tasks/src/manager.rs @@ -161,7 +161,7 @@ pub trait TurboTasksApi: TurboTasksCallApi + Sync + Send { reader: TaskId, id: u32, key_hashes: &FxHashSet, - ); + ) -> Result<()>; /// Reads a [`RawVcUnpacked::LocalOutput`][crate::RawVcUnpacked::LocalOutput]. If the task has /// completed, returns the [`RawVc`] the local task points to. @@ -211,7 +211,7 @@ pub trait TurboTasksApi: TurboTasksCallApi + Sync + Send { ) -> Result; /// See [`Backend::drop_task_cell_content_hint`]. - fn drop_task_cell_content_hint(&self, task: TaskId, index: CellId); + fn drop_task_cell_content_hint(&self, task: TaskId, index: CellId) -> Result<()>; fn read_own_task_cell(&self, task: TaskId, index: CellId) -> Result; fn update_own_task_cell( @@ -977,6 +977,11 @@ struct CurrentTaskStateInner { /// execution that haven't been dropped within this execution yet. When it isn't zero at the /// end of the execution, completing it panics (see [`PROVISIONAL_READ_REF_LEAKED`]). alive_provisional_read_refs: AtomicU32, + /// An error a drop of a [`KeyedReadRef`](crate::KeyedReadRef) / + /// [`LazyReadRef`](crate::LazyReadRef) of this execution ran into (see + /// [`ProvisionalReadDependency::fail_execution`]). A drop can't return it, so the execution + /// fails with it when it completes. + deferred_error: Mutex>, state: RwLock, } @@ -996,6 +1001,7 @@ impl CurrentTaskStateHandle { current_task_id: state.task_id, provisional_read_counter: AtomicU32::new(0), alive_provisional_read_refs: AtomicU32::new(0), + deferred_error: Mutex::new(None), state: RwLock::new(state), }), } @@ -1059,6 +1065,20 @@ impl ProvisionalReadDependency { } } + /// Fails the creating execution with `error` when it completes, unless it fails anyway. For + /// errors of a [`KeyedReadRef`](crate::KeyedReadRef) / [`LazyReadRef`](crate::LazyReadRef) + /// drop, which can't return them. Only called within the creating execution. The first error + /// is kept. + pub(crate) fn fail_execution(&self, error: anyhow::Error) { + if let Some(execution) = self.execution.upgrade() { + execution + .deferred_error + .lock() + .unwrap() + .get_or_insert(error); + } + } + /// Releases a registration made with [`ProvisionalReadDependency::register_alive_ref`]. Only /// called when the holder is dropped (or the read fails) within the creating execution /// ([`ProvisionalReadDependency::is_current_execution`]). @@ -1917,6 +1937,16 @@ impl Executor, ScheduledTask, TaskPriority> for TurboT Ok(Err(err)) => Err(err.into()), Err(err) => Err(TurboTasksExecutionError::Panic(Arc::new(err))), }; + // A `KeyedReadRef` / `LazyReadRef` drop that failed fails the + // execution (see `ProvisionalReadDependency::fail_execution`). + // All drops of this execution happened above, as local tasks + // were awaited. + let deferred_error = CURRENT_TASK_STATE + .with(|ts| ts.inner.deferred_error.lock().unwrap().take()); + let result = match (result, deferred_error) { + (Ok(_), Some(error)) => Err(error.into()), + (result, _) => result, + }; let finished_state = this.finish_current_task_state(); let ( @@ -2254,7 +2284,7 @@ impl TurboTasksApi for TurboTasks { reader: TaskId, id: u32, key_hashes: &FxHashSet, - ) { + ) -> Result<()> { self.backend.refine_provisional_cell_dependency( task, index, @@ -2274,7 +2304,7 @@ impl TurboTasksApi for TurboTasks { .try_read_own_task_cell(current_task, index, self) } - fn drop_task_cell_content_hint(&self, task: TaskId, index: CellId) { + fn drop_task_cell_content_hint(&self, task: TaskId, index: CellId) -> Result<()> { self.backend.drop_task_cell_content_hint(task, index, self) } diff --git a/turbopack/crates/turbo-tasks/src/vc/keyed_read_ref.rs b/turbopack/crates/turbo-tasks/src/vc/keyed_read_ref.rs index 352c2a94c289..ca87283a09d6 100644 --- a/turbopack/crates/turbo-tasks/src/vc/keyed_read_ref.rs +++ b/turbopack/crates/turbo-tasks/src/vc/keyed_read_ref.rs @@ -118,7 +118,7 @@ where } dependency.release_alive_ref(); let key_hashes = std::mem::take(self.accessed_key_hashes.get_mut()); - with_turbo_tasks(|tt| { + if let Err(error) = with_turbo_tasks(|tt| { tt.refine_provisional_cell_dependency( task, index, @@ -126,7 +126,10 @@ where dependency.id, &key_hashes, ) - }); + }) { + // The cell's task was garbage collected while this execution used it. + dependency.fail_execution(error); + } } } diff --git a/turbopack/crates/turbo-tasks/src/vc/lazy_read_ref.rs b/turbopack/crates/turbo-tasks/src/vc/lazy_read_ref.rs index 5fc578924548..0007a9659009 100644 --- a/turbopack/crates/turbo-tasks/src/vc/lazy_read_ref.rs +++ b/turbopack/crates/turbo-tasks/src/vc/lazy_read_ref.rs @@ -84,7 +84,7 @@ where return; } // Refining the provisional dependency to no hashed dependencies at all removes it. - with_turbo_tasks(|tt| { + if let Err(error) = with_turbo_tasks(|tt| { tt.refine_provisional_cell_dependency( task, index, @@ -92,7 +92,10 @@ where dependency.id, &FxHashSet::default(), ) - }); + }) { + // The cell's task was garbage collected while this execution used it. + dependency.fail_execution(error); + } } } diff --git a/turbopack/crates/turbo-tasks/src/vc/mod.rs b/turbopack/crates/turbo-tasks/src/vc/mod.rs index f3f72cd3f5de..63e3a95c7e05 100644 --- a/turbopack/crates/turbo-tasks/src/vc/mod.rs +++ b/turbopack/crates/turbo-tasks/src/vc/mod.rs @@ -460,8 +460,7 @@ where let RawVcUnpacked::TaskCell(task, index) = self.node.resolve().await?.unpack() else { unreachable!("resolve always returns a TaskCell"); }; - crate::turbo_tasks().drop_task_cell_content_hint(task, index); - Ok(()) + crate::turbo_tasks().drop_task_cell_content_hint(task, index) } /// Returns `true` if the reference is resolved, meaning the underlying [`RawVc`] uses the From 37f92a4bf415707019fff6697267fd9eddcd8a27 Mon Sep 17 00:00:00 2001 From: Luke Sandberg Date: Sun, 22 Nov 2026 10:43:02 -0800 Subject: [PATCH 2/2] Inline the collected task error message in gc_in_progress_reader Co-Authored-By: Claude Opus 5.5 --- .../turbo-tasks-backend/tests/gc_in_progress_reader.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/turbopack/crates/turbo-tasks-backend/tests/gc_in_progress_reader.rs b/turbopack/crates/turbo-tasks-backend/tests/gc_in_progress_reader.rs index 1854360421d3..7177c1c4941c 100644 --- a/turbopack/crates/turbo-tasks-backend/tests/gc_in_progress_reader.rs +++ b/turbopack/crates/turbo-tasks-backend/tests/gc_in_progress_reader.rs @@ -30,10 +30,6 @@ use crate::{ util::create_tt, }; -/// The message of the error a read of a collected task fails with (see -/// `collected_task_read_error` in the backend). -const COLLECTED_TASK_ERROR: &str = "no longer exists (it was garbage collected)"; - #[turbo_tasks::value(transparent, cell = "keyed")] struct Map(FxHashMap); @@ -164,8 +160,10 @@ async fn run_reader_across_owner_collection( fn assert_fails_with_collected_task_error(result: Result<()>) { let error = result.expect_err("the reader should fail"); let message = format!("{error:?}"); + // The error a read of a collected task fails with (see `collected_task_read_error` in the + // backend). assert!( - message.contains(COLLECTED_TASK_ERROR), + message.contains("no longer exists (it was garbage collected)"), "expected a collected task error, got: {message}" ); }