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

Simplify turbo-tasks-backend guards and execution contexts (#99599)

### What?

Simplify the task guard and execution context abstractions in
`turbo-tasks-backend`, including the companion child context used for
parallel work.

Followup from #99249

### Why?

Each trait has a single implementation, with no alternate
implementations or mocks using the abstraction. The trait layer adds
duplicate declarations, associated types, and generic plumbing without
providing a useful extension point today. This is a simplicity refactor,
not a performance optimization.


<!-- fleet 22e7fce7-cf14-4d21-9cb9-d77f674cb241 -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 2d5a45a5
......@@ -31,8 +31,8 @@ use crate::{
backend::{
TurboTasksBackend,
operation::{
AggregationUpdateJob, AggregationUpdateQueue, ExecuteContext, ExecuteContextImpl,
TaskGuard, capture_all_edges, cleanup_old_edges_deletions_only,
AggregationUpdateJob, AggregationUpdateQueue, ExecuteContext, capture_all_edges,
cleanup_old_edges_deletions_only,
},
snapshot_coordinator::SnapshotPhase,
storage::{SpecificTaskDataCategory, TaskDataCategory},
......@@ -262,7 +262,7 @@ impl TurboTasksBackend {
GcJob::Collect(task_id) => task_id,
};
let collector = |child_id| spawner.spawn(GcJob::Collect(child_id));
let mut ctx = ExecuteContextImpl::new_for_gc(self, turbo_tasks, phase, &collector);
let mut ctx = ExecuteContext::new_for_gc(self, turbo_tasks, phase, &collector);
// `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);
......@@ -321,7 +321,7 @@ impl TurboTasksBackend {
let deferred = std::mem::take(&mut result.deferred_balance_edges);
if !deferred.is_empty() {
let noop_collector = |_task_id| {};
let mut ctx = ExecuteContextImpl::new_for_gc(self, turbo_tasks, phase, &noop_collector);
let mut ctx = ExecuteContext::new_for_gc(self, turbo_tasks, phase, &noop_collector);
let mut queue = AggregationUpdateQueue::new();
queue.extend_balance_edges(deferred, &mut ctx);
while !queue.process(&mut ctx) {}
......@@ -333,7 +333,7 @@ impl TurboTasksBackend {
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 ctx = ExecuteContext::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 {
......
......@@ -64,11 +64,10 @@ pub use self::{
use crate::{
backend::{
operation::{
AggregationUpdateJob, AggregationUpdateQueue, ChildExecuteContext, ExecuteContext,
ExecuteContextImpl, LeafDistanceUpdateQueue, OutdatedEdge, TaskGuard, TaskType,
TaskTypeRef, capture_all_edges, cleanup_old_edges, connect_child, connect_children,
get_aggregation_number, get_uppers, invalidate, make_task_dirty_internal,
prepare_new_children, update_cell,
AggregationUpdateJob, AggregationUpdateQueue, ExecuteContext, LeafDistanceUpdateQueue,
OutdatedEdge, TaskGuard, TaskType, TaskTypeRef, capture_all_edges, cleanup_old_edges,
connect_child, connect_children, get_aggregation_number, get_uppers, invalidate,
make_task_dirty_internal, prepare_new_children, update_cell,
},
snapshot_coordinator::{OperationGuard, SlowSettle, SnapshotCoordinator},
storage::Storage,
......@@ -104,7 +103,7 @@ const GC_MIN_PROGRESS: Duration = Duration::from_millis(100);
/// than the (likely higher) priority of the original schedule. We use invalidation priority
/// based on the task's leaf distance, parented under either the task's current dirty priority
/// or `leaf()` if it is no longer dirty.
fn compute_stale_priority(task: &impl TaskGuard) -> TaskPriority {
fn compute_stale_priority(task: &TaskGuard<'_>) -> TaskPriority {
TaskPriority::invalidation(
task.get_leaf_distance()
.copied()
......@@ -371,8 +370,8 @@ impl TurboTasksBackend {
fn execute_context<'a>(
&'a self,
turbo_tasks: &'a TurboTasks<TurboTasksBackend>,
) -> impl ExecuteContext<'a> {
ExecuteContextImpl::new(self, turbo_tasks)
) -> ExecuteContext<'a> {
ExecuteContext::new(self, turbo_tasks)
}
/// Like [`TurboTasksBackend::execute_context`], but refuses to hand out a context once
......@@ -385,12 +384,12 @@ impl TurboTasksBackend {
fn try_execute_context<'a>(
&'a self,
turbo_tasks: &'a TurboTasks<TurboTasksBackend>,
) -> Option<impl ExecuteContext<'a>> {
) -> Option<ExecuteContext<'a>> {
let stopping = self.stopping.read();
if *stopping {
return None;
}
Some(ExecuteContextImpl::new_with_shutdown_guard(
Some(ExecuteContext::new_with_shutdown_guard(
self,
turbo_tasks,
stopping,
......@@ -513,7 +512,7 @@ impl TurboTasksBackend {
fn task_error_to_turbo_tasks_execution_error(
&self,
error: &TaskError,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
) -> TurboTasksExecutionError {
match error {
TaskError::Panic(panic) => TurboTasksExecutionError::Panic(panic.clone()),
......@@ -584,11 +583,11 @@ struct TaskExecutionCompletePrepareResult {
pub is_session_dependent: bool,
}
fn lock_task_and_optional_reader<'e, C: ExecuteContext<'e>>(
ctx: &mut C,
fn lock_task_and_optional_reader<'e>(
ctx: &mut ExecuteContext<'e>,
task_id: TaskId,
reader_id: Option<TaskId>,
) -> (C::TaskGuardImpl, Option<C::TaskGuardImpl>) {
) -> (TaskGuard<'e>, Option<TaskGuard<'e>>) {
let Some(reader_id) = reader_id else {
return (ctx.task(task_id, TaskDataCategory::All), None);
};
......@@ -663,7 +662,7 @@ impl TurboTasksBackend {
/// whether a worker has actually started it. A task that is only `Scheduled` can be taken
/// over and executed by the reader; one that is `InProgress` can only be waited for.
fn check_in_progress<T>(
task: &impl TaskGuard,
task: &TaskGuard<'_>,
reader_description: Option<EventDescription>,
tracking: ReadTracking,
) -> Option<Result<ReadOutcome<T>>> {
......@@ -749,7 +748,7 @@ impl TurboTasksBackend {
.collect::<String>()
}
fn get_info(
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
task_id: TaskId,
parent_and_count: Option<(TaskId, i32)>,
visited: &mut FxHashSet<TaskId>,
......@@ -963,9 +962,9 @@ impl TurboTasksBackend {
fn add_cell_dependency(
task_id: TaskId,
mut task: impl TaskGuard,
mut task: TaskGuard<'_>,
reader: Option<TaskId>,
reader_task: Option<impl TaskGuard>,
reader_task: Option<TaskGuard<'_>>,
cell: CellId,
key: Option<u64>,
) {
......@@ -1104,10 +1103,10 @@ impl TurboTasksBackend {
fn listen_to_cell(
&self,
task: &mut impl TaskGuard,
task: &mut TaskGuard<'_>,
task_id: TaskId,
reader: Option<TaskId>,
reader_task: &Option<impl TaskGuard>,
reader_task: &Option<TaskGuard<'_>>,
cell: CellId,
) -> (EventListener, bool) {
let note = || {
......@@ -2298,7 +2297,7 @@ impl TurboTasksBackend {
fn task_execution_completed_prepare(
&self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
#[cfg(feature = "trace_task_details")] span: &Span,
task_id: TaskId,
result: Result<RawVc, TurboTasksExecutionError>,
......@@ -2603,7 +2602,7 @@ impl TurboTasksBackend {
fn task_execution_completed_invalidate_output_dependent(
&self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
task_id: TaskId,
#[cfg(feature = "task_dirty_cause")] function_id: Option<FunctionId>,
output_dependent_tasks: SmallVec<[TaskId; 4]>,
......@@ -2626,7 +2625,7 @@ impl TurboTasksBackend {
}
fn process_output_dependents(
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
task_id: TaskId,
#[cfg(feature = "task_dirty_cause")] cause: &TaskDirtyCause,
dependent_task_id: TaskId,
......@@ -2719,7 +2718,7 @@ impl TurboTasksBackend {
fn task_execution_completed_connect(
&self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
task_id: TaskId,
new_children: FxHashSet<TaskId>,
) -> Option<TaskPriority> {
......@@ -2789,7 +2788,7 @@ impl TurboTasksBackend {
#[allow(clippy::type_complexity)]
fn task_execution_completed_finish(
&self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
task_id: TaskId,
#[cfg(feature = "verify_determinism")] no_output_set: bool,
new_output: Option<OutputValue>,
......@@ -2897,7 +2896,7 @@ impl TurboTasksBackend {
fn task_execution_completed_cleanup(
&self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
task_id: TaskId,
cell_counters: &AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>,
is_error: bool,
......
......@@ -89,7 +89,7 @@ pub fn is_root_node(aggregation_number: u32) -> bool {
/// Returns a list of tasks that are considered as "following" the task.
fn get_followers_with_aggregation_number(
task: &impl TaskGuard,
task: &TaskGuard<'_>,
aggregation_number: u32,
) -> TaskIdVec {
if is_aggregating_node(aggregation_number) {
......@@ -101,25 +101,25 @@ fn get_followers_with_aggregation_number(
/// Returns a list of tasks that are considered as "following" the task. The current tasks is not
/// aggregating over the follower tasks and they should be aggregated by all upper tasks.
fn get_followers(task: &impl TaskGuard) -> TaskIdVec {
fn get_followers(task: &TaskGuard<'_>) -> TaskIdVec {
get_followers_with_aggregation_number(task, get_aggregation_number(task))
}
/// Returns a list of tasks that are considered as "upper" tasks of the task. The upper tasks are
/// aggregating over the task.
pub fn get_uppers(task: &impl TaskGuard) -> TaskIdVec {
pub fn get_uppers(task: &TaskGuard<'_>) -> TaskIdVec {
task.iter_upper().map(|(&id, _count)| id).collect()
}
/// Acquires a `Meta`-category guard for `task_id` and sets `optimization_pending`. Used in
/// the optimize-queue drop paths when the caller doesn't already hold a guard for the task.
fn lock_and_mark_optimization_pending(ctx: &mut impl ExecuteContext<'_>, task_id: TaskId) {
fn lock_and_mark_optimization_pending(ctx: &mut ExecuteContext<'_>, task_id: TaskId) {
let mut task = ctx.task(task_id, TaskDataCategory::Meta);
task.set_optimization_pending(true);
}
/// Returns the aggregation number of the task.
pub fn get_aggregation_number(task: &impl TaskGuard) -> u32 {
pub fn get_aggregation_number(task: &TaskGuard<'_>) -> u32 {
task.get_aggregation_number()
.map(|a| a.effective)
.unwrap_or_default()
......@@ -323,7 +323,7 @@ pub enum AggregationUpdateJob {
impl AggregationUpdateJob {
pub fn data_update(
task: &mut impl TaskGuard,
task: &mut TaskGuard<'_>,
update: AggregatedDataUpdate,
) -> Option<AggregationUpdateJob> {
let upper_ids: SmallVec<_> = get_uppers(task);
......@@ -360,7 +360,7 @@ pub struct AggregatedDataUpdate {
impl AggregatedDataUpdate {
/// Derives an `AggregatedDataUpdate` from a task. This is used when a task is connected to an
/// upper task.
fn from_task(task: &mut impl TaskGuard) -> Self {
fn from_task(task: &mut TaskGuard<'_>) -> Self {
let aggregation = get_aggregation_number(task);
let mut dirty_count = 0;
let mut current_session_clean_count = 0;
......@@ -425,7 +425,7 @@ impl AggregatedDataUpdate {
#[allow(clippy::needless_late_init)]
fn apply(
&self,
task: &mut impl TaskGuard,
task: &mut TaskGuard<'_>,
should_track_activeness: bool,
queue: &mut AggregationUpdateQueue,
) -> AggregatedDataUpdate {
......@@ -1022,7 +1022,7 @@ impl AggregationUpdateQueue {
/// it is free since the caller already holds the guard, and the saved flag value lets
/// a later drop avoid an unnecessary flag write.
/// If the job can't be enqueued the flag is set on the task instead.
fn push_optimize_task(&mut self, task: &mut impl TaskGuard) {
fn push_optimize_task(&mut self, task: &mut TaskGuard<'_>) {
let optimization_pending_flag_already_set = task.optimization_pending();
if !self.try_enqueue_optimize_job(task.id(), optimization_pending_flag_already_set) {
task.set_optimization_pending(true);
......@@ -1034,7 +1034,7 @@ impl AggregationUpdateQueue {
/// Only called from `optimize_task`'s self re-enqueue, which has just cleared the flag at
/// entry, so the enqueued job carries `optimization_pending_flag_already_set = false`. The
/// `Meta`-category guard is acquired only when the push has to be dropped.
fn push_optimize_task_by_id(&mut self, ctx: &mut impl ExecuteContext<'_>, task_id: TaskId) {
fn push_optimize_task_by_id(&mut self, ctx: &mut ExecuteContext<'_>, task_id: TaskId) {
if !self.try_enqueue_optimize_job(task_id, false) {
lock_and_mark_optimization_pending(ctx, task_id);
}
......@@ -1050,7 +1050,7 @@ impl AggregationUpdateQueue {
/// from up-to-date optimization, so we leave its tasks for one of the other recovery
/// hooks to pick up. There is currently no dedicated unit test for the drop/recovery
/// paths; coverage relies on integration tests that exercise the aggregation graph.
fn check_optimization_pending(&mut self, task: &impl TaskGuard) {
fn check_optimization_pending(&mut self, task: &TaskGuard<'_>) {
if !task.optimization_pending() {
// Common case: nothing pending, no work to do.
return;
......@@ -1061,7 +1061,7 @@ impl AggregationUpdateQueue {
}
/// Runs the job and all dependent jobs until it's done.
pub fn run(job: AggregationUpdateJob, ctx: &mut impl ExecuteContext<'_>) {
pub fn run(job: AggregationUpdateJob, ctx: &mut ExecuteContext<'_>) {
let mut queue = Self::new();
queue.push(job);
queue.execute(ctx);
......@@ -1120,7 +1120,7 @@ impl AggregationUpdateQueue {
pub fn extend_balance_edges(
&mut self,
edges: impl IntoIterator<Item = (TaskId, TaskId)>,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
) {
for (upper_id, task_id) in edges {
// structure as 2 if statements to ensure the first guard is dropped before the second
......@@ -1136,7 +1136,7 @@ impl AggregationUpdateQueue {
}
/// Executes a single step of the queue. Returns true, when the queue is empty.
pub fn process(&mut self, ctx: &mut impl ExecuteContext<'_>) -> bool {
pub fn process(&mut self, ctx: &mut ExecuteContext<'_>) -> bool {
if let Some(job) = self.jobs.pop_front() {
let job: AggregationUpdateJobGuard = job.entered();
match job.job {
......@@ -1630,7 +1630,7 @@ impl AggregationUpdateQueue {
/// triggers more changes to the structure.
///
/// It locks both tasks simultaneously to atomically change the edges.
fn balance_edge(&mut self, ctx: &mut impl ExecuteContext, upper_id: TaskId, task_id: TaskId) {
fn balance_edge(&mut self, ctx: &mut ExecuteContext<'_>, upper_id: TaskId, task_id: TaskId) {
#[cfg(feature = "trace_aggregation_update")]
let _span = trace_span!("process balance edge").entered();
......@@ -1802,7 +1802,7 @@ impl AggregationUpdateQueue {
fn find_and_schedule_dirty(
&mut self,
jobs: SmallVec<[FindAndScheduleJob; 4]>,
ctx: &mut impl ExecuteContext,
ctx: &mut ExecuteContext<'_>,
) {
#[cfg(feature = "trace_find_and_schedule")]
let mut spans: FxHashMap<TaskId, Option<Span>> = jobs
......@@ -1831,8 +1831,8 @@ impl AggregationUpdateQueue {
fn find_and_schedule_dirty_internal(
&mut self,
task_id: TaskId,
mut task: impl TaskGuard,
ctx: &mut impl ExecuteContext<'_>,
mut task: TaskGuard<'_>,
ctx: &mut ExecuteContext<'_>,
) {
// Task need to be scheduled if it's dirty or doesn't have output
let dirty = task.is_dirty();
......@@ -1873,7 +1873,7 @@ impl AggregationUpdateQueue {
fn aggregated_data_update(
&mut self,
upper_ids: TaskIdVec,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
update: AggregatedDataUpdate,
) {
// For performance reasons this should stay `Meta` and not `All`
......@@ -1901,7 +1901,7 @@ impl AggregationUpdateQueue {
fn inner_of_upper_lost_follower(
&mut self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
lost_follower_id: TaskId,
upper_id: TaskId,
mut retry: u16,
......@@ -2079,7 +2079,7 @@ impl AggregationUpdateQueue {
fn inner_of_uppers_lost_follower(
&mut self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
lost_follower_id: TaskId,
mut upper_ids: TaskIdVec,
mut retry: u16,
......@@ -2272,7 +2272,7 @@ impl AggregationUpdateQueue {
fn inner_of_upper_lost_followers(
&mut self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
mut lost_follower_ids: TaskIdVec,
upper_id: TaskId,
mut retry: u16,
......@@ -2468,7 +2468,7 @@ impl AggregationUpdateQueue {
/// See detailed comments in that function, follow the STEP numbers.
fn inner_of_uppers_has_new_follower<T: TaskIdWithOptionalCount + Clone, const N: usize>(
&mut self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
new_follower_id: TaskId,
mut upper_ids: SmallVec<[T; N]>,
) {
......@@ -2714,7 +2714,7 @@ impl AggregationUpdateQueue {
/// See detailed comments in that function, follow the STEP numbers.
fn inner_of_upper_has_new_followers<T: TaskIdWithOptionalCount, const N: usize>(
&mut self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
new_follower_ids: SmallVec<[T; N]>,
upper_id: TaskId,
) {
......@@ -2975,7 +2975,7 @@ impl AggregationUpdateQueue {
fn inner_of_upper_has_new_follower(
&mut self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
new_follower_id: TaskId,
upper_id: TaskId,
count: u32,
......@@ -3157,7 +3157,7 @@ impl AggregationUpdateQueue {
/// Decreases the active count of a task.
///
/// Only used when activeness is tracked.
fn decrease_active_count(&mut self, ctx: &mut impl ExecuteContext<'_>, task_id: TaskId) {
fn decrease_active_count(&mut self, ctx: &mut ExecuteContext<'_>, task_id: TaskId) {
#[cfg(feature = "trace_aggregation_update")]
let _span = trace_span!("decrease active count").entered();
......@@ -3204,7 +3204,7 @@ impl AggregationUpdateQueue {
/// Only used when activeness is tracked.
fn increase_active_count(
&mut self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
task_id: TaskId,
release_construction_ref: bool,
) {
......@@ -3256,7 +3256,7 @@ impl AggregationUpdateQueue {
fn update_aggregation_number(
&mut self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
task_id: TaskId,
base_effective_distance: Option<std::num::NonZero<u32>>,
base_aggregation_number: u32,
......@@ -3360,7 +3360,7 @@ impl AggregationUpdateQueue {
/// does so); when `false`, the flag is known to be unset already and we can skip the write.
fn optimize_task(
&mut self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
task_id: TaskId,
optimization_pending_flag_already_set: bool,
) {
......@@ -3505,7 +3505,7 @@ impl AggregationUpdateQueue {
#[cfg(feature = "trace_aggregation_update_stats")]
pub fn execute_with_stats(
&mut self,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
) -> AggregationUpdateQueueStats {
while !self.process(ctx) {}
take(&mut self.stats)
......@@ -3513,7 +3513,7 @@ impl AggregationUpdateQueue {
}
impl AggregationUpdateQueue {
pub fn execute(&mut self, ctx: &mut impl ExecuteContext<'_>) {
pub fn execute(&mut self, ctx: &mut ExecuteContext<'_>) {
while !self.process(ctx) {}
}
}
......
......@@ -91,7 +91,7 @@ pub fn cleanup_old_edges(
task_id: TaskId,
outdated: Vec<OutdatedEdge>,
queue: AggregationUpdateQueue,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
) -> Stats {
cleanup_old_edges_inner(task_id, outdated, queue, ctx, false).0
}
......@@ -102,10 +102,10 @@ pub fn cleanup_old_edges(
/// parallel collect is quiescent. Deletion is safe to run concurrently; the deferred work is
/// not. `balance_edge` *adds* edges, and dirtying propagates through the aggregation graph --
/// neither is safe while other workers are still collecting.
pub fn cleanup_old_edges_deletions_only<'a, C: ExecuteContext<'a>>(
pub fn cleanup_old_edges_deletions_only(
task_id: TaskId,
outdated: Vec<OutdatedEdge>,
ctx: &mut C,
ctx: &mut ExecuteContext<'_>,
) -> DeferredCleanup {
let (_, stopped) = cleanup_old_edges_inner(
task_id,
......@@ -122,7 +122,7 @@ fn cleanup_old_edges_inner(
task_id: TaskId,
mut outdated: Vec<OutdatedEdge>,
mut queue: AggregationUpdateQueue,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
stop_when_only_rebalance_remains: bool,
) -> (Stats, Option<DeferredCleanup>) {
let mut dirty_dependents = AutoSet::default();
......
......@@ -20,12 +20,12 @@ use crate::{
/// connect handshake.
///
/// GC destructively mutates tasks so mark resurrected tasks as dirty to get them re-scheduled.
pub(super) fn resurrect_deleted<'e, C: ExecuteContext<'e>>(
guard: C::TaskGuardImpl,
pub(super) fn resurrect_deleted<'e>(
guard: TaskGuard<'e>,
task_id: TaskId,
queue: &mut AggregationUpdateQueue,
ctx: &mut C,
) -> C::TaskGuardImpl {
ctx: &mut ExecuteContext<'e>,
) -> TaskGuard<'e> {
if !guard.deleted() {
return guard;
}
......@@ -64,7 +64,7 @@ pub(super) fn resurrect_deleted<'e, C: ExecuteContext<'e>>(
task
}
fn release_construction_ref<'e, C: ExecuteContext<'e>>(task_id: TaskId, ctx: &mut C) {
fn release_construction_ref(task_id: TaskId, ctx: &mut ExecuteContext<'_>) {
let mut task = ctx.task(task_id, TaskDataCategory::Meta);
task.update_and_get_transient_ref_count(-1);
}
......@@ -73,7 +73,7 @@ pub fn connect_child(
parent_task_id: Option<TaskId>,
child_task_id: TaskId,
release_construction_ref: bool,
mut ctx: impl ExecuteContext<'_>,
mut ctx: ExecuteContext<'_>,
) {
if parent_task_id.is_none() {
// All parentless tasks receive a transient ref when connected: their lifetime cannot be
......
......@@ -10,17 +10,17 @@ use turbo_tasks::{
use crate::backend::{
operation::{
AggregationUpdateJob, AggregationUpdateQueue, ChildExecuteContext, ExecuteContext,
TaskGuard, aggregation_update::InnerOfUppersHasNewFollowersJob, get_aggregation_number,
get_uppers, invalidate::make_task_dirty_internal, is_aggregating_node,
AggregationUpdateJob, AggregationUpdateQueue, ExecuteContext, TaskGuard,
aggregation_update::InnerOfUppersHasNewFollowersJob, get_aggregation_number, get_uppers,
invalidate::make_task_dirty_internal, is_aggregating_node,
},
storage_schema::TaskStorageAccessors,
};
pub fn connect_children(
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
parent_task_id: TaskId,
mut parent_task: impl TaskGuard,
mut parent_task: TaskGuard<'_>,
new_children: FxHashSet<TaskId>,
parent_has_active_count: bool,
should_track_activeness: bool,
......@@ -46,7 +46,7 @@ pub fn connect_children(
drop(parent_task);
fn process_new_children(
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
new_follower_ids: SmallVec<[TaskId; 4]>,
upper_ids: Option<SmallVec<[TaskId; 4]>>,
parent_task_id: TaskId,
......
......@@ -20,7 +20,7 @@ use crate::{
pub fn invalidate(
task_ids: SmallVec<[TaskId; 4]>,
#[cfg(feature = "task_dirty_cause")] cause: TaskDirtyCause,
mut ctx: impl ExecuteContext<'_>,
mut ctx: ExecuteContext<'_>,
) {
let mut queue = AggregationUpdateQueue::new();
for task_id in task_ids {
......@@ -42,7 +42,7 @@ pub fn try_make_task_dirty(
task_id: TaskId,
#[cfg(feature = "task_dirty_cause")] cause: TaskDirtyCause,
queue: &mut AggregationUpdateQueue,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
) {
let Some(mut task) = ctx.try_task(task_id, TaskDataCategory::All) else {
return;
......@@ -58,12 +58,12 @@ pub fn try_make_task_dirty(
}
/// Requires the guard to be allocated with [TaskDataCategory::All]
pub fn make_task_dirty_internal<'e, E: ExecuteContext<'e>>(
task: &mut E::TaskGuardImpl,
pub fn make_task_dirty_internal(
task: &mut TaskGuard<'_>,
make_stale: bool,
#[cfg(feature = "task_dirty_cause")] cause: TaskDirtyCause,
queue: &mut AggregationUpdateQueue,
ctx: &mut E,
ctx: &mut ExecuteContext<'_>,
) {
// There must be no way to invalidate immutable tasks. If there would be a way the task is not
// immutable.
......
......@@ -85,7 +85,7 @@ impl LeafDistanceUpdateQueue {
}
/// Executes a single step of the queue. Returns true, when the queue is empty.
pub fn process(&mut self, ctx: &mut impl ExecuteContext) -> bool {
pub fn process(&mut self, ctx: &mut ExecuteContext<'_>) -> bool {
let mut remaining = MAX_COUNT_BEFORE_YIELD;
while remaining > 0 {
if let Some((Reverse(queue_dependencies_distance), task_id)) = self.queue.pop() {
......@@ -121,7 +121,7 @@ impl LeafDistanceUpdateQueue {
fn update_leaf_distance(
&mut self,
ctx: &mut impl ExecuteContext,
ctx: &mut ExecuteContext<'_>,
task_id: TaskId,
dependencies_distance: u32,
dependencies_max_distance_in_buffer: u32,
......@@ -169,7 +169,7 @@ impl LeafDistanceUpdateQueue {
task.set_leaf_distance(leaf_distance);
}
pub fn execute(&mut self, ctx: &mut impl ExecuteContext<'_>) {
pub fn execute(&mut self, ctx: &mut ExecuteContext<'_>) {
if self.is_empty() {
return;
}
......
......@@ -55,129 +55,6 @@ enum TaskAccess {
AllowMissing,
}
// TODO: consider removing this trait (and `TaskGuard`) in favor of the concrete types. Each has
// exactly one implementation (`ExecuteContextImpl` / `TaskGuardImpl`), so the abstraction buys
// nothing and just adds declaration overhead and extra generic plumbing.
pub trait ExecuteContext<'e>: Sized {
type TaskGuardImpl: TaskGuard + 'e;
fn child_context<'l, 'r>(&'r self) -> impl ChildExecuteContext<'l> + use<'e, 'l, Self>
where
'e: 'l;
/// Opens a task that must **already exist**, restoring the requested `category` if needed. A
/// missing requested category in memory and on disk is a stale reference, so this panics
/// rather than fabricate a blank. This is the common case; use
/// [`Self::task_or_create`] only where the task may be getting materialized for
/// the first time.
///
/// A transient task (or any task, without backing storage) is restored from creation and never
/// evicted, so one that is not restored exists nowhere. See `ExecuteContextImpl::open_task`.
fn task(&mut self, task_id: TaskId, category: TaskDataCategory) -> Self::TaskGuardImpl;
/// Opens a task that may legitimately be gone, returning `None` if it is.
///
/// Gone covers a missing requested category as well as a soft-deleted task: the caller cannot
/// tell those apart, since only the timing of the next eviction separates them.
fn try_task(
&mut self,
task_id: TaskId,
category: TaskDataCategory,
) -> Option<Self::TaskGuardImpl>;
/// Opens a task, materializing an in-memory storage entry for it if one is not resident yet
/// (inserting a blank, then restoring `category` from disk if present). Use only where the
/// task's storage may not be resident: the first connect of a freshly-minted child (threads can
/// race to first-touch it).
///
/// This creates *storage for* an already-minted `TaskId`; it does not mint one. Compare
/// `TurboTasksBackend::get_or_create_task`, which takes a function and arguments and returns a
/// `TaskId` (reusing one if the task is already cached).
fn task_or_create(
&mut self,
task_id: TaskId,
category: TaskDataCategory,
) -> Self::TaskGuardImpl;
/// Prepares (as in fetches from persistent storage) a list of tasks.
/// The iterator should not have duplicates, as this would cause over-fetching.
///
/// Like [`Self::task`], a missing requested category makes the task invalid and panics.
fn prepare_tasks(
&mut self,
task_ids: impl IntoIterator<Item = (TaskId, TaskDataCategory)>,
reason: &'static str,
);
/// Opens each task like [`Self::task`] (so every task must already exist), batching the reads
/// from persistent storage.
fn for_each_task(
&mut self,
task_ids: impl IntoIterator<Item = (TaskId, TaskDataCategory)>,
reason: &'static str,
func: impl FnMut(Self::TaskGuardImpl, &mut Self),
);
fn for_each_task_meta(
&mut self,
task_ids: impl IntoIterator<Item = TaskId>,
reason: &'static str,
func: impl FnMut(Self::TaskGuardImpl, &mut Self),
) {
self.for_each_task(
task_ids.into_iter().map(|id| (id, TaskDataCategory::Meta)),
reason,
func,
)
}
fn for_each_task_all(
&mut self,
task_ids: impl IntoIterator<Item = TaskId>,
reason: &'static str,
func: impl FnMut(Self::TaskGuardImpl, &mut Self),
) {
self.for_each_task(
task_ids.into_iter().map(|id| (id, TaskDataCategory::All)),
reason,
func,
)
}
/// Opens two tasks that must **already exist** under a single lock acquisition (to atomically
/// read/mutate an edge between them). Both ids are opened `MustExist` — an edge only exists
/// between already-materialized tasks.
fn task_pair(
&mut self,
task_id1: TaskId,
task_id2: TaskId,
category: TaskDataCategory,
) -> (Self::TaskGuardImpl, Self::TaskGuardImpl);
fn schedule_task(&self, task: &Self::TaskGuardImpl, parent_priority: TaskPriority);
fn get_current_task_priority(&self) -> TaskPriority;
/// Record `task` as a GC candidate **if it is in fact collectible**.
///
/// Call this wherever an operation removes the last reference of some kind to a task. This may
/// be a transition to collectibility.
///
/// Only effective in a gc context see [`Self::collects_gc_candidates`].
fn note_maybe_collectible(&mut self, task: &impl TaskGuard);
fn should_track_dependencies(&self) -> bool;
fn should_track_activeness(&self) -> bool;
fn turbo_tasks(&self) -> Arc<dyn TurboTasksCallApi>;
/// Look up a TaskId from the backing storage for a given task type.
///
/// Uses hash-based lookup which may return multiple candidates due to hash collisions,
/// then verifies each candidate by comparing the stored `persistent_task_type`.
/// Returns `Some((task_id, task_type))` if a matching task is found, where `task_type` is
/// the existing `CachedTaskTypeArc` from storage (avoiding a duplicate
/// allocation).
///
/// Accepts exploded components so the caller does not need to box the argument before calling.
fn task_by_type(
&mut self,
native_fn: &'static NativeFunction,
this: Option<RawVc>,
arg: &dyn DynTaskInputs,
) -> Option<(TaskId, CachedTaskTypeArc)>;
fn debug_get_task_description(&self, task_id: TaskId) -> String;
}
pub trait ChildExecuteContext<'e>: Send + Sized {
fn create(self) -> impl ExecuteContext<'e>;
}
/// Counter that tracks how many task guards are alive, detecting concurrent access.
///
/// In release builds all methods are no-ops and the struct is zero-sized, so there is no runtime
......@@ -224,7 +101,7 @@ impl TaskLockCounter {
}
}
pub struct ExecuteContextImpl<'e> {
pub struct ExecuteContext<'e> {
backend: &'e TurboTasksBackend,
turbo_tasks: &'e TurboTasks<TurboTasksBackend>,
gc_collectible: Option<&'e dyn Fn(TaskId)>,
......@@ -236,7 +113,7 @@ pub struct ExecuteContextImpl<'e> {
task_lock_counter: TaskLockCounter,
}
impl<'e> ExecuteContextImpl<'e> {
impl<'e> ExecuteContext<'e> {
pub(super) fn new(
backend: &'e TurboTasksBackend,
turbo_tasks: &'e TurboTasks<TurboTasksBackend>,
......@@ -251,7 +128,7 @@ impl<'e> ExecuteContextImpl<'e> {
}
}
/// Like [`ExecuteContextImpl::new`], but owns the shutdown read guard that
/// Like [`ExecuteContext::new`], but owns the shutdown read guard that
/// [`TurboTasksBackend::try_execute_context`] acquired, keeping `stop()` out until this
/// context is dropped.
pub(super) fn new_with_shutdown_guard(
......@@ -296,7 +173,7 @@ impl<'e> ExecuteContextImpl<'e> {
task_id: TaskId,
category: TaskDataCategory,
access: TaskAccess,
) -> Option<TaskGuardImpl<'e>> {
) -> Option<TaskGuard<'e>> {
self.task_lock_counter.acquire();
let mut task = self.backend.storage.access_entry_mut(task_id);
......@@ -306,7 +183,7 @@ impl<'e> ExecuteContextImpl<'e> {
return None;
}
if task.flags.is_restored(category) {
return Some(TaskGuardImpl::new(
return Some(TaskGuard::new(
task.into_write_guard(),
task_id,
category,
......@@ -319,7 +196,7 @@ impl<'e> ExecuteContextImpl<'e> {
// restored was never created or has been collected.
if access == TaskAccess::MaybeCreate {
task.flags.set_restored(TaskDataCategory::All);
return Some(TaskGuardImpl::new(
return Some(TaskGuard::new(
task.into_write_guard(),
task_id,
category,
......@@ -341,7 +218,7 @@ impl<'e> ExecuteContextImpl<'e> {
self.task_lock_counter.release();
return None;
}
Some(TaskGuardImpl::new(
Some(TaskGuard::new(
task.into_write_guard(),
task_id,
category,
......@@ -898,7 +775,7 @@ struct TaskRestoreEntry {
self_restored: bool,
}
/// Outcome of [`ExecuteContextImpl::restore_task`].
/// Outcome of [`ExecuteContext::restore_task`].
struct RestoreOutcome {
/// A requested category was absent on disk; the task is invalid under MustExist/AllowMissing.
missing_on_disk: bool,
......@@ -943,7 +820,7 @@ fn panic_missing_task(task_id: TaskId, reason: &str) -> ! {
/// The priority a task is scheduled with: an already computed task is a re-computation of a
/// (possibly deep) dependency, everything else starts at the initial priority.
fn schedule_priority(task: &impl TaskGuard, parent_priority: TaskPriority) -> TaskPriority {
fn schedule_priority(task: &TaskGuard<'_>, parent_priority: TaskPriority) -> TaskPriority {
let priority = if task.has_output() {
TaskPriority::invalidation(
task.get_leaf_distance()
......@@ -993,42 +870,60 @@ fn apply_restore_result(
}
}
impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
type TaskGuardImpl = TaskGuardImpl<'e>;
fn child_context<'l, 'r>(&'r self) -> impl ChildExecuteContext<'l> + use<'e, 'l>
impl<'e> ExecuteContext<'e> {
pub fn child_context<'l>(&self) -> ChildExecuteContext<'l>
where
'e: 'l,
{
ChildExecuteContextImpl {
ChildExecuteContext {
backend: self.backend,
turbo_tasks: self.turbo_tasks,
}
}
fn task(&mut self, task_id: TaskId, category: TaskDataCategory) -> Self::TaskGuardImpl {
/// Opens a task that must **already exist**, restoring the requested `category` if needed. A
/// missing requested category in memory and on disk is a stale reference, so this panics
/// rather than fabricate a blank. This is the common case; use
/// [`Self::task_or_create`] only where the task may be getting materialized for
/// the first time.
///
/// A transient task (or any task, without backing storage) is restored from creation and never
/// evicted, so one that is not restored exists nowhere. See `ExecuteContext::open_task`.
pub fn task(&mut self, task_id: TaskId, category: TaskDataCategory) -> TaskGuard<'e> {
self.open_task(task_id, category, TaskAccess::MustExist)
.expect("a MustExist open either yields a task or panics")
}
fn try_task(
/// Opens a task that may legitimately be gone, returning `None` if it is.
///
/// Gone covers a missing requested category as well as a soft-deleted task: the caller cannot
/// tell those apart, since only the timing of the next eviction separates them.
pub fn try_task(
&mut self,
task_id: TaskId,
category: TaskDataCategory,
) -> Option<Self::TaskGuardImpl> {
) -> Option<TaskGuard<'e>> {
self.open_task(task_id, category, TaskAccess::AllowMissing)
}
fn task_or_create(
&mut self,
task_id: TaskId,
category: TaskDataCategory,
) -> Self::TaskGuardImpl {
/// Opens a task, materializing an in-memory storage entry for it if one is not resident yet
/// (inserting a blank, then restoring `category` from disk if present). Use only where the
/// task's storage may not be resident: the first connect of a freshly-minted child (threads can
/// race to first-touch it).
///
/// This creates *storage for* an already-minted `TaskId`; it does not mint one. Compare
/// `TurboTasksBackend::get_or_create_task`, which takes a function and arguments and returns a
/// `TaskId` (reusing one if the task is already cached).
pub fn task_or_create(&mut self, task_id: TaskId, category: TaskDataCategory) -> TaskGuard<'e> {
self.open_task(task_id, category, TaskAccess::MaybeCreate)
.expect("a MaybeCreate open always yields a task")
}
fn prepare_tasks(
/// Prepares (as in fetches from persistent storage) a list of tasks.
/// The iterator should not have duplicates, as this would cause over-fetching.
///
/// Like [`Self::task`], a missing requested category makes the task invalid and panics.
pub fn prepare_tasks(
&mut self,
task_ids: impl IntoIterator<Item = (TaskId, TaskDataCategory)>,
reason: &'static str,
......@@ -1036,30 +931,61 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
self.prepare_tasks_with_callback(task_ids, reason, |_, _, _, _| {});
}
fn for_each_task(
/// Opens each task like [`Self::task`] (so every task must already exist), batching the reads
/// from persistent storage.
pub fn for_each_task(
&mut self,
task_ids: impl IntoIterator<Item = (TaskId, TaskDataCategory)>,
reason: &'static str,
mut func: impl FnMut(Self::TaskGuardImpl, &mut Self),
mut func: impl FnMut(TaskGuard<'e>, &mut Self),
) {
let task_lock_counter = self.task_lock_counter.clone();
self.prepare_tasks_with_callback(task_ids, reason, |this, task_id, _category, task| {
// prepare_tasks_with_callback releases the counter before calling this callback,
// so the counter is 0 here. Acquire for the TaskGuardImpl that will release on
// so the counter is 0 here. Acquire for the TaskGuard that will release on
// Drop.
task_lock_counter.acquire();
let guard = TaskGuardImpl::new(task, task_id, _category, task_lock_counter.clone());
let guard = TaskGuard::new(task, task_id, _category, task_lock_counter.clone());
func(guard, this);
});
}
fn task_pair(
pub fn for_each_task_meta(
&mut self,
task_ids: impl IntoIterator<Item = TaskId>,
reason: &'static str,
func: impl FnMut(TaskGuard<'e>, &mut Self),
) {
self.for_each_task(
task_ids.into_iter().map(|id| (id, TaskDataCategory::Meta)),
reason,
func,
)
}
pub fn for_each_task_all(
&mut self,
task_ids: impl IntoIterator<Item = TaskId>,
reason: &'static str,
func: impl FnMut(TaskGuard<'e>, &mut Self),
) {
self.for_each_task(
task_ids.into_iter().map(|id| (id, TaskDataCategory::All)),
reason,
func,
)
}
/// Opens two tasks that must **already exist** under a single lock acquisition (to atomically
/// read/mutate an edge between them). Both ids are opened `MustExist` — an edge only exists
/// between already-materialized tasks.
pub fn task_pair(
&mut self,
task_id1: TaskId,
task_id2: TaskId,
category: TaskDataCategory,
) -> (Self::TaskGuardImpl, Self::TaskGuardImpl) {
) -> (TaskGuard<'e>, TaskGuard<'e>) {
self.task_lock_counter.acquire_multiple(2);
// `task_pair` is always a `MustExist` open (both endpoints of an existing edge). Each task
......@@ -1110,40 +1036,55 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
};
(
TaskGuardImpl::new(task1, task_id1, category, self.task_lock_counter.clone()),
TaskGuardImpl::new(task2, task_id2, category, self.task_lock_counter.clone()),
TaskGuard::new(task1, task_id1, category, self.task_lock_counter.clone()),
TaskGuard::new(task2, task_id2, category, self.task_lock_counter.clone()),
)
}
fn schedule_task(&self, task: &Self::TaskGuardImpl, parent_priority: TaskPriority) {
pub fn schedule_task(&self, task: &TaskGuard<'e>, parent_priority: TaskPriority) {
let priority = schedule_priority(task, parent_priority);
self.turbo_tasks.schedule(task.id(), priority);
}
fn get_current_task_priority(&self) -> TaskPriority {
pub fn get_current_task_priority(&self) -> TaskPriority {
self.turbo_tasks.get_current_task_priority()
}
fn note_maybe_collectible(&mut self, task: &impl TaskGuard) {
/// Record `task` as a GC candidate **if it is in fact collectible**.
///
/// Call this wherever an operation removes the last reference of some kind to a task. This may
/// be a transition to collectibility.
///
/// Only effective in a GC context.
pub fn note_maybe_collectible(&mut self, task: &TaskGuard<'_>) {
if let Some(collector) = self.gc_collectible
&& task.is_gc_collectible()
{
collector(task.id());
}
}
fn should_track_dependencies(&self) -> bool {
pub fn should_track_dependencies(&self) -> bool {
self.backend.should_track_dependencies()
}
fn should_track_activeness(&self) -> bool {
pub fn should_track_activeness(&self) -> bool {
self.backend.should_track_activeness()
}
fn turbo_tasks(&self) -> Arc<dyn TurboTasksCallApi> {
pub fn turbo_tasks(&self) -> Arc<dyn TurboTasksCallApi> {
self.turbo_tasks.pin()
}
fn task_by_type(
/// Look up a TaskId from the backing storage for a given task type.
///
/// Uses hash-based lookup which may return multiple candidates due to hash collisions,
/// then verifies each candidate by comparing the stored `persistent_task_type`.
/// Returns `Some((task_id, task_type))` if a matching task is found, where `task_type` is
/// the existing `CachedTaskTypeArc` from storage (avoiding a duplicate
/// allocation).
///
/// Accepts exploded components so the caller does not need to box the argument before calling.
pub fn task_by_type(
&mut self,
native_fn: &'static NativeFunction,
this: Option<RawVc>,
......@@ -1173,19 +1114,19 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
None
}
fn debug_get_task_description(&self, task_id: TaskId) -> String {
pub fn debug_get_task_description(&self, task_id: TaskId) -> String {
self.backend.debug_get_task_description(task_id)
}
}
struct ChildExecuteContextImpl<'e> {
pub struct ChildExecuteContext<'e> {
backend: &'e TurboTasksBackend,
turbo_tasks: &'e TurboTasks<TurboTasksBackend>,
}
impl<'e> ChildExecuteContext<'e> for ChildExecuteContextImpl<'e> {
fn create(self) -> impl ExecuteContext<'e> {
ExecuteContextImpl {
impl<'e> ChildExecuteContext<'e> {
pub fn create(self) -> ExecuteContext<'e> {
ExecuteContext {
backend: self.backend,
turbo_tasks: self.turbo_tasks,
gc_collectible: None,
......@@ -1236,18 +1177,50 @@ impl Display for TaskType {
}
}
pub trait TaskGuard: Debug + TaskStorageAccessors {
fn id(&self) -> TaskId;
#[cfg(debug_assertions)]
fn access(&self) -> TaskDataCategory;
pub struct TaskGuard<'a> {
task_id: TaskId,
task: StorageWriteGuard<'a>,
// None means no categories are accessible other than transient data.
#[cfg(debug_assertions)]
fn downgrade_access(&mut self, access: TaskDataCategory);
category: TaskDataCategory,
task_lock_counter: TaskLockCounter,
}
impl Drop for TaskGuard<'_> {
fn drop(&mut self) {
self.task_lock_counter.release();
}
}
impl Debug for TaskGuard<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("TaskGuard");
d.field("task_id", &self.task_id);
d.field("storage", &*self.task);
d.finish()
}
}
impl<'a> TaskGuard<'a> {
fn new(
task: StorageWriteGuard<'a>,
task_id: TaskId,
#[allow(unused_variables)] category: TaskDataCategory,
task_lock_counter: TaskLockCounter,
) -> Self {
Self {
task,
task_id,
#[cfg(debug_assertions)]
category,
task_lock_counter,
}
}
/// Asserts this task has not been GC-collected.
#[track_caller]
#[inline]
fn assert_not_deleted(&self, operation: &str) {
pub fn assert_not_deleted(&self, operation: &str) {
debug_assert!(
!self.deleted(),
"{operation} on GC-deleted task {} — a resurrection path was missed",
......@@ -1255,21 +1228,12 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
);
}
/// Clears all modified/new flags for a GC-collected task that was **never persisted**
/// (`new_task`).
fn discard_modifications_for_gc_new_task(&mut self);
/// Get mutable reference to the activeness state, inserting a new one if not present
fn get_activeness_mut_or_insert_with<F>(&mut self, f: F) -> &mut ActivenessState
where
F: FnOnce() -> ActivenessState;
// ============ Aggregated Container Count (scalar) APIs ============
// These are for the scalar total count fields, not the CounterMap per-task fields.
/// Update the aggregated dirty container count (the scalar total count field) by the given
/// delta and return the new value.
fn update_and_get_aggregated_dirty_container_count(&mut self, delta: i32) -> i32 {
pub fn update_and_get_aggregated_dirty_container_count(&mut self, delta: i32) -> i32 {
let current = self
.get_aggregated_dirty_container_count()
.copied()
......@@ -1285,7 +1249,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
/// Update the aggregated current session clean container count (the scalar total count field)
/// by the given delta and return the new value.
fn update_and_get_aggregated_current_session_clean_container_count(
pub fn update_and_get_aggregated_current_session_clean_container_count(
&mut self,
delta: i32,
) -> i32 {
......@@ -1305,7 +1269,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
/// Adjust the count of persistent parents referencing this task by `delta`
///
/// Panics on underflow/overflow
fn update_and_get_parent_count(&mut self, delta: i32) -> u32 {
pub fn update_and_get_parent_count(&mut self, delta: i32) -> u32 {
let current = self.get_parent_count().copied().unwrap_or(0);
let new_value = current
.checked_add_signed(delta)
......@@ -1317,7 +1281,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
/// Like [`Self::update_and_get_parent_count`], but for the transient (session-only) parent
/// reference count
/// Panics on underflow/overflow.
fn update_and_get_transient_ref_count(&mut self, delta: i32) -> u32 {
pub fn update_and_get_transient_ref_count(&mut self, delta: i32) -> u32 {
let current = self.get_transient_ref_count().copied().unwrap_or(0);
let new_value = current
.checked_add_signed(delta)
......@@ -1327,18 +1291,12 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
}
/// Whether a GC pass may collect this task: nothing references it.
fn is_gc_collectible(&self) -> bool {
pub fn is_gc_collectible(&self) -> bool {
self.check_access(SpecificTaskDataCategory::Meta);
self.typed().gc_collectible()
}
fn invalidate_serialization(&mut self);
/// Determine which tasks to prefetch for a task.
/// Only returns Some once per task.
/// It returns a set of tasks and which info is needed.
fn prefetch(&mut self) -> Option<FxIndexMap<TaskId, TaskDataCategory>>;
fn is_dirty(&self) -> Option<TaskPriority> {
pub fn is_dirty(&self) -> Option<TaskPriority> {
self.get_dirty().and_then(|dirtyness| match dirtyness {
Dirtyness::Dirty {
parent_priority, ..
......@@ -1353,7 +1311,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
})
}
/// Returns (is_dirty, is_clean_in_current_session)
fn dirty_state(&self) -> (bool, bool) {
pub fn dirty_state(&self) -> (bool, bool) {
match self.get_dirty() {
None => (false, false),
Some(Dirtyness::Dirty { .. }) => (true, false),
......@@ -1366,13 +1324,10 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
///
/// Returns an optional `AggregationUpdateJob` that the caller must run via
/// `AggregationUpdateQueue::run` to propagate the change to aggregating ancestors.
fn update_dirty_state(
pub fn update_dirty_state(
&mut self,
new_dirtyness: Option<Dirtyness>,
) -> Option<AggregationUpdateJob>
where
Self: Sized,
{
) -> Option<AggregationUpdateJob> {
let task_id = self.id();
let old_dirtyness = self.get_dirty().cloned();
let (old_self_dirty, old_current_session_self_clean) = self.dirty_state();
......@@ -1431,11 +1386,11 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
AggregationUpdateJob::data_update(self, aggregated_update)
})
}
fn dirty_containers(&self) -> impl Iterator<Item = TaskId> {
pub fn dirty_containers(&self) -> impl Iterator<Item = TaskId> {
self.dirty_containers_with_count()
.map(|(task_id, _)| task_id)
}
fn dirty_containers_with_count(&self) -> impl Iterator<Item = (TaskId, i32)> + '_ {
pub fn dirty_containers_with_count(&self) -> impl Iterator<Item = (TaskId, i32)> + '_ {
let dirty_map = self.aggregated_dirty_containers();
let clean_map = self.aggregated_current_session_clean_containers();
dirty_map.into_iter().flat_map(move |map| {
......@@ -1454,7 +1409,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
})
}
fn has_dirty_containers(&self) -> bool {
pub fn has_dirty_containers(&self) -> bool {
let dirty_count = self
.get_aggregated_dirty_container_count()
.copied()
......@@ -1469,7 +1424,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
dirty_count > clean_count
}
/// Insert cell data, returning the old value if present.
fn insert_cell_data(
pub fn insert_cell_data(
&mut self,
cell: CellId,
value: SharedReference,
......@@ -1486,7 +1441,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
self.typed_mut().cell_data_mut().insert(cell, value)
}
fn take_cell_data(&mut self) -> Option<CellData> {
pub fn take_cell_data(&mut self) -> Option<CellData> {
self.check_access(SpecificTaskDataCategory::Data);
let undoable = self.track_modification(SpecificTaskDataCategory::Data, "cell_data");
let prev = self.typed_mut().take_cell_data();
......@@ -1497,7 +1452,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
prev
}
/// Remove cell data, returning the old value if present.
fn remove_cell_data(
pub fn remove_cell_data(
&mut self,
cell: &CellId,
persistence: &ValueTypePersistence,
......@@ -1521,7 +1476,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
/// Add new cell data. Panics if the cell already had a value. See
/// [`insert_cell_data`](Self::insert_cell_data) for the tracking rationale.
fn add_cell_data(
pub fn add_cell_data(
&mut self,
cell: CellId,
value: SharedReference,
......@@ -1534,7 +1489,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
/// Add a scheduled task item. Returns true if the task was successfully added (wasn't already
/// present).
#[must_use]
fn add_scheduled(
pub fn add_scheduled(
&mut self,
reason: TaskExecutionReason,
description: EventDescription,
......@@ -1549,7 +1504,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
/// Insert an outdated collectible with count. Returns true if it was newly inserted.
#[must_use]
fn insert_outdated_collectible(&mut self, collectible: CollectibleRef, value: i32) -> bool {
pub fn insert_outdated_collectible(&mut self, collectible: CollectibleRef, value: i32) -> bool {
// Check if already exists
if self.get_outdated_collectibles(&collectible).is_some() {
return false;
......@@ -1558,7 +1513,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
self.add_outdated_collectibles(collectible, value);
true
}
fn get_task_type(&self) -> TaskTypeRef<'_> {
pub fn get_task_type(&self) -> TaskTypeRef<'_> {
if let Some(task_type) = self.get_persistent_task_type() {
TaskTypeRef::Cached(task_type)
} else if let Some(task_type) = self.get_transient_task_type() {
......@@ -1571,7 +1526,7 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
/// A description of this task for diagnostics: `"<id> <task type>"`.
///
/// Is intentionally tolerant of non-resident data.
fn get_task_desc_fn(&self) -> impl Fn() -> String + Send + Sync + 'static {
pub fn get_task_desc_fn(&self) -> impl Fn() -> String + Send + Sync + 'static {
// Bypass `check_access`!!
// Generally it is a bad idea since accessing a `Data` field like get_persistence_task_type
// without opening the task that way is bug But this is for diagnostics and
......@@ -1593,49 +1548,17 @@ pub trait TaskGuard: Debug + TaskStorageAccessors {
}
}
// Requires the task to have been opened with Data access
fn get_task_description(&self) -> String {
pub fn get_task_description(&self) -> String {
let task_type = self.get_task_type().to_owned();
let task_id = self.id();
format!("{task_id:?} {task_type}")
}
#[cfg(feature = "trace_task_dirty")]
fn get_task_name(&self) -> String {
pub fn get_task_name(&self) -> String {
let task_type = self.get_task_type().to_owned();
format!("{task_type}")
}
}
pub struct TaskGuardImpl<'a> {
task_id: TaskId,
task: StorageWriteGuard<'a>,
// None means no categories are accessible other than transient data.
#[cfg(debug_assertions)]
category: TaskDataCategory,
task_lock_counter: TaskLockCounter,
}
impl Drop for TaskGuardImpl<'_> {
fn drop(&mut self) {
self.task_lock_counter.release();
}
}
impl<'a> TaskGuardImpl<'a> {
fn new(
task: StorageWriteGuard<'a>,
task_id: TaskId,
#[allow(unused_variables)] category: TaskDataCategory,
task_lock_counter: TaskLockCounter,
) -> Self {
Self {
task,
task_id,
#[cfg(debug_assertions)]
category,
task_lock_counter,
}
}
/// Verify that the task guard restored the correct category
/// before accessing the data.
......@@ -1671,28 +1594,17 @@ impl<'a> TaskGuardImpl<'a> {
}
}
}
}
impl Debug for TaskGuardImpl<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut d = f.debug_struct("TaskGuard");
d.field("task_id", &self.task_id);
d.field("storage", &*self.task);
d.finish()
}
}
impl TaskGuard for TaskGuardImpl<'_> {
fn id(&self) -> TaskId {
pub fn id(&self) -> TaskId {
self.task_id
}
#[cfg(debug_assertions)]
fn access(&self) -> TaskDataCategory {
pub fn access(&self) -> TaskDataCategory {
self.category
}
#[cfg(debug_assertions)]
fn downgrade_access(&mut self, access: TaskDataCategory) {
pub fn downgrade_access(&mut self, access: TaskDataCategory) {
assert!(
self.category >= access,
"Cannot downgrade {:?} to {access:?}",
......@@ -1701,11 +1613,13 @@ impl TaskGuard for TaskGuardImpl<'_> {
self.category = access;
}
fn discard_modifications_for_gc_new_task(&mut self) {
/// Clears all modified/new flags for a GC-collected task that was **never persisted**
/// (`new_task`).
pub fn discard_modifications_for_gc_new_task(&mut self) {
self.task.discard_modifications_for_gc_new_task();
}
fn invalidate_serialization(&mut self) {
pub fn invalidate_serialization(&mut self) {
// TODO this causes race conditions, since we never know when a value is changed. We can't
// "snapshot" the value correctly.
// Serialization invalidation is about cell data (e.g. a `State` mutated in place), so only
......@@ -1716,7 +1630,10 @@ impl TaskGuard for TaskGuardImpl<'_> {
let _ = self.track_modification(SpecificTaskDataCategory::Data, "invalidate_serialization");
}
fn prefetch(&mut self) -> Option<FxIndexMap<TaskId, TaskDataCategory>> {
/// Determine which tasks to prefetch for a task.
/// Only returns Some once per task.
/// It returns a set of tasks and which info is needed.
pub fn prefetch(&mut self) -> Option<FxIndexMap<TaskId, TaskDataCategory>> {
if self.task.flags.prefetched() {
return None;
}
......@@ -1744,7 +1661,8 @@ impl TaskGuard for TaskGuardImpl<'_> {
(map.len() > 1).then_some(map)
}
fn get_activeness_mut_or_insert_with<F>(&mut self, f: F) -> &mut ActivenessState
/// Get mutable reference to the activeness state, inserting a new one if not present
pub fn get_activeness_mut_or_insert_with<F>(&mut self, f: F) -> &mut ActivenessState
where
F: FnOnce() -> ActivenessState,
{
......@@ -1756,7 +1674,7 @@ impl TaskGuard for TaskGuardImpl<'_> {
}
}
impl TaskStorageAccessors for TaskGuardImpl<'_> {
impl TaskStorageAccessors for TaskGuard<'_> {
fn typed(&self) -> &TaskStorage {
&self.task
}
......@@ -1851,7 +1769,7 @@ mod must_exist_tests {
let tt = backend(Some(StorageMode::ReadOnly));
let present = persistent(1);
resident(&tt, present, TaskDataCategory::All);
let mut ctx = ExecuteContextImpl::new(tt.backend(), &tt);
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
let _ = ctx.task_pair(present, persistent(2), TaskDataCategory::Meta);
}
......@@ -1861,7 +1779,7 @@ mod must_exist_tests {
let tt = backend(Some(StorageMode::ReadOnly));
let present = persistent(1);
resident(&tt, present, TaskDataCategory::All);
let mut ctx = ExecuteContextImpl::new(tt.backend(), &tt);
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
let _ = ctx.task_pair(
TaskId::new(TRANSIENT_TASK_BIT | 2).unwrap(),
present,
......@@ -1873,7 +1791,7 @@ mod must_exist_tests {
#[should_panic(expected = "prepare batch, MustExist")]
async fn prepare_tasks_rejects_missing_batch() {
let tt = backend(Some(StorageMode::ReadOnly));
let mut ctx = ExecuteContextImpl::new(tt.backend(), &tt);
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
ctx.prepare_tasks(
[
(persistent(1), TaskDataCategory::Data),
......@@ -1888,7 +1806,7 @@ mod must_exist_tests {
#[should_panic(expected = "prepare transient, MustExist")]
async fn prepare_tasks_rejects_missing_transient() {
let tt = backend(Some(StorageMode::ReadOnly));
let mut ctx = ExecuteContextImpl::new(tt.backend(), &tt);
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
ctx.prepare_tasks(
[(
TaskId::new(TRANSIENT_TASK_BIT | 1).unwrap(),
......@@ -1959,7 +1877,7 @@ mod must_exist_tests {
let first = persistent(1);
let second = persistent(2);
let (tt, _dir) = persisted_tasks(&[first, second]);
let mut ctx = ExecuteContextImpl::new(tt.backend(), &tt);
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
ctx.prepare_tasks(
[
(first, TaskDataCategory::All),
......@@ -1979,7 +1897,7 @@ mod must_exist_tests {
let (tt, _dir) = persisted_tasks(&[ready, disk[0], disk[1]]);
resident(&tt, ready, TaskDataCategory::All);
resident(&tt, transient, TaskDataCategory::All);
let mut ctx = ExecuteContextImpl::new(tt.backend(), &tt);
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
let mut seen = Vec::new();
ctx.for_each_task(
[disk[0], ready, disk[1], transient].map(|id| (id, TaskDataCategory::All)),
......@@ -2014,7 +1932,7 @@ mod must_exist_tests {
let (sender, receiver) = mpsc::sync_channel(1);
let worker_tt = tt.clone();
let worker = std::thread::spawn(move || {
let mut ctx = ExecuteContextImpl::new(worker_tt.backend(), &worker_tt);
let mut ctx = ExecuteContext::new(worker_tt.backend(), &worker_tt);
let panicked = catch_unwind(AssertUnwindSafe(|| {
let _ = ctx.task(id, TaskDataCategory::All);
}))
......@@ -2057,7 +1975,7 @@ mod must_exist_tests {
let listener = tt.backend().storage.restored.listen();
let worker_tt = tt.clone();
let worker = std::thread::spawn(move || {
let mut ctx = ExecuteContextImpl::new(worker_tt.backend(), &worker_tt);
let mut ctx = ExecuteContext::new(worker_tt.backend(), &worker_tt);
catch_unwind(AssertUnwindSafe(|| {
ctx.prepare_tasks([(id, TaskDataCategory::All)], "wait for peer");
}))
......@@ -2094,7 +2012,7 @@ mod must_exist_tests {
let missing = persistent(2);
resident(&tt, present, TaskDataCategory::All);
for _ in 0..2 {
let mut ctx = ExecuteContextImpl::new(tt.backend(), &tt);
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
assert!(
catch_unwind(AssertUnwindSafe(|| {
let _ = ctx.task_pair(present, missing, TaskDataCategory::Meta);
......@@ -2120,7 +2038,7 @@ mod must_exist_tests {
let tt = backend(Some(StorageMode::ReadOnly));
let missing = [persistent(1), persistent(2), persistent(3)];
for _ in 0..2 {
let mut ctx = ExecuteContextImpl::new(tt.backend(), &tt);
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
assert!(
catch_unwind(AssertUnwindSafe(|| {
ctx.prepare_tasks(
......@@ -2143,7 +2061,7 @@ mod must_exist_tests {
let second = persistent(2);
resident(&tt, first, TaskDataCategory::All);
resident(&tt, second, TaskDataCategory::Meta);
let mut ctx = ExecuteContextImpl::new(tt.backend(), &tt);
let mut ctx = ExecuteContext::new(tt.backend(), &tt);
let tasks = [
(first, TaskDataCategory::Meta),
(second, TaskDataCategory::Meta),
......@@ -2162,7 +2080,7 @@ mod filter_transient_tracking_tests {
//!
//! These live here (rather than next to the schema in
//! `storage_schema.rs`) because the tracking accessors are only implemented by
//! [`TaskGuardImpl`], whose fields are private to this module.
//! [`TaskGuard`], whose fields are private to this module.
use turbo_tasks::{CellId, TRANSIENT_TASK_BIT, TaskId, ValueTypeId};
use super::*;
......@@ -2187,19 +2105,18 @@ mod filter_transient_tracking_tests {
}
}
/// Build a `TaskGuardImpl` for a persistent task, fully restored and with
/// Build a `TaskGuard` for a persistent task, fully restored and with
/// `All` category so `check_access` passes for both data and meta fields.
/// The guard must be dropped before `storage` (enforced by the borrow).
fn guard_for(storage: &Storage, task_id: TaskId) -> TaskGuardImpl<'_> {
fn guard_for(storage: &Storage, task_id: TaskId) -> TaskGuard<'_> {
let mut write = storage.access_mut(task_id);
write.flags.set_restored(TaskDataCategory::All);
TaskGuardImpl {
task: write,
TaskGuard::new(
write,
task_id,
#[cfg(debug_assertions)]
category: TaskDataCategory::All,
task_lock_counter: TaskLockCounter::new(),
}
TaskDataCategory::All,
TaskLockCounter::new(),
)
}
#[test]
......@@ -2455,16 +2372,15 @@ mod cell_data_tracking_tests {
SharedReference::new(triomphe::Arc::new(0u32))
}
fn guard_for(storage: &Storage, task_id: TaskId) -> TaskGuardImpl<'_> {
fn guard_for(storage: &Storage, task_id: TaskId) -> TaskGuard<'_> {
let mut write = storage.access_mut(task_id);
write.flags.set_restored(TaskDataCategory::All);
TaskGuardImpl {
task: write,
TaskGuard::new(
write,
task_id,
#[cfg(debug_assertions)]
category: TaskDataCategory::All,
task_lock_counter: TaskLockCounter::new(),
}
TaskDataCategory::All,
TaskLockCounter::new(),
)
}
#[test]
......
......@@ -3,15 +3,18 @@ use std::{cmp::max, num::NonZeroU32};
use rustc_hash::FxHashSet;
use turbo_tasks::TaskId;
use crate::backend::operation::{
AggregationUpdateJob, AggregationUpdateQueue, TaskGuard, is_aggregating_node, is_root_node,
use crate::backend::{
operation::{
AggregationUpdateJob, AggregationUpdateQueue, TaskGuard, is_aggregating_node, is_root_node,
},
storage_schema::TaskStorageAccessors,
};
const AGGREGATION_NUMBER_BUFFER_SPACE: u32 = 3;
pub fn prepare_new_children(
parent_task_id: TaskId,
parent_task: &mut impl TaskGuard,
parent_task: &mut TaskGuard<'_>,
new_children: &FxHashSet<TaskId>,
queue: &mut AggregationUpdateQueue,
) -> u32 {
......
......@@ -29,7 +29,7 @@ pub fn update_cell(
content_hash: Option<CellHash>,
#[cfg(feature = "verify_determinism")] verification_mode: VerificationMode,
#[cfg(not(feature = "verify_determinism"))] _verification_mode: VerificationMode,
mut ctx: impl ExecuteContext<'_>,
mut ctx: ExecuteContext<'_>,
) {
let value_type = registry::get_value_type(cell.type_id());
// `content_hash` is only ever supplied for `HashOnly` cells — only the
......@@ -219,7 +219,7 @@ pub fn update_cell(
/// Updates the stored cell_data_hash, which only `serialization = "hash"`
/// cells consult (on eviction + recompute). Skips the update for all other
/// persistence modes and when the hash hasn't changed.
fn update_cell_data_hash(task: &mut impl TaskGuard, cell: &CellId, content_hash: Option<CellHash>) {
fn update_cell_data_hash(task: &mut TaskGuard<'_>, cell: &CellId, content_hash: Option<CellHash>) {
let old_hash = task.get_cell_data_hash(cell).copied();
if old_hash != content_hash {
if let Some(hash) = content_hash {
......@@ -235,7 +235,7 @@ fn invalidate_cell_dependents(
mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[Option<u64>; 2]>>,
#[cfg(feature = "task_dirty_cause")] has_updated_key_hashes: bool,
content: Option<TypedSharedReference>,
ctx: &mut impl ExecuteContext<'_>,
ctx: &mut ExecuteContext<'_>,
) {
let mut queue = AggregationUpdateQueue::new();
while let Some((dependent_task_id, keys)) = dependent_tasks.pop() {
......
......@@ -21,7 +21,7 @@ impl UpdateCollectibleOperation {
task_id: TaskId,
collectible: CollectibleRef,
mut count: i32,
mut ctx: impl ExecuteContext<'_>,
mut ctx: ExecuteContext<'_>,
) {
let mut task = ctx.task(task_id, TaskDataCategory::All);
if count < 0
......
#![feature(anonymous_lifetime_in_impl_trait)]
#![feature(deref_patterns)]
mod backend;
......
......@@ -335,7 +335,7 @@ async fn mutating_a_state_read_by_a_collected_task_does_not_panic() {
// GC only soft-deletes, leaving the task resident, and a weak open of a resident-but-deleted
// task returns early on the `deleted` flag. Evicting drops it from memory (and tombstones it on
// disk), so the open below instead reaches the exists-nowhere case in
// `ExecuteContextImpl::open_task` -- nothing restored, nothing found on disk -- which is the
// `ExecuteContext::open_task` -- nothing restored, nothing found on disk -- which is the
// one that would panic under `MustExist`. Drop this line and the test still passes, but it
// stops covering that path.
tt2.backend().snapshot_and_evict_for_testing(&tt2);
......
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