Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 39 additions & 13 deletions turbopack/crates/turbo-tasks-backend/src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1256,12 +1256,20 @@ impl TurboTasksBackend {
task_id: TaskId,
cell: CellId,
turbo_tasks: &TurboTasks<TurboTasksBackend>,
) {
) -> 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`
Expand All @@ -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(
Expand All @@ -1283,28 +1296,40 @@ impl TurboTasksBackend {
id: u32,
key_hashes: impl IntoIterator<Item = u64, IntoIter: Clone>,
turbo_tasks: &TurboTasks<TurboTasksBackend>,
) {
) -> 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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -4263,7 +4289,7 @@ impl Backend for TurboTasksBackend {
id: u32,
key_hashes: impl IntoIterator<Item = u64, IntoIter: Clone>,
turbo_tasks: &TurboTasks<Self>,
) {
) -> Result<()> {
self.refine_provisional_cell_dependency(task_id, cell, reader, id, key_hashes, turbo_tasks)
}

Expand All @@ -4281,7 +4307,7 @@ impl Backend for TurboTasksBackend {
task_id: TaskId,
cell: CellId,
turbo_tasks: &TurboTasks<Self>,
) {
) -> Result<()> {
self.drop_task_cell_content_hint(task_id, cell, turbo_tasks)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
193 changes: 193 additions & 0 deletions turbopack/crates/turbo-tasks-backend/tests/gc_in_progress_reader.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
#![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,
};

#[turbo_tasks::value(transparent, cell = "keyed")]
struct Map(FxHashMap<u32, u32>);

/// 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<Constant>) -> Result<Vc<Map>> {
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<Selector>,
constant: ResolvedVc<Constant>,
) -> Result<Vc<Map>> {
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<Gate> = LazyLock::new(Gate::new);
static DROP_HINT_GATE: LazyLock<Gate> = 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<Map>) -> Result<Vc<u32>> {
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<Map>) -> Result<Vc<()>> {
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<T: VcValueType>(
name: &str,
gate: &'static Gate,
reader: fn(ResolvedVc<Map>) -> OperationVc<T>,
) -> 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:?}");
// The error a read of a collected task fails with (see `collected_task_read_error` in the
// backend).
assert!(
message.contains("no longer exists (it was garbage collected)"),
"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);
}
13 changes: 9 additions & 4 deletions turbopack/crates/turbo-tasks/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -714,7 +717,7 @@ pub trait Backend: Sized + Sync + Send {
id: u32,
key_hashes: impl IntoIterator<Item = u64, IntoIter: Clone>,
turbo_tasks: &TurboTasks<Self>,
);
) -> Result<()>;

/// INVALIDATION: Be careful with this, it will not track dependencies, so
/// using it could break cache invalidation.
Expand All @@ -729,16 +732,18 @@ 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(
&self,
_task_id: TaskId,
_cell: CellId,
_turbo_tasks: &TurboTasks<Self>,
) {
) -> Result<()> {
Ok(())
}

/// INVALIDATION: Be careful with this, when reader is None, it will not track dependencies, so
Expand Down
Loading
Loading