Unverified Commit 0fd2df41 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

turbo-tasks: unify keyed cell dependencies

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent b3a13b48
......@@ -34,10 +34,10 @@ use tokio::time::{Duration, Instant};
use tracing::{Span, field::display, trace_span};
use turbo_bincode::TurboBincodeBuffer;
use turbo_tasks::{
CellId, DynTaskInputsStorage, RawVc, RawVcUnpacked, ReadCellOptions, ReadCellTracking,
CellId, CellKey, DynTaskInputsStorage, RawVc, RawVcUnpacked, ReadCellOptions, ReadCellTracking,
ReadConsistency, ReadOutcome, ReadOutputOptions, ReadTracking, SharedReference,
TRANSIENT_TASK_BIT, TaskExecutionReason, TaskId, TaskPersistence, TaskPriority, TrackKey,
TraitTypeId, TurboTasks, TurboTasksCallApi, TurboTasksPanic, ValueTypeId,
TRANSIENT_TASK_BIT, TaskExecutionReason, TaskId, TaskPersistence, TaskPriority, TraitTypeId,
TurboTasks, TurboTasksCallApi, TurboTasksPanic, ValueTypeId,
backend::{
Backend, CachedTaskType, CachedTaskTypeArc, CellContent, CellHash, TaskCollectiblesMap,
TaskExecutionSpec, TransientTaskType, TurboTaskContextError, TurboTaskLocalContextError,
......@@ -1052,20 +1052,17 @@ impl TurboTasksBackend {
reader: Option<TaskId>,
reader_task: Option<TaskGuard<'_>>,
cell: CellId,
key: TrackKey,
key: Option<CellKey>,
) {
if let Some(mut reader_task) = reader_task {
let reader = reader.unwrap();
let reverse = CellRef { task: reader, cell };
match key {
TrackKey::None => {
None => {
let _ = task.add_cell_dependents(reverse);
}
TrackKey::Key(k) => {
let _ = task.add_cell_dependents_hashed((reverse, k));
}
TrackKey::Keyed(id) => {
let _ = task.add_cell_dependents_keyed((reverse, id));
Some(key) => {
let _ = task.add_cell_dependents_keyed((reverse, key));
}
}
drop(task);
......@@ -1080,19 +1077,14 @@ impl TurboTasksBackend {
cell,
};
match key {
TrackKey::None => {
None => {
if !reader_task.remove_outdated_cell_dependencies(&target) {
let _ = reader_task.add_cell_dependencies(target);
}
}
TrackKey::Key(k) => {
if !reader_task.remove_outdated_cell_dependencies_hashed(&(target, k)) {
let _ = reader_task.add_cell_dependencies_hashed((target, k));
}
}
TrackKey::Keyed(id) => {
if !reader_task.remove_outdated_cell_dependencies_keyed(&(target, id)) {
let _ = reader_task.add_cell_dependencies_keyed((target, id));
Some(key) => {
if !reader_task.remove_outdated_cell_dependencies_keyed(&(target, key)) {
let _ = reader_task.add_cell_dependencies_keyed((target, key));
}
}
}
......@@ -1205,13 +1197,13 @@ impl TurboTasksBackend {
Ok(ReadOutcome::Scheduled(listener))
}
/// Replaces the [`TrackKey::Keyed`] dependency of `reader` on `cell` of `task_id` (created by a
/// `Vc::keyed()` read) with [`TrackKey::Key`] dependencies on `key_hashes`.
/// Replaces the [`CellKey::Keyed`] dependency of `reader` on `cell` of `task_id` (created by a
/// `Vc::keyed()` read) with [`CellKey::Hash`] dependencies on `key_hashes`.
///
/// When the cell content is currently missing, the [`TrackKey::Keyed`] dependency is kept
/// When the cell content is currently missing, the [`CellKey::Keyed`] dependency is kept
/// (conservatively depending on the whole cell). That covers a concurrent `update_cell`
/// invalidation: it removes the cell content before it invalidates the dependents it collected
/// earlier, and it would skip a [`TrackKey::Keyed`] dependency that was removed in between,
/// earlier, and it would skip a [`CellKey::Keyed`] dependency that was removed in between,
/// without seeing the hashed dependencies that replaced it.
fn convert_keyed_cell_dependency(
&self,
......@@ -1236,17 +1228,64 @@ impl TurboTasksBackend {
task: task_id,
cell,
};
task.remove_cell_dependents_keyed(&(reverse, id));
reader_task.remove_cell_dependencies_keyed(&(target, id));
reader_task.remove_outdated_cell_dependencies_keyed(&(target, id));
let keyed = CellKey::Keyed(id);
task.remove_cell_dependents_keyed(&(reverse, keyed));
reader_task.remove_cell_dependencies_keyed(&(target, keyed));
reader_task.remove_outdated_cell_dependencies_keyed(&(target, keyed));
// Immutable tasks never need dependency edges and can never be invalidated.
if immutable {
return;
}
for k in key_hashes {
let _ = task.add_cell_dependents_hashed((reverse, k));
if !reader_task.remove_outdated_cell_dependencies_hashed(&(target, k)) {
let _ = reader_task.add_cell_dependencies_hashed((target, k));
let key = CellKey::Hash(k);
let _ = task.add_cell_dependents_keyed((reverse, key));
if !reader_task.remove_outdated_cell_dependencies_keyed(&(target, key)) {
let _ = reader_task.add_cell_dependencies_keyed((target, key));
}
}
}
/// Converts all [`CellKey::Keyed`] dependencies of `reader` that are still present (their
/// `KeyedReadRef` wasn't dropped within the execution) into normal (full) cell dependencies.
/// Called when an execution of `reader` that made `Vc::keyed()` reads completes, as the ids are
/// only meaningful within that execution.
///
/// A concurrent `update_cell` that collected the [`CellKey::Keyed`] dependent before the
/// conversion still invalidates `reader`, as it also accepts a full dependency on the cell when
/// it re-checks a [`CellKey::Keyed`] dependent.
fn convert_remaining_keyed_cell_dependencies(
&self,
ctx: &mut ExecuteContext<'_>,
reader: TaskId,
) {
let remaining: SmallVec<[(CellRef, CellKey); 4]> = ctx
.task(reader, TaskDataCategory::Data)
.iter_cell_dependencies_keyed()
.filter(|(_, key)| matches!(key, CellKey::Keyed(_)))
.collect();
for (target, key) in remaining {
let reverse = CellRef {
task: reader,
cell: target.cell,
};
if target.task == reader {
// Not expected (reads of own cells aren't tracked), but don't leave it behind.
let mut reader_task = ctx.task(reader, TaskDataCategory::All);
reader_task.remove_cell_dependencies_keyed(&(target, key));
reader_task.remove_cell_dependents_keyed(&(reverse, key));
continue;
}
let (mut task, mut reader_task) =
ctx.task_pair(target.task, reader, TaskDataCategory::All);
task.remove_cell_dependents_keyed(&(reverse, key));
reader_task.remove_cell_dependencies_keyed(&(target, key));
// Immutable tasks never need dependency edges and can never be invalidated.
if task.immutable() && !cfg!(feature = "verify_immutable") {
continue;
}
let _ = task.add_cell_dependents(reverse);
if !reader_task.remove_outdated_cell_dependencies(&target) {
let _ = reader_task.add_cell_dependencies(target);
}
}
}
......@@ -2208,8 +2247,6 @@ impl TurboTasksBackend {
// dependency registration work if we re-read them
let cell_dependencies = task.iter_cell_dependencies().collect();
task.set_outdated_cell_dependencies(cell_dependencies);
let cell_dependencies_hashed = task.iter_cell_dependencies_hashed().collect();
task.set_outdated_cell_dependencies_hashed(cell_dependencies_hashed);
let cell_dependencies_keyed = task.iter_cell_dependencies_keyed().collect();
task.set_outdated_cell_dependencies_keyed(cell_dependencies_keyed);
......@@ -2265,6 +2302,7 @@ impl TurboTasksBackend {
task_id: TaskId,
result: Result<RawVc, TurboTasksExecutionError>,
cell_counters: &AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>,
has_keyed_reads: bool,
#[cfg(feature = "verify_determinism")] stateful: bool,
has_invalidator: bool,
turbo_tasks: &TurboTasks<TurboTasksBackend>,
......@@ -2310,6 +2348,21 @@ impl TurboTasksBackend {
let mut ctx = self.execute_context(turbo_tasks);
// `CellKey::Keyed` ids are only meaningful within this execution, so convert the remaining
// ones to normal dependencies first, before the outdated edges are cleaned up.
if has_keyed_reads && self.should_track_dependencies() {
self.convert_remaining_keyed_cell_dependencies(&mut ctx, task_id);
}
// Only checked for executions with `keyed()` reads, so other tasks don't pay for it.
debug_assert!(
!has_keyed_reads
|| !ctx
.task(task_id, TaskDataCategory::Data)
.iter_cell_dependencies_keyed()
.any(|(_, key)| matches!(key, CellKey::Keyed(_))),
"`CellKey::Keyed` dependencies must be converted when the execution completes"
);
let TaskExecutionCompletePrepareResult {
new_children,
is_now_immutable,
......@@ -2547,7 +2600,6 @@ impl TurboTasksBackend {
// Collect all dependencies on tasks to check if all dependencies are immutable.
task.iter_output_dependencies()
.chain(task.iter_cell_dependencies().map(|r| r.task))
.chain(task.iter_cell_dependencies_hashed().map(|(r, _)| r.task))
.chain(task.iter_cell_dependencies_keyed().map(|(r, _)| r.task))
.collect::<FxHashSet<_>>(),
)
......@@ -2591,20 +2643,12 @@ impl TurboTasksBackend {
cell,
}
}));
old_edges.extend(
task.iter_outdated_cell_dependencies_hashed()
.map(|(cell, key)| OutdatedEdge::HashedCellDependency {
dependent: task_id,
cell,
key,
}),
);
old_edges.extend(
task.iter_outdated_cell_dependencies_keyed()
.map(|(cell, id)| OutdatedEdge::KeyedCellDependency {
.map(|(cell, key)| OutdatedEdge::KeyedCellDependency {
dependent: task_id,
cell,
id,
key,
}),
);
old_edges.extend(task.iter_outdated_output_dependencies().map(|output_task| {
......@@ -3975,6 +4019,7 @@ impl Backend for TurboTasksBackend {
task_id: TaskId,
result: Result<RawVc, TurboTasksExecutionError>,
cell_counters: &AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>,
has_keyed_reads: bool,
#[cfg(feature = "verify_determinism")] stateful: bool,
has_invalidator: bool,
turbo_tasks: &TurboTasks<Self>,
......@@ -3983,6 +4028,7 @@ impl Backend for TurboTasksBackend {
task_id,
result,
cell_counters,
has_keyed_reads,
#[cfg(feature = "verify_determinism")]
stateful,
has_invalidator,
......
......@@ -3,7 +3,7 @@ use std::mem::take;
use rustc_hash::FxHashSet;
use smallvec::SmallVec;
use turbo_tasks::TaskId;
use turbo_tasks::{CellKey, TaskId};
use crate::{
backend::{
......@@ -29,16 +29,11 @@ pub enum OutdatedEdge {
dependent: TaskId,
cell: CellRef,
},
HashedCellDependency {
dependent: TaskId,
cell: CellRef,
key: u64,
},
/// A `Vc::keyed()` read dependency (`TrackKey::Keyed(id)`).
/// `dependent` reads `cell` with a [`CellKey`] (a hashed sub-value or a `Vc::keyed()` read).
KeyedCellDependency {
dependent: TaskId,
cell: CellRef,
id: u32,
key: CellKey,
},
/// `dependent` reads the output of `output_task`.
OutputDependency {
......@@ -66,18 +61,11 @@ pub fn capture_all_edges(task: &TaskGuard<'_>) -> Vec<OutdatedEdge> {
cell,
}),
);
old_edges.extend(task.iter_cell_dependencies_hashed().map(|(cell, key)| {
OutdatedEdge::HashedCellDependency {
dependent: task_id,
cell,
key,
}
}));
old_edges.extend(task.iter_cell_dependencies_keyed().map(|(cell, id)| {
old_edges.extend(task.iter_cell_dependencies_keyed().map(|(cell, key)| {
OutdatedEdge::KeyedCellDependency {
dependent: task_id,
cell,
id,
key,
}
}));
old_edges.extend(
......@@ -96,24 +84,14 @@ pub fn capture_all_edges(task: &TaskGuard<'_>) -> Vec<OutdatedEdge> {
},
}),
);
old_edges.extend(task.iter_cell_dependents_hashed().map(|(entry, key)| {
OutdatedEdge::HashedCellDependency {
dependent: entry.task,
cell: CellRef {
task: task_id,
cell: entry.cell,
},
key,
}
}));
old_edges.extend(task.iter_cell_dependents_keyed().map(|(entry, id)| {
old_edges.extend(task.iter_cell_dependents_keyed().map(|(entry, key)| {
OutdatedEdge::KeyedCellDependency {
dependent: entry.task,
cell: CellRef {
task: task_id,
cell: entry.cell,
},
id,
key,
}
}));
old_edges.extend(task.iter_output_dependent().map(|dependent| {
......@@ -297,32 +275,10 @@ fn cleanup_old_edges_inner(
task.remove_outdated_cell_dependencies(&cell);
}
}
OutdatedEdge::HashedCellDependency {
dependent,
cell,
key,
} => {
// Same as above but in the `_hashed` sets.
{
let mut task = ctx.task(cell.task, TaskDataCategory::Data);
task.remove_cell_dependents_hashed(&(
CellRef {
task: dependent,
cell: cell.cell,
},
key,
));
}
{
let mut task = ctx.task(dependent, TaskDataCategory::Data);
task.remove_cell_dependencies_hashed(&(cell, key));
task.remove_outdated_cell_dependencies_hashed(&(cell, key));
}
}
OutdatedEdge::KeyedCellDependency {
dependent,
cell,
id,
key,
} => {
// Same as above but in the `_keyed` sets.
{
......@@ -332,13 +288,13 @@ fn cleanup_old_edges_inner(
task: dependent,
cell: cell.cell,
},
id,
key,
));
}
{
let mut task = ctx.task(dependent, TaskDataCategory::Data);
task.remove_cell_dependencies_keyed(&(cell, id));
task.remove_outdated_cell_dependencies_keyed(&(cell, id));
task.remove_cell_dependencies_keyed(&(cell, key));
task.remove_outdated_cell_dependencies_keyed(&(cell, key));
}
}
OutdatedEdge::OutputDependency {
......
......@@ -1775,10 +1775,6 @@ impl<'a> TaskGuard<'a> {
self.iter_cell_dependencies()
.map(|r| (r.task, TaskDataCategory::All)),
)
.chain(
self.iter_cell_dependencies_hashed()
.map(|(r, _)| (r.task, TaskDataCategory::All)),
)
.chain(
self.iter_cell_dependencies_keyed()
.map(|(r, _)| (r.task, TaskDataCategory::All)),
......
......@@ -5,7 +5,7 @@ use smallvec::SmallVec;
#[cfg(feature = "task_dirty_cause")]
use turbo_tasks::TaskDirtyCause;
use turbo_tasks::{
CellId, FxIndexMap, TaskId, TrackKey, TypedSharedReference, ValueTypePersistence,
CellId, CellKey, FxIndexMap, TaskId, TypedSharedReference, ValueTypePersistence,
backend::{CellContent, CellHash, VerificationMode},
registry,
};
......@@ -109,7 +109,7 @@ pub fn update_cell(
// Collect dependent tasks only when not skipping invalidation.
// The iterators borrow from `task`, so they must be scoped to drop before
// we mutably borrow `task` again in the fast path.
let mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[TrackKey; 2]>> =
let mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[Option<CellKey>; 2]>> =
FxIndexMap::default();
if !skip_invalidation {
// Keyless dependents: always invalidate when the cell matches.
......@@ -122,44 +122,34 @@ pub fn update_cell(
dependent_tasks
.entry(dependent_task)
.or_default()
.push(TrackKey::None);
.push(None);
}
}
// `keyed()` read dependents: always invalidate when the cell matches, like keyless
// dependents.
for (
CellRef {
task: dependent_task,
cell: dependent_cell,
},
id,
key,
) in task.iter_cell_dependents_keyed()
{
if dependent_cell == cell {
dependent_tasks
.entry(dependent_task)
.or_default()
.push(TrackKey::Keyed(id));
if dependent_cell != cell {
continue;
}
}
// Keyed dependents: invalidate only when the changed sub-value (key) matches.
for (
CellRef {
task: dependent_task,
cell: dependent_cell,
},
key_hash,
) in task.iter_cell_dependents_hashed()
{
if dependent_cell == cell
&& updated_key_hashes_set
let affected = match key {
// Hashed dependents: invalidate only when the changed sub-value (key)
// matches.
CellKey::Hash(key_hash) => updated_key_hashes_set
.as_ref()
.is_none_or(|set| set.contains(&key_hash))
{
.is_none_or(|set| set.contains(&key_hash)),
// `keyed()` read dependents: always invalidate, like keyless dependents.
CellKey::Keyed(_) => true,
};
if affected {
dependent_tasks
.entry(dependent_task)
.or_default()
.push(TrackKey::Key(key_hash));
.push(Some(key));
}
}
}
......@@ -250,7 +240,7 @@ fn update_cell_data_hash(task: &mut TaskGuard<'_>, cell: &CellId, content_hash:
fn invalidate_cell_dependents(
cell_ref: CellRef,
mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[TrackKey; 2]>>,
mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[Option<CellKey>; 2]>>,
#[cfg(feature = "task_dirty_cause")] has_updated_key_hashes: bool,
content: Option<TypedSharedReference>,
ctx: &mut ExecuteContext<'_>,
......@@ -267,21 +257,26 @@ fn invalidate_cell_dependents(
let mut dependent = ctx.task(dependent_task_id, TaskDataCategory::All);
for key in keys.iter().copied() {
let (in_outdated, in_current) = match key {
TrackKey::Key(k) => {
Some(key @ CellKey::Hash(_)) => {
let in_outdated =
dependent.outdated_cell_dependencies_hashed_contains(&(cell_ref, k));
let in_current =
!in_outdated && dependent.cell_dependencies_hashed_contains(&(cell_ref, k));
dependent.outdated_cell_dependencies_keyed_contains(&(cell_ref, key));
let in_current = !in_outdated
&& dependent.cell_dependencies_keyed_contains(&(cell_ref, key));
(in_outdated, in_current)
}
TrackKey::Keyed(id) => {
Some(key @ CellKey::Keyed(_)) => {
let in_outdated =
dependent.outdated_cell_dependencies_keyed_contains(&(cell_ref, id));
let in_current =
!in_outdated && dependent.cell_dependencies_keyed_contains(&(cell_ref, id));
dependent.outdated_cell_dependencies_keyed_contains(&(cell_ref, key));
// When the execution of the dependent completed in the meantime, the `Keyed`
// dependency was converted to a full dependency on the cell. Accepting a full
// dependency here never over-invalidates: it would invalidate the dependent
// anyway.
let in_current = !in_outdated
&& (dependent.cell_dependencies_keyed_contains(&(cell_ref, key))
|| dependent.cell_dependencies_contains(&cell_ref));
(in_outdated, in_current)
}
TrackKey::None => {
None => {
let in_outdated = dependent.outdated_cell_dependencies_contains(&cell_ref);
let in_current =
!in_outdated && dependent.cell_dependencies_contains(&cell_ref);
......@@ -316,8 +311,8 @@ fn invalidate_cell_dependents(
keys: if has_updated_key_hashes {
keys.iter()
.map(|key| match key {
TrackKey::Key(k) => Some(*k),
TrackKey::None | TrackKey::Keyed(_) => None,
Some(CellKey::Hash(k)) => Some(*k),
None | Some(CellKey::Keyed(_)) => None,
})
.collect()
} else {
......@@ -363,9 +358,7 @@ mod invalidate_cell_dependents_tests {
use std::sync::Arc;
use smallvec::{SmallVec, smallvec};
use turbo_tasks::{
CellId, FxIndexMap, TaskId, TrackKey, TurboTasks, ValueTypeId, event::Event,
};
use turbo_tasks::{CellId, CellKey, FxIndexMap, TaskId, TurboTasks, ValueTypeId, event::Event};
use super::invalidate_cell_dependents;
use crate::{
......@@ -394,6 +387,22 @@ mod invalidate_cell_dependents_tests {
}
}
fn hash(k: u64) -> Option<CellKey> {
Some(CellKey::Hash(k))
}
fn keyed(id: u32) -> Option<CellKey> {
Some(CellKey::Keyed(id))
}
/// The `cell_dependents` entry of [`DEPENDENT`] for [`cell_ref`].
fn reverse_ref() -> CellRef {
CellRef {
task: task(DEPENDENT),
cell: cell_ref().cell,
}
}
fn backend() -> Arc<TurboTasks<TurboTasksBackend>> {
let tt = TurboTasks::new(TurboTasksBackend::new(
BackendOptions {
......@@ -425,7 +434,7 @@ mod invalidate_cell_dependents_tests {
/// Marks the dependent as in progress (so it is never scheduled for real), applies `setup`,
/// invalidates the cell for `keys` and returns `(dirty, stale)` of the dependent.
fn run(setup: Setup, keys: SmallVec<[TrackKey; 2]>) -> (bool, bool) {
fn run(setup: Setup, keys: SmallVec<[Option<CellKey>; 2]>) -> (bool, bool) {
let tt = backend();
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
{
......@@ -440,16 +449,17 @@ mod invalidate_cell_dependents_tests {
},
)));
for k in setup.current_keys {
let _ = dependent.add_cell_dependencies_hashed((cell_ref(), k));
let _ = dependent.add_cell_dependencies_keyed((cell_ref(), CellKey::Hash(k)));
}
for k in setup.outdated_keys {
let _ = dependent.add_outdated_cell_dependencies_hashed((cell_ref(), k));
let _ =
dependent.add_outdated_cell_dependencies_keyed((cell_ref(), CellKey::Hash(k)));
}
if setup.current_unkeyed {
let _ = dependent.add_cell_dependencies(cell_ref());
}
for id in setup.current_keyed {
let _ = dependent.add_cell_dependencies_keyed((cell_ref(), id));
let _ = dependent.add_cell_dependencies_keyed((cell_ref(), CellKey::Keyed(id)));
}
}
......@@ -480,18 +490,12 @@ mod invalidate_cell_dependents_tests {
current_keys: vec![99],
..Default::default()
};
assert_eq!(
run(setup, smallvec![TrackKey::Key(1), TrackKey::Key(2)]),
(false, false)
);
assert_eq!(run(setup, smallvec![hash(1), hash(2)]), (false, false));
}
#[tokio::test(flavor = "multi_thread")]
async fn unkeyed_dependency_removed_does_not_dirty() {
assert_eq!(
run(Setup::default(), smallvec![TrackKey::None]),
(false, false)
);
assert_eq!(run(Setup::default(), smallvec![None]), (false, false));
}
#[tokio::test(flavor = "multi_thread")]
......@@ -500,10 +504,7 @@ mod invalidate_cell_dependents_tests {
current_keys: vec![2],
..Default::default()
};
assert_eq!(
run(setup, smallvec![TrackKey::Key(1), TrackKey::Key(2)]),
(true, true)
);
assert_eq!(run(setup, smallvec![hash(1), hash(2)]), (true, true));
}
#[tokio::test(flavor = "multi_thread")]
......@@ -512,7 +513,7 @@ mod invalidate_cell_dependents_tests {
current_unkeyed: true,
..Default::default()
};
assert_eq!(run(setup, smallvec![TrackKey::None]), (true, true));
assert_eq!(run(setup, smallvec![None]), (true, true));
}
#[tokio::test(flavor = "multi_thread")]
......@@ -521,7 +522,7 @@ mod invalidate_cell_dependents_tests {
current_keyed: vec![0],
..Default::default()
};
assert_eq!(run(setup, smallvec![TrackKey::Keyed(0)]), (true, true));
assert_eq!(run(setup, smallvec![keyed(0)]), (true, true));
}
#[tokio::test(flavor = "multi_thread")]
......@@ -531,7 +532,55 @@ mod invalidate_cell_dependents_tests {
current_keyed: vec![1],
..Default::default()
};
assert_eq!(run(setup, smallvec![TrackKey::Keyed(0)]), (false, false));
assert_eq!(run(setup, smallvec![keyed(0)]), (false, false));
}
#[tokio::test(flavor = "multi_thread")]
async fn converted_keyed_read_dependency_dirty_and_stale() {
// The `Keyed` dependent was collected, but the execution of the dependent completed in the
// meantime and converted it to a full dependency. The invalidation must not be lost.
let setup = Setup {
current_unkeyed: true,
..Default::default()
};
assert_eq!(run(setup, smallvec![keyed(0)]), (true, true));
}
#[tokio::test(flavor = "multi_thread")]
async fn remaining_keyed_dependencies_converted_on_completion() {
let tt = backend();
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
{
let (mut cell_task, mut dependent) =
ctx.task_pair(task(CELL_TASK), task(DEPENDENT), TaskDataCategory::All);
// Two `keyed()` reads of the same cell, and a hashed read.
for key in [CellKey::Keyed(0), CellKey::Keyed(1), CellKey::Hash(5)] {
let _ = cell_task.add_cell_dependents_keyed((reverse_ref(), key));
let _ = dependent.add_cell_dependencies_keyed((cell_ref(), key));
}
// A full dependency from the previous execution that wasn't re-read as such. The
// conversion re-reads it, so it must no longer be outdated (and not be cleaned up).
let _ = cell_task.add_cell_dependents(reverse_ref());
let _ = dependent.add_cell_dependencies(cell_ref());
let _ = dependent.add_outdated_cell_dependencies(cell_ref());
}
tt.backend()
.convert_remaining_keyed_cell_dependencies(&mut ctx, task(DEPENDENT));
let (cell_task, dependent) =
ctx.task_pair(task(CELL_TASK), task(DEPENDENT), TaskDataCategory::All);
// The `Keyed` dependencies became a full dependency, on both sides of the edge.
for key in [CellKey::Keyed(0), CellKey::Keyed(1)] {
assert!(!dependent.cell_dependencies_keyed_contains(&(cell_ref(), key)));
assert!(!cell_task.cell_dependents_keyed_contains(&(reverse_ref(), key)));
}
assert!(dependent.cell_dependencies_contains(&cell_ref()));
assert!(!dependent.outdated_cell_dependencies_contains(&cell_ref()));
assert!(cell_task.cell_dependents_contains(&reverse_ref()));
// Hashed dependencies are untouched.
assert!(dependent.cell_dependencies_keyed_contains(&(cell_ref(), CellKey::Hash(5))));
assert!(cell_task.cell_dependents_keyed_contains(&(reverse_ref(), CellKey::Hash(5))));
}
#[tokio::test(flavor = "multi_thread")]
......@@ -544,14 +593,8 @@ mod invalidate_cell_dependents_tests {
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
let (mut cell_task, mut dependent) =
ctx.task_pair(task(CELL_TASK), task(DEPENDENT), TaskDataCategory::All);
let _ = cell_task.add_cell_dependents_keyed((
CellRef {
task: task(DEPENDENT),
cell: cell_ref().cell,
},
0,
));
let _ = dependent.add_cell_dependencies_keyed((cell_ref(), 0));
let _ = cell_task.add_cell_dependents_keyed((reverse_ref(), CellKey::Keyed(0)));
let _ = dependent.add_cell_dependencies_keyed((cell_ref(), CellKey::Keyed(0)));
}
tt.backend().convert_keyed_cell_dependency(
......@@ -565,8 +608,8 @@ mod invalidate_cell_dependents_tests {
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
let dependent = ctx.task(task(DEPENDENT), TaskDataCategory::All);
assert!(dependent.cell_dependencies_keyed_contains(&(cell_ref(), 0)));
assert!(!dependent.cell_dependencies_hashed_contains(&(cell_ref(), 1)));
assert!(dependent.cell_dependencies_keyed_contains(&(cell_ref(), CellKey::Keyed(0))));
assert!(!dependent.cell_dependencies_keyed_contains(&(cell_ref(), CellKey::Hash(1))));
}
#[tokio::test(flavor = "multi_thread")]
......@@ -575,9 +618,6 @@ mod invalidate_cell_dependents_tests {
outdated_keys: vec![1],
..Default::default()
};
assert_eq!(
run(setup, smallvec![TrackKey::Key(1), TrackKey::Key(2)]),
(true, false)
);
assert_eq!(run(setup, smallvec![hash(1), hash(2)]), (true, false));
}
}
......@@ -25,7 +25,7 @@ use std::{
use parking_lot::Mutex;
use rustc_hash::FxHasher;
use turbo_tasks::{
CellId, SharedReference, TaskExecutionReason, TaskId, TraitTypeId, ValueTypeId,
CellId, CellKey, SharedReference, TaskExecutionReason, TaskId, TraitTypeId, ValueTypeId,
backend::{CachedTaskTypeArc, CellHash, TransientTaskType},
event::Event,
task_storage,
......@@ -267,9 +267,9 @@ struct TaskStorageSchema {
)]
output_dependencies: AutoSet<TaskId, 6>,
/// Cells this task depends on as a whole (keyless `CellDependency::All`). The common case;
/// kept separate from `cell_dependencies_hashed` so it stores a bare `CellRef` instead of the
/// wider `CellDependency` enum (no tag, no `u64`).
/// Cells this task depends on as a whole (keyless). The common case; kept separate from
/// `cell_dependencies_keyed` so it stores a bare `CellRef` instead of a `(CellRef, CellKey)`
/// pair.
#[field(
storage = "auto_set",
category = "data",
......@@ -279,7 +279,13 @@ struct TaskStorageSchema {
)]
cell_dependencies: AutoSet<CellRef, 3>,
/// Cells this task depends on, narrowed to a hashed sub-value (`CellDependency::Hash`). Rare.
/// Cells this task depends on with a `CellKey`. Rare.
/// - `CellKey::Hash`: narrowed to a hashed sub-value, only invalidated when it changes.
/// - `CellKey::Keyed`: a `Vc::keyed()` read that hasn't been converted to `CellKey::Hash`
/// dependencies yet, identified by the `keyed()` call counter of the execution. Invalidated
/// like `cell_dependencies`. Short-lived: the `KeyedReadRef` converts it to `CellKey::Hash`
/// entries when dropped, and any remaining ones are converted to `cell_dependencies` when
/// the execution completes.
#[field(
storage = "auto_set",
category = "data",
......@@ -287,20 +293,7 @@ struct TaskStorageSchema {
shrink_on_completion,
drop_on_completion_if_immutable
)]
cell_dependencies_hashed: AutoSet<(CellRef, u64), 1>,
/// Cells this task depends on via a `Vc::keyed()` read that hasn't been converted to hashed
/// dependencies (`TrackKey::Keyed`), identified by the `keyed()` call counter of the
/// execution. Invalidated like `cell_dependencies`. Rare and usually short-lived: the
/// `KeyedReadRef` converts it to `cell_dependencies_hashed` when dropped.
#[field(
storage = "auto_set",
category = "data",
filter_transient,
shrink_on_completion,
drop_on_completion_if_immutable
)]
cell_dependencies_keyed: AutoSet<(CellRef, u32), 1>,
cell_dependencies_keyed: AutoSet<(CellRef, CellKey), 1>,
/// Collectibles this task depends on.
#[field(
......@@ -320,13 +313,9 @@ struct TaskStorageSchema {
#[field(storage = "auto_set", category = "transient", drop_on_completion)]
outdated_cell_dependencies: AutoSet<CellRef, 3>,
/// Outdated hashed cell dependencies to be cleaned up (transient).
/// Outdated cell dependencies with a `CellKey` to be cleaned up (transient).
#[field(storage = "auto_set", category = "transient", drop_on_completion)]
outdated_cell_dependencies_hashed: AutoSet<(CellRef, u64), 1>,
/// Outdated keyed-read cell dependencies to be cleaned up (transient).
#[field(storage = "auto_set", category = "transient", drop_on_completion)]
outdated_cell_dependencies_keyed: AutoSet<(CellRef, u32), 1>,
outdated_cell_dependencies_keyed: AutoSet<(CellRef, CellKey), 1>,
/// Outdated collectibles dependencies to be cleaned up (transient).
#[field(storage = "auto_set", category = "transient", drop_on_completion)]
......@@ -346,25 +335,16 @@ struct TaskStorageSchema {
)]
cell_dependents: AutoSet<CellRef, 3>,
/// Tasks that depend on a hashed sub-value of this task's cells. Reverse of
/// `cell_dependencies_hashed`.
/// Tasks that depend on this task's cells with a `CellKey`. Reverse of
/// `cell_dependencies_keyed`. `CellKey::Hash` entries are only invalidated when that sub-value
/// changes, `CellKey::Keyed` entries like `cell_dependents`.
#[field(
storage = "auto_set",
category = "data",
filter_transient,
drop_on_completion_if_immutable
)]
cell_dependents_hashed: AutoSet<(CellRef, u64), 1>,
/// Tasks that depend on this task's cells via a `Vc::keyed()` read. Reverse of
/// `cell_dependencies_keyed`. Invalidated like `cell_dependents`.
#[field(
storage = "auto_set",
category = "data",
filter_transient,
drop_on_completion_if_immutable
)]
cell_dependents_keyed: AutoSet<(CellRef, u32), 1>,
cell_dependents_keyed: AutoSet<(CellRef, CellKey), 1>,
/// Tasks that depend on collectibles of a specific type from this task.
/// Maps TraitTypeId -> Set<TaskId>
......@@ -879,7 +859,7 @@ impl TaskStorage {
///
/// The `Data`-category dependent sets are deliberately not consulted:
///
/// - `cell_dependents` / `cell_dependents_hashed` are redundant with ancestry. A cell dependent
/// - `cell_dependents` / `cell_dependents_keyed` are redundant with ancestry. A cell dependent
/// is either a child, whose child edge already orders the teardown, or a sibling reached by
/// passing a `ResolvedVc` laterally, which needs a common ancestor that collects both in the
/// same pass. Counting them deadlocked the caller/callee cycle `NftJsonAsset::content` ->
......@@ -1005,12 +985,7 @@ impl IsTransient for CellRef {
CellRef::is_transient(self)
}
}
impl IsTransient for (CellRef, u64) {
fn is_transient(&self) -> bool {
self.0.is_transient()
}
}
impl IsTransient for (CellRef, u32) {
impl IsTransient for (CellRef, CellKey) {
fn is_transient(&self) -> bool {
self.0.is_transient()
}
......
......@@ -625,6 +625,11 @@ pub trait Backend: Sized + Sync + Send {
/// Called when a task's execution finishes.
///
/// `has_keyed_reads` is true when the execution made [`Vc::keyed`][crate::Vc::keyed] reads.
/// The backend must then convert all [`CellKey::Keyed`][crate::CellKey::Keyed] dependencies of
/// the task that are still present into normal (full) cell dependencies, as their ids are only
/// meaningful within this execution.
///
/// Returns `Some(priority)` if the task was invalidated again while executing and must be
/// re-run. The caller is responsible for re-scheduling the task at the returned priority
/// (typically lower than the priority of the just-finished run).
......@@ -633,6 +638,7 @@ pub trait Backend: Sized + Sync + Send {
task: TaskId,
result: Result<RawVc, TurboTasksExecutionError>,
cell_counters: &AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>,
has_keyed_reads: bool,
#[cfg(feature = "verify_determinism")] stateful: bool,
has_invalidator: bool,
turbo_tasks: &TurboTasks<Self>,
......@@ -667,9 +673,9 @@ pub trait Backend: Sized + Sync + Send {
turbo_tasks: &TurboTasks<Self>,
) -> Result<ReadOutcome<TypedCellContent>>;
/// Replaces the [`TrackKey::Keyed(id)`][crate::TrackKey::Keyed] dependency of `reader` on the
/// Replaces the [`CellKey::Keyed(id)`][crate::CellKey::Keyed] dependency of `reader` on the
/// cell `index` of `task`, which was created by a [`Vc::keyed`][crate::Vc::keyed] read, with
/// [`TrackKey::Key`][crate::TrackKey::Key] dependencies on each of the `key_hashes`, in a
/// [`CellKey::Hash`][crate::CellKey::Hash] dependencies on each of the `key_hashes`, in a
/// single operation.
///
/// Must only be called from within the same execution of `reader` that created the
......
......@@ -100,8 +100,8 @@ pub use crate::{
},
join_iter_ext::{JoinIterExt, TryFlatJoinIterExt, TryJoinIterExt},
manager::{
CurrentCellRef, GcRoot, InputResolution, ReadCellTracking, ReadConsistency, ReadTracking,
ScheduleKey, TaskPersistence, TaskPriority, TrackKey, TurboTasks, TurboTasksApi,
CellKey, CurrentCellRef, GcRoot, InputResolution, ReadCellTracking, ReadConsistency,
ReadTracking, ScheduleKey, TaskPersistence, TaskPriority, TurboTasks, TurboTasksApi,
TurboTasksCallApi, Unused, UpdateInfo, dynamic_call, emit, get_serialization_invalidator,
mark_finished, mark_stateful, mark_top_level_task, prevent_gc, run, run_once,
run_once_with_reason, trait_call, try_turbo_tasks, turbo_tasks, turbo_tasks_scope,
......
......@@ -150,8 +150,8 @@ pub trait TurboTasksApi: TurboTasksCallApi + Sync + Send {
options: ReadCellOptions,
) -> Result<ReadOutcome<TypedCellContent>>;
/// Replaces the [`TrackKey::Keyed(id)`][TrackKey::Keyed] dependency of the current task
/// (`reader`) on the cell `index` of `task` with [`TrackKey::Key`] dependencies on each of the
/// Replaces the [`CellKey::Keyed(id)`][CellKey::Keyed] dependency of the current task
/// (`reader`) on the cell `index` of `task` with [`CellKey::Hash`] dependencies on each of the
/// `key_hashes`. See [`Backend::convert_keyed_cell_dependency`].
fn convert_keyed_cell_dependency(
&self,
......@@ -351,21 +351,21 @@ pub enum ReadConsistency {
Strong,
}
/// Identifies which part of a cell a tracked cell read depends on.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Default)]
pub enum TrackKey {
/// The read depends on the whole cell content.
#[default]
None,
/// Identifies the part of a cell a tracked cell read depends on, when it doesn't depend on the
/// whole cell content (which is represented by `None` in an `Option<CellKey>`).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Encode, Decode)]
pub enum CellKey {
/// The read only depends on the sub-value identified by this key hash (see
/// [`KeyedEq`]). The dependency is only invalidated when the value of this key changes.
Key(u64),
/// The read is a [`Vc::keyed`](crate::Vc::keyed) read. For invalidation it behaves like
/// [`TrackKey::None`] (invalidated by any change of the cell), but it is a separate dependency
/// that is uniquely identified by this counter of `keyed()` calls within the current task
/// execution. This allows the [`KeyedReadRef`](crate::KeyedReadRef) to replace it with
/// [`TrackKey::Key`] dependencies of the accessed keys once it's dropped, without affecting
/// other (full) dependencies on the same cell.
Hash(u64),
/// The read is a [`Vc::keyed`](crate::Vc::keyed) read. For invalidation it behaves like a
/// dependency on the whole cell (invalidated by any change of the cell), but it is a separate
/// dependency that is uniquely identified by this counter of `keyed()` calls within the
/// current task execution. This allows the [`KeyedReadRef`](crate::KeyedReadRef) to replace it
/// with [`CellKey::Hash`] dependencies of the accessed keys once it's dropped, without
/// affecting other (full) dependencies on the same cell. `Keyed` dependencies that are still
/// present when the execution completes are converted to normal (full) dependencies, so they
/// never outlive the execution that created them.
Keyed(u32),
}
......@@ -373,8 +373,8 @@ pub enum TrackKey {
pub enum ReadCellTracking {
/// Reads are tracked as dependencies of the current task.
Tracked {
/// The key used for the dependency
key: TrackKey,
/// The part of the cell the dependency is on. `None` depends on the whole cell.
key: Option<CellKey>,
},
/// The read is only tracked when there is an error, otherwise it is untracked.
///
......@@ -397,34 +397,30 @@ impl ReadCellTracking {
}
}
pub fn key(&self) -> TrackKey {
pub fn key(&self) -> Option<CellKey> {
match self {
ReadCellTracking::Tracked { key } => *key,
ReadCellTracking::TrackOnlyError => TrackKey::None,
ReadCellTracking::Untracked => TrackKey::None,
ReadCellTracking::TrackOnlyError => None,
ReadCellTracking::Untracked => None,
}
}
}
impl Default for ReadCellTracking {
fn default() -> Self {
ReadCellTracking::Tracked {
key: TrackKey::None,
}
ReadCellTracking::Tracked { key: None }
}
}
impl Display for ReadCellTracking {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ReadCellTracking::Tracked { key: None } => write!(f, "tracked"),
ReadCellTracking::Tracked {
key: TrackKey::None,
} => write!(f, "tracked"),
ReadCellTracking::Tracked {
key: TrackKey::Key(key),
key: Some(CellKey::Hash(key)),
} => write!(f, "tracked with key {key}"),
ReadCellTracking::Tracked {
key: TrackKey::Keyed(id),
key: Some(CellKey::Keyed(id)),
} => write!(f, "tracked as keyed read {id}"),
ReadCellTracking::TrackOnlyError => write!(f, "track only error"),
ReadCellTracking::Untracked => write!(f, "untracked"),
......@@ -864,7 +860,7 @@ struct CurrentTaskStateHandle {
struct CurrentTaskStateInner {
current_task_id: Option<TaskId>,
/// Counter of [`Vc::keyed`](crate::Vc::keyed) reads in this execution, used to give every
/// [`TrackKey::Keyed`] dependency a unique id.
/// [`CellKey::Keyed`] dependency a unique id.
keyed_read_counter: AtomicU32,
state: RwLock<CurrentTaskState>,
}
......@@ -885,7 +881,7 @@ impl CurrentTaskStateHandle {
}
}
/// Identifies the [`TrackKey::Keyed`] dependency of a [`Vc::keyed`](crate::Vc::keyed) read and the
/// Identifies the [`CellKey::Keyed`] dependency of a [`Vc::keyed`](crate::Vc::keyed) read and the
/// task execution that created it.
pub(crate) struct KeyedReadDependency {
/// The execution state of the reading task. Only used for identity (a `Weak` keeps the
......@@ -896,7 +892,7 @@ pub(crate) struct KeyedReadDependency {
}
impl KeyedReadDependency {
/// Allocates a new [`TrackKey::Keyed`] dependency id for the current task execution. Returns
/// Allocates a new [`CellKey::Keyed`] dependency id for the current task execution. Returns
/// `None` when not called from within a task execution (e.g. a top-level `run`), where reads
/// are not tracked anyway, or when the ids of this execution are exhausted. In that case the
/// read is tracked as a normal (full) dependency.
......@@ -1745,12 +1741,23 @@ impl<B: Backend> Executor<TurboTasks<B>, ScheduledTask, TaskPriority> for TurboT
};
let finished_state = this.finish_current_task_state();
let cell_counters = CURRENT_TASK_STATE
.with(|ts| ts.write().unwrap().cell_counters.take().unwrap());
let (cell_counters, has_keyed_reads) =
CURRENT_TASK_STATE.with(|ts| {
let cell_counters =
ts.write().unwrap().cell_counters.take().unwrap();
// All reads of this execution are done (local tasks
// were awaited above), so the backend only needs to
// look for remaining `CellKey::Keyed` dependencies when
// `keyed()` was used.
let has_keyed_reads =
ts.inner.keyed_read_counter.load(Ordering::Relaxed) > 0;
(cell_counters, has_keyed_reads)
});
this.backend.task_execution_completed(
task_id,
result,
&cell_counters,
has_keyed_reads,
#[cfg(feature = "verify_determinism")]
finished_state.stateful,
finished_state.has_invalidator,
......
......@@ -26,9 +26,9 @@ use crate::{
/// change. The hashes of the accessed keys are recorded. When it is dropped within the task
/// execution that read it, that dependency is replaced (in a single batch operation) with
/// dependencies on only the accessed keys, so the task is only invalidated when one of the
/// accessed keys changes, like with [`Vc::get`](crate::Vc::get). When it is dropped outside of
/// that task execution (e.g. moved to another thread or task), the dependency on the whole cell
/// is kept.
/// accessed keys changes, like with [`Vc::get`](crate::Vc::get). When it is still alive at the end
/// of that task execution or dropped outside of it (e.g. moved to another thread or task), the
/// dependency is converted to a normal dependency on the whole cell when the execution completes.
///
/// Note: Like with [`Vc::contains_key`](crate::Vc::contains_key), a
/// [`contains_key`](KeyedReadRef::contains_key) access is also invalidated when the value of the
......
......@@ -25,9 +25,9 @@ use crate::{
event::EventListener,
id::{ExecutionId, LocalTaskId, TASK_ID_MAX},
manager::{
ReadCellTracking, ReadTracking, SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK,
ScheduleKey, TrackKey, TurboTasksApi, execute_read_target_inline, read_local_output,
with_turbo_tasks,
CellKey, ReadCellTracking, ReadTracking,
SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK, ScheduleKey, TurboTasksApi,
execute_read_target_inline, read_local_output, with_turbo_tasks,
},
read_options::ReadOutcome,
registry::get_value_type,
......@@ -770,12 +770,12 @@ impl ReadRawVcFuture {
/// Track the value as a dependency with an key.
pub fn track_with_key(mut self, key: u64) -> Self {
self.read_cell_options.tracking = ReadCellTracking::Tracked {
key: TrackKey::Key(key),
key: Some(CellKey::Hash(key)),
};
self.map_resolve(|r| r.track_with_key())
}
/// Track the value as a [`TrackKey::Keyed`] dependency of a [`Vc::keyed`](crate::Vc::keyed)
/// Track the value as a [`CellKey::Keyed`] dependency of a [`Vc::keyed`](crate::Vc::keyed)
/// read. Like [`ReadRawVcFuture::track_with_key`], this also tracks the reads of task outputs
/// while resolving the [`RawVc`].
///
......@@ -787,20 +787,18 @@ impl ReadRawVcFuture {
};
resolve.read_output_options.tracking = ReadTracking::Tracked;
self.read_cell_options.tracking = ReadCellTracking::Tracked {
key: TrackKey::Keyed(id),
key: Some(CellKey::Keyed(id)),
};
}
/// Track the remaining reads as normal full dependencies, e.g. when a [`TrackKey::Keyed`] read
/// Track the remaining reads as normal full dependencies, e.g. when a [`CellKey::Keyed`] read
/// continues in a different task execution than the one that allocated its id. Can be called
/// at any time before the future completes.
pub(crate) fn set_track_full(&mut self) {
if let ReadRawVcState::Resolving(resolve) = &mut self.state {
resolve.read_output_options.tracking = ReadTracking::Tracked;
}
self.read_cell_options.tracking = ReadCellTracking::Tracked {
key: TrackKey::None,
};
self.read_cell_options.tracking = ReadCellTracking::Tracked { key: None };
}
/// The task cell the [`RawVc`] was resolved to. Only available once the future has completed
......
......@@ -349,7 +349,7 @@ where
/// created the future).
enum KeyedDependencyState {
NotStarted,
/// `None` if the read isn't a [`TrackKey::Keyed`](crate::TrackKey::Keyed) read (no current
/// `None` if the read isn't a [`CellKey::Keyed`](crate::CellKey::Keyed) read (no current
/// task, or the dependency was already handed to the [`KeyedReadRef`]).
Started(Option<KeyedReadDependency>),
}
......
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