Unverified Commit fea76de6 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

turbo-tasks-gc: tear down reverse edges when collecting a task (#99145)

When deleting a task, remove the reverse dependeny edges also. Generally
this should be empty, but there can be tasks if those tasks are owned by
a root that is pinned but not active. So in the rare case that such
tasks are 'reactivated' this also dirties the task.

This closes a hole where a task with a cell_dependency can reference a
deleted task. Then new test demonstrates the bug, without the fix it
will panic when collecting the second task
parent 10c5a6ac
......@@ -31,8 +31,8 @@ use crate::{
backend::{
AnyOperation, TurboTasksBackend,
operation::{
AggregationUpdateQueue, CleanupOldEdgesOperation, ExecuteContext, ExecuteContextImpl,
TaskGuard, capture_all_outgoing_edges,
AggregationUpdateJob, AggregationUpdateQueue, CleanupOldEdgesOperation, ExecuteContext,
ExecuteContextImpl, TaskGuard, capture_all_edges,
},
snapshot_coordinator::SnapshotPhase,
storage::{SpecificTaskDataCategory, TaskDataCategory},
......@@ -129,6 +129,9 @@ pub struct GcPassResult {
deleted_roots: Vec<TaskId>,
/// Aggregation rebalance requests that were deferred from the main GC loop.
deferred_balance_edges: FxHashSet<(TaskId, TaskId)>,
/// Dependents of collected tasks whose forward edge was scrubbed, deferred from the main GC
/// loop. Dirtying propagates through the aggregation graph, so it must not race the cascade.
deferred_dirty_dependents: FxHashSet<TaskId>,
/// The gc loop was interrupted by competing work.
pub interrupted: bool,
}
......@@ -176,6 +179,15 @@ impl GcPassResult {
}
self.deferred_balance_edges
.extend(other.deferred_balance_edges);
// merge into the larger set and keep that one
if other.deferred_dirty_dependents.len() > self.deferred_dirty_dependents.len() {
std::mem::swap(
&mut self.deferred_dirty_dependents,
&mut other.deferred_dirty_dependents,
);
}
self.deferred_dirty_dependents
.extend(other.deferred_dirty_dependents);
self.interrupted |= other.interrupted;
self
}
......@@ -251,7 +263,7 @@ impl TurboTasksBackend {
};
let collector = |child_id| spawner.spawn(GcJob::Collect(child_id));
let mut ctx = ExecuteContextImpl::new_for_gc(self, turbo_tasks, phase, &collector);
// `All` restores Data so `capture_all_outgoing_edges` below can read the
// `All` restores Data so `capture_all_edges` below can read the
// Data-category dependency sets. The recheck itself only needs Meta.
let mut task = ctx.task(task_id, TaskDataCategory::All);
// Recheck under the guard: the shard scan saw this task without holding it, and a
......@@ -261,7 +273,7 @@ impl TurboTasksBackend {
return ControlFlow::Continue(());
}
let old_edges = capture_all_outgoing_edges(&task);
let old_edges = capture_all_edges(&task);
// Clear `immutable` defensively so `resurrect_deleted` can mark the task dirty if
// it needs to
task.set_immutable(false);
......@@ -287,9 +299,12 @@ impl TurboTasksBackend {
// Delete outgoing edges but don't update the aggregation graph yet.
// To avoid accidentally rebalancing on deleted tasks due to racing deletions,
// we defer all rebalancing to the end
result.deferred_balance_edges.extend(
CleanupOldEdgesOperation::run_edge_deletions_only(task_id, old_edges, &mut ctx),
);
let deferred =
CleanupOldEdgesOperation::run_edge_deletions_only(task_id, old_edges, &mut ctx);
result.deferred_balance_edges.extend(deferred.balance_edges);
result
.deferred_dirty_dependents
.extend(deferred.dirty_dependents);
ControlFlow::Continue(())
},
|(stats, result), (other_stats, other_result)| {
......@@ -313,6 +328,21 @@ impl TurboTasksBackend {
while !queue.process(&mut ctx) {}
}
// Dirty the dependents whose edges were scrubbed. After the rebalance above so the
// aggregation graph is settled, and before the root scan below because dirtying can change
// activeness and therefore rootness.
let dirty_dependents = std::mem::take(&mut result.deferred_dirty_dependents);
if !dirty_dependents.is_empty() {
let noop_collector = |_task_id| {};
let mut ctx = ExecuteContextImpl::new_for_gc(self, turbo_tasks, phase, &noop_collector);
let mut queue = AggregationUpdateQueue::new();
// A dependent collected by this same pass is skipped: the job is weak by construction.
queue.push(AggregationUpdateJob::InvalidateDueToDependencyTornDown {
task_ids: dirty_dependents.into_iter().collect(),
});
while !queue.process(&mut ctx) {}
}
// Collect all active roots
// We don't do this in the GC pass because a task detected as a root 'early' might become a
// non-root later due to other operations (e.g. it might get promoted to a live aggregation
......
......@@ -68,7 +68,7 @@ use crate::{
AggregationUpdateJob, AggregationUpdateQueue, ChildExecuteContext,
CleanupOldEdgesOperation, ConnectChildOperation, ExecuteContext, ExecuteContextImpl,
LeafDistanceUpdateQueue, Operation, OutdatedEdge, TaskGuard, TaskType, TaskTypeRef,
capture_all_outgoing_edges, connect_children, get_aggregation_number, get_uppers,
capture_all_edges, connect_children, get_aggregation_number, get_uppers,
make_task_dirty_internal, prepare_new_children,
},
snapshot_coordinator::{OperationGuard, SnapshotCoordinator},
......@@ -3442,7 +3442,7 @@ impl TurboTasksBackend {
activeness_state.all_clean_event.notify(usize::MAX);
}
// Remove all the outgoing edges of this task.
let old_edges = capture_all_outgoing_edges(&task);
let old_edges = capture_all_edges(&task);
drop(task);
if !old_edges.is_empty() {
......
......@@ -42,8 +42,9 @@ use crate::{
backend::{
TaskDataCategory,
operation::{
ExecuteContext, Operation, TaskGuard, connect_child::resurrect_deleted,
invalidate::make_task_dirty,
ExecuteContext, Operation, TaskGuard,
connect_child::resurrect_deleted,
invalidate::{make_task_dirty, try_make_task_dirty},
},
storage_schema::TaskStorageAccessors,
},
......@@ -306,6 +307,11 @@ pub enum AggregationUpdateJob {
},
/// Notifies an upper task about changed data from an inner task.
AggregatedDataUpdate(Box<AggregatedDataUpdateJob>),
/// Mark these tasks dirty because they have a dependency on a task being deleted by GC.
///
/// The id references are weak by construction: a dependent that was itself collected is
/// skipped.
InvalidateDueToDependencyTornDown { task_ids: TaskIdVec },
/// Invalidates tasks that are dependent on a collectible type.
InvalidateDueToCollectiblesChange {
task_ids: TaskIdVec,
......@@ -1535,6 +1541,18 @@ impl AggregationUpdateQueue {
}
self.aggregated_data_update(upper_ids, ctx, update);
}
AggregationUpdateJob::InvalidateDueToDependencyTornDown { task_ids } => {
for task_id in task_ids {
// `try_*`: the dependent may itself have been collected in this cascade.
try_make_task_dirty(
task_id,
#[cfg(feature = "task_dirty_cause")]
TaskDirtyCause::DependencyTornDown,
self,
ctx,
);
}
}
AggregationUpdateJob::InvalidateDueToCollectiblesChange {
task_ids,
#[cfg(feature = "task_dirty_cause")]
......
......@@ -109,7 +109,7 @@ pub fn make_task_dirty(
/// Marks a task dirty, doing nothing if it no longer exists.
///
/// Intended for invalidation usecases.
fn try_make_task_dirty(
pub fn try_make_task_dirty(
task_id: TaskId,
#[cfg(feature = "task_dirty_cause")] cause: TaskDirtyCause,
queue: &mut AggregationUpdateQueue,
......
......@@ -191,11 +191,6 @@ pub trait ExecuteContext<'e>: Sized {
///
/// Only effective in a gc context see [`Self::collects_gc_candidates`].
fn note_maybe_collectible(&mut self, task: &impl TaskGuard);
/// Whether [`Self::note_maybe_collectible`] does anything, i.e. this is a GC context.
///
/// Lets a caller skip work that only exists to feed the collector — in particular opening a
/// task with a wider [`TaskDataCategory`] than it would otherwise need.
fn collects_gc_candidates(&self) -> bool;
fn should_track_dependencies(&self) -> bool;
fn should_track_activeness(&self) -> bool;
fn turbo_tasks(&self) -> Arc<dyn TurboTasksCallApi>;
......@@ -1383,11 +1378,6 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
collector(task.id());
}
}
fn collects_gc_candidates(&self) -> bool {
matches!(self.phase, ExecutePhase::Gc(_))
}
fn should_track_dependencies(&self) -> bool {
self.backend.should_track_dependencies()
}
......@@ -2099,7 +2089,7 @@ pub use self::{
AggregatedDataUpdate, AggregationUpdateJob, get_aggregation_number, get_uppers,
is_aggregating_node, is_root_node,
},
cleanup_old_edges::{OutdatedEdge, capture_all_outgoing_edges},
cleanup_old_edges::{OutdatedEdge, capture_all_edges},
connect_children::connect_children,
invalidate::make_task_dirty_internal,
prepare_new_children::prepare_new_children,
......
......@@ -15,11 +15,11 @@ use std::{
};
use anyhow::Result;
use turbo_tasks::{GcRoot, TurboTasks, Vc};
use turbo_tasks::{GcRoot, ResolvedVc, TurboTasks, Vc};
use turbo_tasks_backend::TurboTasksBackend;
use crate::{
gc_fixture::{create_constant, diamond_root_op},
gc_fixture::{Constant, Selector, create_constant, create_selector, diamond_root_op},
util::{create_persistence_dir, reopen_tt_with_gc, reopen_tt_with_gc_ttl},
};
......@@ -219,3 +219,135 @@ async fn gc_collect_scrubs_disk_only_forward_dep_target() {
result.unwrap();
}
}
// Regression test for a bug where a second cell reader owned by a different root task would panic
// when the root eventually ages out.
//
// This test merely asserts that such dependencies don't cause panics.
//
// `shared_target` is *called* by the owning side only, so that side is its sole parent.
// `borrowing_root` receives the target already resolved and only reads it through `shared_reader`:
// a forward cell-dependency, no child edge. So the target's `cell_dependents` holds reader 2 while
// its `parent_count` comes entirely from the owning side.
//
// Session 1 flips a selector to drop the owning side cleanly -- no invalidation, so the target
// keeps its edges -- and collects it. The shared target cascades with it, because
// `cell_dependents` do not keep a task alive (the documented `gc_collectible` heuristic). Reader 2
// survives under the pinned borrowing root holding a forward dependency on a task that is now
// gone, and that state is persisted.
//
// Session 2 ages the borrowing root out. Tearing down reader 2 scrubs its forward dependency on
// the target collected back in session 1: a `MustExist` open of an already-collected task. The
// session does not need to execute anything -- the tasks only have to exist on disk for GC to
// reach them.
#[turbo_tasks::function]
async fn shared_target(constant: ResolvedVc<Constant>) -> Result<Vc<u32>> {
Ok(Vc::cell(*constant.await?.get() + 41))
}
/// Reads the shared target via an already-resolved `Vc`: a forward cell-dependency, no child edge.
#[turbo_tasks::function]
async fn shared_reader(target: ResolvedVc<u32>, n: u32) -> Result<Vc<u32>> {
Ok(Vc::cell(n + *target.await?))
}
/// Calls the shared target -- becoming its only parent -- and reads it through reader 1.
#[turbo_tasks::function]
async fn owning_subtree(constant: ResolvedVc<Constant>) -> Result<Vc<u32>> {
let target = shared_target(*constant).to_resolved().await?;
assert_eq!(*shared_reader(*target, 1).await?, 42);
// Return the target's own `Vc`, so a caller that resolves this reaches `shared_target`.
Ok(*target)
}
/// Selector-gated root over [`owning_subtree`]: flipping the selector to `true` drops the owning
/// subtree cleanly, without invalidating it, so it keeps its edges and becomes collectible.
#[turbo_tasks::function(operation, root)]
async fn select_owning(
selector: ResolvedVc<Selector>,
constant: ResolvedVc<Constant>,
) -> Result<Vc<u32>> {
// Pass the subtree's `Vc` through unchanged rather than re-celling it, so resolving this op
// names `shared_target` itself -- that is the task the borrowing side must depend on.
if !*selector.await?.get() {
Ok(owning_subtree(*constant))
} else {
Ok(Vc::cell(0))
}
}
/// Reaches reader 2 through an **already-resolved** target, so it never calls the target and never
/// becomes its parent. Reader 2 keeps its forward cell-dependency on the target after the owning
/// subtree -- the target's only parent -- is collected.
#[turbo_tasks::function(operation, root)]
async fn borrowing_root(target: ResolvedVc<u32>) -> Result<Vc<u32>> {
Ok(Vc::cell(*shared_reader(*target, 2).await?))
}
/// A surviving task must not be left holding a forward cell-dependency on a collected task.
///
/// Two readers share a cell target, but only one side *owns* it (is its parent). The owning side is
/// collected while the borrowing root is still pinned, so the target is destroyed with reader 2
/// still depending on it -- and reader 2 is only torn down in the next session.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn shared_cell_target_collected_before_its_second_reader() {
let dir = create_persistence_dir("shared_cell_target_collected_before_its_second_reader");
// Session 1: build both sides over one shared target, drop the owning side, and collect it.
// That leaves reader 2 holding a dependency on the collected target, and persists it.
{
let tt = reopen_tt_with_gc(&dir);
let borrowing_op = turbo_tasks::run_once(tt.clone(), async move {
let selector_op = create_selector(false);
let selector_vc = selector_op.resolve().strongly_consistent().await?;
let selector = selector_op.read_strongly_consistent().await?;
let constant_op = create_constant();
let constant_vc = constant_op.resolve().strongly_consistent().await?;
// The owning side parents the target and hands it back.
let owning = select_owning(selector_vc, constant_vc);
let target = owning.resolve().strongly_consistent().await?;
assert_eq!(*target.await?, 41);
let borrowing = borrowing_root(target);
assert_eq!(*borrowing.read_strongly_consistent().await?, 43);
// Drop the owning subtree cleanly: no invalidation, so the target keeps its edges.
selector.set(true);
assert_eq!(*owning.read_strongly_consistent().await?, 0);
anyhow::Ok(borrowing)
})
.await
.unwrap();
// Pin the borrowing root so only the owning side is collectible.
let borrowing_pin = GcRoot::pin(tt.clone(), borrowing_op);
let collected = gc_until_collected(&tt, 3).await;
assert!(
collected >= 3,
"the owning subtree, reader 1 and the shared target should be collected (got {collected})"
);
tt.backend().snapshot_and_evict_for_testing(&tt);
drop(borrowing_pin);
tt.stop_and_wait().await;
}
// Session 2: nothing is pinned, so the borrowing root ages out. Tearing down reader 2 scrubs
// its forward dependency on the target collected in session 1 -- the dangling half-edge.
// Surviving these passes without a panic is the assertion.
{
let tt = reopen_tt_with_gc_ttl(&dir, Duration::ZERO);
let tt2 = tt.clone();
turbo_tasks::run_once(tt.clone(), async move {
gc_until_collected(&tt2, 2).await;
anyhow::Ok(())
})
.await
.unwrap();
tt.stop_and_wait().await;
}
}
......@@ -964,6 +964,28 @@ impl<B: Backend + 'static> TurboTasks<B> {
self.schedule(id, TaskPriority::initial());
}
/// Runs `future` as a top-level task and returns its result.
///
/// # Returned values must not contain `Vc` or `ResolvedVc` or if they do they should be covered by a pin
///
/// `T` is deliberately unconstrained for ergonomics, but a `Vc`/`ResolvedVc` that escapes this
/// call is **not** protected against garbage collection. It can be collected, and
/// dereferencing the stale handle then fails.
/// ///
/// To hand a computation out of a top-level task, return the [`OperationVc`] and pin it:
///
/// ```ignore
/// let (resolved, op) = tt.run_once(async move {
/// let op = my_operation(args);
/// let resolved = op.resolve().strongly_consistent().await?;
/// // Return the operation too, so it can be pinned below.
/// Ok((resolved, op))
/// }).await?;
/// let _gc_root = GcRoot::pin(tt.clone(), op); // unpins on drop
/// ```
///
/// Returning owned data -- [`ReadRef`](crate::ReadRef), `RcStr`, plain values -- is always
/// fine.
pub async fn run_once<T: Send + 'static>(
&self,
future: impl Future<Output = Result<T>> + Send + 'static,
......@@ -980,6 +1002,11 @@ impl<B: Backend + 'static> TurboTasks<B> {
rx.await?
}
/// Runs `future` as a top-level task and returns its result.
///
/// The same constraint as [`run_once`](Self::run_once) applies to `T`: a `Vc`/`ResolvedVc`
/// returned from here is not anchored against garbage collection. See that method's docs for
/// why, and for the pin-the-`OperationVc` idiom.
#[tracing::instrument(level = "trace", skip_all, name = "turbo_tasks::run")]
pub async fn run<T: Send + 'static>(
&self,
......
......@@ -24,6 +24,9 @@ pub enum TaskDirtyCause {
/// Re-dirtied because a GC-soft-deleted task was resurrected by a new connection before its
/// hard-delete: its edges were scrubbed, so it must re-execute to rebuild them.
Resurrected,
/// Dirtied because a task this one depended on was torn down: the value this task's result was
/// derived from no longer exists, so the result cannot be trusted.
DependencyTornDown,
Unknown,
}
......@@ -87,6 +90,7 @@ impl std::fmt::Display for TaskDirtyCause {
}
TaskDirtyCause::Invalidator => write!(f, "invalidator"),
TaskDirtyCause::Resurrected => write!(f, "resurrected"),
TaskDirtyCause::DependencyTornDown => write!(f, "dependency torn down"),
TaskDirtyCause::Unknown => write!(f, "unknown"),
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment