Unverified Commit 82794ab4 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

turbo-tasks-backend: restore invalidated tasks with batched optional reads (#100465)

### What?

`invalidate()` now opens its tasks with a bulk optional read
(`ExecuteContext::for_each_try_task_all`) instead of one `try_task` per
id. Non-resident persisted tasks are restored with one batched disk
lookup per category instead of one lookup per task.

### Why?

Follow-up to #100446
(https://github.com/vercel/next.js/pull/100446#discussion_r4326845752).
The existing bulk read APIs (`prepare_tasks` / `for_each_task*`) are
`MustExist`: a task missing in memory and on disk panics. Invalidation
needs `try_task` semantics instead, because a task being invalidated may
legitimately be gone.

### How?

- `prepare_tasks_with_callback` takes a `TaskAccess` mode.
- `MustExist` is the existing behavior and keeps the same panics and
messages.
- `AllowMissing` skips any task that `try_task` would not return, and
the callback isn't called for it:
    - a soft-deleted task, which is left in place
- a task that isn't restorable (transient, or no backing storage) and
isn't resident, which is discarded
- a task whose requested category has no disk key, including when only
one category is missing; it is discarded and its restoring claims are
cleared
- The existing restore phases are reused for both modes:
  - ready tasks are handed off first
  - claimed reads are done as batched I/O
- claims are applied and waiters notified before callbacks run for the
tasks this call restored
  - tasks a peer is restoring are waited for
- New `for_each_try_task_all` is built on that, sharing the guard and
lock-counter handling with `for_each_task`.
- `invalidate()` uses `for_each_try_task_all`.
- It requires unique ids: a `debug_assert!` checks this, with no
deduplication cost in release builds. The no-duplicates contract is
documented on `Backend::invalidate_tasks`, and every in-tree caller
already passes unique ids.
- Each task is still marked dirty, and its priority computed, while its
guard is held.
  - Scheduling is still a single `schedule_tasks` call.

In-tree, `invalidate()` currently gets a single id from every caller
(`Invalidator` → `Backend::invalidate_task`). Batching real multi-task
invalidations (file watcher, filesystem invalidation, `State`
dependents) through `Backend::invalidate_tasks` is a separate,
independent PR, and it carries the benchmark. This PR makes no
performance claim.

### Tests

- 11 unit tests for `for_each_try_task_all` in
`backend/operation/mod.rs`:
  - resident tasks
- persisted tasks that aren't resident, checked with a test-only lookup
counter: 3 tasks need 2 batched lookups and 0 single lookups
  - missing persistent and missing transient ids
  - soft-deleted tasks
  - a task with only one category on disk
  - no backing storage
  - a mixed batch
- waiting on a peer's restore, then either restoring the task or
skipping it when missing
- `tests/invalidate_tasks.rs`: `Backend::invalidate_tasks` with present,
missing persistent and missing transient ids. Each existing task
re-executes exactly once. This test also passes on the parent commit.
- `cargo test -p turbo-tasks-backend`, `cargo clippy -p
turbo-tasks-backend --all-targets -- -D warnings`, `cargo check -p
turbo-tasks-backend --features task_dirty_cause`

<!-- NEXT_JS_LLM -->


<!-- fleet d21ddb86-de88-41df-82c7-aa6a29a6165e -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 2085f517
......@@ -5,7 +5,6 @@ use turbo_tasks::{TaskExecutionReason, TaskId, TaskPriority, event::EventDescrip
use crate::{
backend::{
TaskDataCategory,
operation::{
ExecuteContext, TaskGuard,
aggregation_update::{
......@@ -17,31 +16,39 @@ use crate::{
data::{Dirtyness, InProgressState, InProgressStateInner},
};
/// Invalidates `task_ids`. Callers must not pass duplicate ids (the bulk task access expects
/// unique ids, and deduplicating here would cost every invalidation).
pub fn invalidate(
task_ids: SmallVec<[TaskId; 4]>,
#[cfg(feature = "task_dirty_cause")] cause: TaskDirtyCause,
mut ctx: ExecuteContext<'_>,
) {
debug_assert!(
task_ids.len() <= 1
|| task_ids.iter().collect::<rustc_hash::FxHashSet<_>>().len() == task_ids.len(),
"invalidate() must not be called with duplicate task ids: {task_ids:?}"
);
let mut queue = AggregationUpdateQueue::new();
// The tasks to schedule are collected and handed to the scheduler as one batch, which takes
// the scheduler's queue lock once instead of once per task.
let mut to_schedule: SmallVec<[_; 4]> = SmallVec::with_capacity(task_ids.len());
for task_id in task_ids {
let Some(mut task) = ctx.try_task(task_id, TaskDataCategory::All) else {
// The task no longer exists, nothing to invalidate.
continue;
};
// Tasks that no longer exist are skipped, there is nothing to invalidate. Tasks that are not
// resident are restored from persistent storage in batches.
ctx.for_each_try_task_all(task_ids, "invalidate", |mut task, ctx| {
if let Some(parent_priority) = make_task_dirty_without_scheduling(
&mut task,
true,
#[cfg(feature = "task_dirty_cause")]
cause.clone(),
&mut queue,
&mut ctx,
ctx,
) {
to_schedule.push((task_id, ctx.schedule_task_priority(&task, parent_priority)));
to_schedule.push((
task.id(),
ctx.schedule_task_priority(&task, parent_priority),
));
}
}
});
ctx.schedule_tasks(&to_schedule);
queue.execute(&mut ctx);
}
......
#![feature(arbitrary_self_types)]
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
mod util;
use std::sync::atomic::{AtomicU32, Ordering};
use turbo_tasks::{TRANSIENT_TASK_BIT, TaskId, Vc, backend::Backend};
use turbo_tasks_backend::TestSnapshotOutcome;
use crate::util::create_tt;
static EXECUTIONS: [AtomicU32; 2] = [AtomicU32::new(0), AtomicU32::new(0)];
#[turbo_tasks::function(operation, root)]
fn leaf(index: u32) -> Vc<u32> {
// Tasks without an invalidator or dependencies are immutable and must not be invalidated.
let _ = turbo_tasks::get_invalidator();
let executions = EXECUTIONS[index as usize].fetch_add(1, Ordering::SeqCst) + 1;
Vc::cell(executions)
}
/// `Backend::invalidate_tasks` with a batch containing ids of tasks that don't exist (persistent
/// and transient) invalidates the existing tasks once each and skips the rest.
///
/// Restoring non-resident tasks in a batch is covered by the `try_tasks_*` unit tests in
/// `backend/operation/mod.rs`; eviction here is best-effort, as tasks held by this session may
/// stay resident.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn invalidate_tasks_mixed_batch() {
let (tt, _persistence_dir) = create_tt("invalidate_tasks_mixed_batch");
let tt2 = tt.clone();
let result = turbo_tasks::run_once(tt.clone(), async move {
let leaves = [leaf(0), leaf(1)];
for leaf in leaves {
assert_eq!(*leaf.read_strongly_consistent().await?, 1);
}
// Persist the tasks, so the missing persistent id is looked up in a real store, and evict
// what can be evicted.
let TestSnapshotOutcome { had_new_data, .. } =
tt2.backend().snapshot_and_evict_for_testing(&tt2);
assert!(had_new_data, "snapshot should have persisted data");
let [a, b] = leaves.map(|leaf| leaf.task_id());
let missing_persistent = TaskId::new(0x00ff_ffff).unwrap();
let missing_transient = TaskId::new(TRANSIENT_TASK_BIT | 0x00ff_ffff).unwrap();
tt2.backend()
.invalidate_tasks(&[missing_persistent, a, b, missing_transient], &tt2);
for leaf in leaves {
assert_eq!(
*leaf.read_strongly_consistent().await?,
2,
"every existing task re-executes exactly once"
);
}
anyhow::Ok(())
})
.await;
tt.stop_and_wait().await;
result.unwrap();
}
......@@ -608,6 +608,7 @@ pub trait Backend: Sized + Sync + Send {
fn invalidate_task(&self, task: TaskId, turbo_tasks: &TurboTasks<Self>);
/// Invalidates all `tasks`. `tasks` must not contain duplicates.
fn invalidate_tasks(&self, tasks: &[TaskId], turbo_tasks: &TurboTasks<Self>);
fn invalidate_tasks_set(&self, tasks: &TaskIdSet, turbo_tasks: &TurboTasks<Self>);
......
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