Unverified Commit 9b963777 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbo-tasks-backend] Correctly maintain outdated_collectibles to prevent…

[turbo-tasks-backend] Correctly maintain outdated_collectibles to prevent unnecessary stale executions (#99386)

The outdated_collectibles collection was not correctly bootstrapped on
when starting task execution and was not leveraged when dirtying tasks

This could lead to extra 'dirty' calls that would actually make tasks
'stale' and lead to re-executions. On canary this generally means that
tasks that read collectibles at the top level can get reexecuted if they
change and they often do (output effects), but with this change we take
advantage of the 'stale vs dirty' optimization to avoid that in the
common case

Depends on #99249 otherwise the new test fails flakily

---------
Co-authored-by: 's avatarClaude Opus 5.5 (1M context) <noreply@anthropic.com>
parent 077ce297
...@@ -2112,6 +2112,10 @@ impl TurboTasksBackend { ...@@ -2112,6 +2112,10 @@ impl TurboTasksBackend {
let outdated_output_dependencies = task.iter_output_dependencies().collect(); let outdated_output_dependencies = task.iter_output_dependencies().collect();
task.set_outdated_output_dependencies(outdated_output_dependencies); task.set_outdated_output_dependencies(outdated_output_dependencies);
let outdated_collectibles_dependencies =
task.iter_collectibles_dependencies().collect();
task.set_outdated_collectibles_dependencies(outdated_collectibles_dependencies);
} }
} }
...@@ -2492,6 +2496,10 @@ impl TurboTasksBackend { ...@@ -2492,6 +2496,10 @@ impl TurboTasksBackend {
task.iter_outdated_output_dependencies() task.iter_outdated_output_dependencies()
.map(OutdatedEdge::OutputDependency), .map(OutdatedEdge::OutputDependency),
); );
old_edges.extend(
task.iter_outdated_collectibles_dependencies()
.map(OutdatedEdge::CollectiblesDependency),
);
} }
// Check if output need to be updated // Check if output need to be updated
...@@ -2940,9 +2948,7 @@ impl TurboTasksBackend { ...@@ -2940,9 +2948,7 @@ impl TurboTasksBackend {
} }
} }
// Clean up task storage after execution: // Free memory now that execution is complete.
// - Shrink collections marked with shrink_on_completion
// - Drop dependency fields for immutable tasks (they'll never re-execute)
task.cleanup_after_execution(); task.cleanup_after_execution();
drop(task); drop(task);
......
...@@ -43,11 +43,11 @@ use crate::{ ...@@ -43,11 +43,11 @@ use crate::{
operation::{ operation::{
ExecuteContext, TaskGuard, ExecuteContext, TaskGuard,
connect_child::resurrect_deleted, connect_child::resurrect_deleted,
invalidate::{make_task_dirty, try_make_task_dirty}, invalidate::{make_task_dirty_internal, try_make_task_dirty},
}, },
storage_schema::TaskStorageAccessors, storage_schema::TaskStorageAccessors,
}, },
data::{ActivenessState, AggregationNumber, CollectibleRef}, data::{ActivenessState, AggregationNumber, CollectibleRef, CollectiblesRef},
utils::swap_retain, utils::swap_retain,
}; };
...@@ -297,10 +297,11 @@ pub enum AggregationUpdateJob { ...@@ -297,10 +297,11 @@ pub enum AggregationUpdateJob {
/// The id references are weak by construction: a dependent that was itself collected is /// The id references are weak by construction: a dependent that was itself collected is
/// skipped. /// skipped.
InvalidateDueToDependencyTornDown { task_ids: TaskIdVec }, InvalidateDueToDependencyTornDown { task_ids: TaskIdVec },
/// Invalidates tasks that are dependent on a collectible type. /// Invalidates tasks that are dependent on a collectible type of `collectibles_task`.
InvalidateDueToCollectiblesChange { InvalidateDueToCollectiblesChange {
task_ids: TaskIdVec, task_ids: TaskIdVec,
#[cfg(feature = "task_dirty_cause")] /// The task whose (aggregated) collectibles changed, i.e. the task the dependents read.
collectibles_task: TaskId,
collectible_type: turbo_tasks::TraitTypeId, collectible_type: turbo_tasks::TraitTypeId,
}, },
/// Increases the active counter of the task /// Increases the active counter of the task
...@@ -601,7 +602,7 @@ impl AggregatedDataUpdate { ...@@ -601,7 +602,7 @@ impl AggregatedDataUpdate {
if !dependent.is_empty() { if !dependent.is_empty() {
queue.push(AggregationUpdateJob::InvalidateDueToCollectiblesChange { queue.push(AggregationUpdateJob::InvalidateDueToCollectiblesChange {
task_ids: dependent, task_ids: dependent,
#[cfg(feature = "task_dirty_cause")] collectibles_task: task.id(),
collectible_type: ty, collectible_type: ty,
}) })
} }
...@@ -1424,12 +1425,22 @@ impl AggregationUpdateQueue { ...@@ -1424,12 +1425,22 @@ impl AggregationUpdateQueue {
} }
AggregationUpdateJob::InvalidateDueToCollectiblesChange { AggregationUpdateJob::InvalidateDueToCollectiblesChange {
task_ids, task_ids,
#[cfg(feature = "task_dirty_cause")] collectibles_task,
collectible_type, collectible_type,
} => { } => {
let target = CollectiblesRef {
task: collectibles_task,
collectible_type,
};
for task_id in task_ids { for task_id in task_ids {
make_task_dirty( let mut task = ctx.task(task_id, TaskDataCategory::All);
task_id, // Like cell dependencies: if the dependency is outdated, the current
// execution hasn't read these collectibles yet and will see the new ones
// when it does, so it must be made dirty but not stale.
let make_stale = !task.outdated_collectibles_dependencies_contains(&target);
make_task_dirty_internal(
&mut task,
make_stale,
#[cfg(feature = "task_dirty_cause")] #[cfg(feature = "task_dirty_cause")]
TaskDirtyCause::CollectiblesChange { collectible_type }, TaskDirtyCause::CollectiblesChange { collectible_type },
self, self,
......
...@@ -225,7 +225,7 @@ fn cleanup_old_edges_inner( ...@@ -225,7 +225,7 @@ fn cleanup_old_edges_inner(
.collect(); .collect();
queue.push(AggregationUpdateJob::InvalidateDueToCollectiblesChange { queue.push(AggregationUpdateJob::InvalidateDueToCollectiblesChange {
task_ids, task_ids,
#[cfg(feature = "task_dirty_cause")] collectibles_task: task_id,
collectible_type: ty, collectible_type: ty,
}); });
} }
......
...@@ -35,24 +35,6 @@ pub fn invalidate( ...@@ -35,24 +35,6 @@ pub fn invalidate(
queue.execute(&mut ctx); queue.execute(&mut ctx);
} }
/// Marks a task dirty. The task must exist.
pub fn make_task_dirty(
task_id: TaskId,
#[cfg(feature = "task_dirty_cause")] cause: TaskDirtyCause,
queue: &mut AggregationUpdateQueue,
ctx: &mut impl ExecuteContext<'_>,
) {
let mut task = ctx.task(task_id, TaskDataCategory::All);
make_task_dirty_internal(
&mut task,
true,
#[cfg(feature = "task_dirty_cause")]
cause,
queue,
ctx,
);
}
/// Marks a task dirty, doing nothing if it no longer exists. /// Marks a task dirty, doing nothing if it no longer exists.
/// ///
/// Intended for invalidation usecases. /// Intended for invalidation usecases.
......
...@@ -1789,7 +1789,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors { ...@@ -1789,7 +1789,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
} else if let Some(task_type) = self.get_transient_task_type() { } else if let Some(task_type) = self.get_transient_task_type() {
TaskTypeRef::Transient(task_type) TaskTypeRef::Transient(task_type)
} else { } else {
panic!("Every task must have a task type {self:?}"); panic!("Every task must have a task type {self:#?}");
} }
} }
......
...@@ -62,7 +62,7 @@ impl UpdateCollectibleOperation { ...@@ -62,7 +62,7 @@ impl UpdateCollectibleOperation {
if !dependent.is_empty() { if !dependent.is_empty() {
queue.push(AggregationUpdateJob::InvalidateDueToCollectiblesChange { queue.push(AggregationUpdateJob::InvalidateDueToCollectiblesChange {
task_ids: dependent, task_ids: dependent,
#[cfg(feature = "task_dirty_cause")] collectibles_task: task_id,
collectible_type: ty, collectible_type: ty,
}) })
} }
......
...@@ -295,19 +295,19 @@ struct TaskStorageSchema { ...@@ -295,19 +295,19 @@ struct TaskStorageSchema {
collectibles_dependencies: AutoSet<CollectiblesRef, 3>, collectibles_dependencies: AutoSet<CollectiblesRef, 3>,
/// Outdated output dependencies to be cleaned up (transient). /// Outdated output dependencies to be cleaned up (transient).
#[field(storage = "auto_set", category = "transient", shrink_on_completion)] #[field(storage = "auto_set", category = "transient", drop_on_completion)]
outdated_output_dependencies: AutoSet<TaskId, 6>, outdated_output_dependencies: AutoSet<TaskId, 6>,
/// Outdated keyless cell dependencies to be cleaned up (transient). /// Outdated keyless cell dependencies to be cleaned up (transient).
#[field(storage = "auto_set", category = "transient", shrink_on_completion)] #[field(storage = "auto_set", category = "transient", drop_on_completion)]
outdated_cell_dependencies: AutoSet<CellRef, 3>, outdated_cell_dependencies: AutoSet<CellRef, 3>,
/// Outdated hashed cell dependencies to be cleaned up (transient). /// Outdated hashed cell dependencies to be cleaned up (transient).
#[field(storage = "auto_set", category = "transient", shrink_on_completion)] #[field(storage = "auto_set", category = "transient", drop_on_completion)]
outdated_cell_dependencies_hashed: AutoSet<(CellRef, u64), 1>, outdated_cell_dependencies_hashed: AutoSet<(CellRef, u64), 1>,
/// Outdated collectibles dependencies to be cleaned up (transient). /// Outdated collectibles dependencies to be cleaned up (transient).
#[field(storage = "auto_set", category = "transient", shrink_on_completion)] #[field(storage = "auto_set", category = "transient", drop_on_completion)]
outdated_collectibles_dependencies: AutoSet<CollectiblesRef, 3>, outdated_collectibles_dependencies: AutoSet<CollectiblesRef, 3>,
// ========================================================================= // =========================================================================
......
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
//! A strongly consistent collector must not be re-executed because of collectibles that change
//! while it is still waiting for its source to settle.
//!
//! Until the collector reads the collectibles again, its dependency on them is left over from the
//! previous execution. Collectibles emitted in the meantime will be seen when the read happens, so
//! they must make the collector dirty without making the running execution stale.
use std::sync::atomic::{AtomicUsize, Ordering};
use anyhow::Result;
use futures::future::try_join_all;
use turbo_rcstr::RcStr;
use turbo_tasks::{
CollectiblesSource, NonLocalValue, ReadRef, ResolvedVc, State, TransientInstance,
ValueToString, Vc, emit,
};
use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!();
#[turbo_tasks::value]
struct Input {
count: State<u32>,
}
#[turbo_tasks::value]
struct Thing(u32);
#[turbo_tasks::value_impl]
impl ValueToString for Thing {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell(format!("thing {}", self.0).into())
}
}
#[derive(NonLocalValue, Default)]
struct ExecutionCounter {
executions: AtomicUsize,
}
#[turbo_tasks::function]
async fn emit_one(i: u32) -> Result<Vc<()>> {
emit(ResolvedVc::upcast::<Box<dyn ValueToString>>(
Thing(i).resolved_cell(),
));
Ok(Vc::cell(()))
}
/// Emits `count` distinct collectibles, so changing `count` changes the collectible set.
#[turbo_tasks::function]
async fn emit_all(input: ResolvedVc<Input>) -> Result<Vc<()>> {
let count = *input.await?.count.get();
try_join_all((0..count).map(|i| emit_one(i).into_future())).await?;
Ok(Vc::cell(()))
}
#[turbo_tasks::function(operation, root)]
async fn source(input: ResolvedVc<Input>) -> Result<Vc<()>> {
emit_all(*input).await?;
Ok(Vc::cell(()))
}
#[turbo_tasks::function(operation, root)]
async fn collector(
input: ResolvedVc<Input>,
take: bool,
counter: TransientInstance<ExecutionCounter>,
) -> Result<Vc<u32>> {
counter.executions.fetch_add(1, Ordering::AcqRel);
// Depend on the input directly, so that a change re-executes the collector right away, while
// the source is still emitting.
let _ = *input.await?.count.get();
let source = source(input);
source.read_strongly_consistent().await?;
let collectibles = if take {
source.take_collectibles::<Box<dyn ValueToString>>()
} else {
source.peek_collectibles::<Box<dyn ValueToString>>()
};
Ok(Vc::cell(collectibles.len() as u32))
}
async fn executions_after_change(take: bool) -> Result<usize> {
let input = ReadRef::new_owned(Input {
count: State::new(5),
});
let input_vc = ReadRef::resolved_cell(input.clone());
let counter = TransientInstance::new(ExecutionCounter::default());
let collector = collector(input_vc, take, counter.clone());
assert_eq!(*collector.read_strongly_consistent().await?, 5);
let initial = counter.executions.load(Ordering::Acquire);
assert_eq!(initial, 1, "take={take}: initial executions");
input.count.set(200);
assert_eq!(*collector.read_strongly_consistent().await?, 200);
Ok(counter.executions.load(Ordering::Acquire) - initial)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn collector_is_not_re_executed_for_collectibles_it_has_not_read_yet() {
run_once(&REGISTRATION, async || {
for take in [false, true] {
assert_eq!(
executions_after_change(take).await?,
1,
"take={take}: executions after the input change"
);
}
anyhow::Ok(())
})
.await
.unwrap()
}
...@@ -66,6 +66,9 @@ struct FieldInfo { ...@@ -66,6 +66,9 @@ struct FieldInfo {
/// If true, shrink this collection after task execution completes. /// If true, shrink this collection after task execution completes.
/// Empty collections are removed entirely from the lazy vec. /// Empty collections are removed entirely from the lazy vec.
shrink_on_completion: bool, shrink_on_completion: bool,
/// If true, drop this collection after task execution completes. For transient bookkeeping
/// that is only meaningful while an execution is in progress.
drop_on_completion: bool,
/// If true, drop this field entirely after execution completes if the task is immutable. /// If true, drop this field entirely after execution completes if the task is immutable.
/// Immutable tasks don't re-execute, so dependency tracking fields are not needed. /// Immutable tasks don't re-execute, so dependency tracking fields are not needed.
drop_on_completion_if_immutable: bool, drop_on_completion_if_immutable: bool,
...@@ -451,6 +454,7 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo { ...@@ -451,6 +454,7 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo {
let mut filter_transient = false; let mut filter_transient = false;
let mut use_default = false; let mut use_default = false;
let mut shrink_on_completion = false; let mut shrink_on_completion = false;
let mut drop_on_completion = false;
let mut drop_on_completion_if_immutable = false; let mut drop_on_completion_if_immutable = false;
let mut custom_drop_partial = false; let mut custom_drop_partial = false;
let mut custom_mutators = false; let mut custom_mutators = false;
...@@ -573,6 +577,8 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo { ...@@ -573,6 +577,8 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo {
use_default = true; use_default = true;
} else if ident == "shrink_on_completion" { } else if ident == "shrink_on_completion" {
shrink_on_completion = true; shrink_on_completion = true;
} else if ident == "drop_on_completion" {
drop_on_completion = true;
} else if ident == "drop_on_completion_if_immutable" { } else if ident == "drop_on_completion_if_immutable" {
drop_on_completion_if_immutable = true; drop_on_completion_if_immutable = true;
} else if ident == "custom_drop_partial" { } else if ident == "custom_drop_partial" {
...@@ -585,8 +591,8 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo { ...@@ -585,8 +591,8 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo {
.error(format!( .error(format!(
"unknown modifier `{ident}`, expected `inline`, \ "unknown modifier `{ident}`, expected `inline`, \
`filter_transient`, `default`, `shrink_on_completion`, \ `filter_transient`, `default`, `shrink_on_completion`, \
`drop_on_completion_if_immutable`, `custom_drop_partial`, or \ `drop_on_completion`, `drop_on_completion_if_immutable`, \
`custom_mutators`" `custom_drop_partial`, or `custom_mutators`"
)) ))
.emit(); .emit();
} }
...@@ -670,6 +676,16 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo { ...@@ -670,6 +676,16 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo {
)) ))
.emit(); .emit();
} }
if drop_on_completion {
field_name
.span()
.unwrap()
.error(format!(
"`drop_on_completion` on field `{field_name}` has no effect: only collection \
types (auto_set, auto_map, counter_map) support clearing"
))
.emit();
}
if inline && drop_on_completion_if_immutable { if inline && drop_on_completion_if_immutable {
field_name field_name
.span() .span()
...@@ -683,6 +699,17 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo { ...@@ -683,6 +699,17 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo {
} }
} }
if drop_on_completion && (shrink_on_completion || drop_on_completion_if_immutable) {
field_name
.span()
.unwrap()
.error(format!(
"`drop_on_completion` on field `{field_name}` already empties it; remove \
`shrink_on_completion` / `drop_on_completion_if_immutable`"
))
.emit();
}
if custom_drop_partial { if custom_drop_partial {
if inline { if inline {
field_name field_name
...@@ -738,6 +765,7 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo { ...@@ -738,6 +765,7 @@ fn parse_field_storage_attributes(field: &syn::Field) -> FieldInfo {
filter_transient, filter_transient,
use_default, use_default,
shrink_on_completion, shrink_on_completion,
drop_on_completion,
drop_on_completion_if_immutable, drop_on_completion_if_immutable,
custom_drop_partial, custom_drop_partial,
as_type, as_type,
...@@ -2920,10 +2948,12 @@ fn generate_automap_ops(field: &FieldInfo) -> TokenStream { ...@@ -2920,10 +2948,12 @@ fn generate_automap_ops(field: &FieldInfo) -> TokenStream {
/// ///
/// This method: /// This method:
/// 1. Queries `self.typed().flags.immutable()` once /// 1. Queries `self.typed().flags.immutable()` once
/// 2. Shrinks any inline collection fields with `shrink_on_completion` /// 2. Shrinks any inline collection fields with `shrink_on_completion` and drops any with
/// `drop_on_completion`
/// 3. Uses swap_retain pattern to process all lazy fields in one pass /// 3. Uses swap_retain pattern to process all lazy fields in one pass
/// 4. For fields with `shrink_on_completion`: shrink or remove if empty /// 4. For fields with `shrink_on_completion`: shrink or remove if empty
/// 5. For fields with `drop_on_completion_if_immutable` when task is immutable: remove /// 5. For fields with `drop_on_completion`: remove
/// 6. For fields with `drop_on_completion_if_immutable` when task is immutable: remove
fn generate_cleanup_after_execution(grouped_fields: &GroupedFields) -> TokenStream { fn generate_cleanup_after_execution(grouped_fields: &GroupedFields) -> TokenStream {
// Generate cleanup calls for inline collection fields. // Generate cleanup calls for inline collection fields.
// Invalid attribute combinations (e.g. shrink/drop on non-collection fields) are rejected // Invalid attribute combinations (e.g. shrink/drop on non-collection fields) are rejected
...@@ -2934,7 +2964,11 @@ fn generate_cleanup_after_execution(grouped_fields: &GroupedFields) -> TokenStre ...@@ -2934,7 +2964,11 @@ fn generate_cleanup_after_execution(grouped_fields: &GroupedFields) -> TokenStre
continue; continue;
} }
let field_name = &field.field_name; let field_name = &field.field_name;
if field.drop_on_completion_if_immutable { if field.drop_on_completion {
inline_cleanups.push(quote! {
typed.#field_name = Default::default();
});
} else if field.drop_on_completion_if_immutable {
inline_cleanups.push(quote! { inline_cleanups.push(quote! {
if is_immutable { if is_immutable {
typed.#field_name = Default::default(); typed.#field_name = Default::default();
...@@ -2963,6 +2997,12 @@ fn generate_cleanup_after_execution(grouped_fields: &GroupedFields) -> TokenStre ...@@ -2963,6 +2997,12 @@ fn generate_cleanup_after_execution(grouped_fields: &GroupedFields) -> TokenStre
let shrink = field.shrink_on_completion; let shrink = field.shrink_on_completion;
let drop_if_immutable = field.drop_on_completion_if_immutable; let drop_if_immutable = field.drop_on_completion_if_immutable;
if field.drop_on_completion {
match_arms.push(quote! {
LazyField::#variant_name(_) => false,
});
continue;
}
if !shrink && !drop_if_immutable { if !shrink && !drop_if_immutable {
continue; continue;
} }
...@@ -3014,6 +3054,7 @@ fn generate_cleanup_after_execution(grouped_fields: &GroupedFields) -> TokenStre ...@@ -3014,6 +3054,7 @@ fn generate_cleanup_after_execution(grouped_fields: &GroupedFields) -> TokenStre
#[doc = ""] #[doc = ""]
#[doc = "This method performs a single pass over lazy fields to:"] #[doc = "This method performs a single pass over lazy fields to:"]
#[doc = "- Shrink collections marked with `shrink_on_completion`"] #[doc = "- Shrink collections marked with `shrink_on_completion`"]
#[doc = "- Remove collections marked with `drop_on_completion`"]
#[doc = "- Remove empty collections"] #[doc = "- Remove empty collections"]
#[doc = "- Drop fields marked with `drop_on_completion_if_immutable` for immutable tasks"] #[doc = "- Drop fields marked with `drop_on_completion_if_immutable` for immutable tasks"]
#[doc = ""] #[doc = ""]
......
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