vercel/next.js · #101514
turbo-tasks: capture effects on multiple workers
Cargo.lock1 + / 0 −
@@ -9173,6 +9173,7 @@ dependencies = [ "bincode", "codspeed-criterion-compat", "concurrent-queue",+ "crossbeam-utils", "dashmap 7.0.0-rc2", "either", "event-listener",turbopack/crates/turbo-tasks-backend/tests/effects.rs267 + / 3 −
@@ -2,9 +2,12 @@ #![feature(arbitrary_self_types_pointers)] #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this -use std::sync::{- Arc,- atomic::{AtomicU64, Ordering},+use std::{+ sync::{+ Arc,+ atomic::{AtomicBool, AtomicU64, Ordering},+ },+ time::Duration, }; use anyhow::Result;@@ -730,3 +733,264 @@ async fn capture_skip_then_stomp_signals_retry() { .await .unwrap() }++/// Enough effects that `take_effects` spreads their captures over several workers (it uses one+/// worker per 64 effects, up to one per CPU and at most 8).+const MANY_EFFECTS: usize = 1000;++/// Lets captures wait until a number of captures run at the same time.+#[derive(NonLocalValue)]+struct Rendezvous {+ #[turbo_tasks(unsafe_ignore)]+ arrived: std::sync::Mutex<usize>,+ #[turbo_tasks(unsafe_ignore)]+ condvar: std::sync::Condvar,+ /// Number of concurrent captures to wait for.+ expected: usize,+ /// Set when a capture gave up waiting.+ timed_out: AtomicBool,+}++impl Rendezvous {+ /// Blocks the calling thread until `expected` captures have arrived, or a timeout passed.+ fn arrive_and_wait(&self) {+ let mut arrived = self.arrived.lock().unwrap();+ *arrived += 1;+ self.condvar.notify_all();+ let (arrived, result) = self+ .condvar+ .wait_timeout_while(arrived, Duration::from_secs(10), |arrived| {+ *arrived < self.expected+ })+ .unwrap();+ drop(arrived);+ if result.timed_out() {+ self.timed_out.store(true, Ordering::Relaxed);+ }+ }+}++/// An effect whose capture blocks on a [`Rendezvous`].+#[turbo_tasks::value(serialization = "skip", cell = "new", eq = "manual")]+struct ProbeEffect {+ index: usize,+ #[turbo_tasks(debug_ignore)]+ rendezvous: Arc<Rendezvous>,+}++#[async_trait]+#[turbo_tasks::value_impl]+impl Effect for ProbeEffect {+ async fn capture(&self) -> Result<Box<dyn CapturedEffect>> {+ self.rendezvous.arrive_and_wait();+ Ok(Box::new(ProbeEffectCaptured { index: self.index }) as Box<dyn CapturedEffect>)+ }+}++#[derive(NonLocalValue)]+struct ProbeEffectCaptured {+ index: usize,+}++#[async_trait]+impl CapturedEffect for ProbeEffectCaptured {+ fn key(&self) -> Box<[u8]> {+ self.index.to_le_bytes().into()+ }++ fn value_hash(&self) -> u128 {+ 0+ }++ async fn apply(&self) -> Result<(), ApplyError> {+ Ok(())+ }+}++#[turbo_tasks::value(eq = "manual", serialization = "skip")]+struct ProbeInput {+ count: usize,+ #[turbo_tasks(debug_ignore)]+ rendezvous: Arc<Rendezvous>,+}++impl PartialEq for ProbeInput {+ fn eq(&self, _other: &Self) -> bool {+ false+ }+}++#[turbo_tasks::function(operation, root)]+async fn probe_producer_operation(input: ResolvedVc<ProbeInput>) -> Result<()> {+ let input = input.await?;+ for index in 0..input.count {+ ProbeEffect {+ index,+ rendezvous: input.rendezvous.clone(),+ }+ .resolved_cell()+ .emit();+ }+ Ok(())+}++#[turbo_tasks::function(operation, root)]+async fn extract_probe_effects(input: ResolvedVc<ProbeInput>) -> Result<Vc<Effects>> {+ let producer = probe_producer_operation(input);+ let _ = producer.resolve().strongly_consistent().await?;+ Ok(take_effects(producer).await?.cell())+}++fn probe_input(count: usize, expected: usize) -> ResolvedVc<ProbeInput> {+ ProbeInput {+ count,+ rendezvous: Arc::new(Rendezvous {+ arrived: std::sync::Mutex::new(0),+ condvar: std::sync::Condvar::new(),+ expected,+ timed_out: AtomicBool::new(false),+ }),+ }+ .resolved_cell()+}++/// The captures of many effects run on several threads at once: every capture blocks its thread+/// until two captures are in progress, which never happens with captures polled one by one.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn many_effects_are_captured_concurrently() {+ if turbo_tasks::parallel::available_parallelism().map_or(1, |n| n.get()) < 2 {+ // `take_effects` uses a single worker on a single CPU.+ return;+ }+ let tt = create_tt();+ tt.run_once(async move {+ let input = probe_input(MANY_EFFECTS, 2);+ let effects = extract_probe_effects(input)+ .read_strongly_consistent()+ .await?;+ effects.apply_for_testing().await?;+ assert!(+ !input.await?.rendezvous.timed_out.load(Ordering::Relaxed),+ "captures did not run concurrently"+ );+ anyhow::Ok(())+ })+ .await+ .unwrap()+}++#[turbo_tasks::value]+struct Version(u64);++#[turbo_tasks::value(eq = "manual", serialization = "skip")]+struct VersionInput {+ #[turbo_tasks(debug_ignore)]+ version: Arc<State<u64>>,+ #[turbo_tasks(debug_ignore)]+ counters: Arc<VersionCounters>,+}++impl PartialEq for VersionInput {+ fn eq(&self, _other: &Self) -> bool {+ false+ }+}++#[derive(NonLocalValue)]+struct VersionCounters {+ producer_runs: AtomicU64,+ captures_of_version_1: AtomicU64,+}++#[turbo_tasks::function]+async fn current_version(input: ResolvedVc<VersionInput>) -> Result<Vc<Version>> {+ Ok(Version(*input.await?.version.get()).cell())+}++/// An effect whose capture reads a cell that can change without its producer rerunning.+#[turbo_tasks::value(serialization = "skip", cell = "new", eq = "manual")]+struct VersionedEffect {+ index: usize,+ version: ResolvedVc<Version>,+ #[turbo_tasks(debug_ignore)]+ counters: Arc<VersionCounters>,+}++#[async_trait]+#[turbo_tasks::value_impl]+impl Effect for VersionedEffect {+ async fn capture(&self) -> Result<Box<dyn CapturedEffect>> {+ let version = self.version.await?.0;+ if version == 1 {+ self.counters+ .captures_of_version_1+ .fetch_add(1, Ordering::Relaxed);+ }+ Ok(Box::new(ProbeEffectCaptured { index: self.index }) as Box<dyn CapturedEffect>)+ }+}++#[turbo_tasks::function(operation, root)]+async fn versioned_producer_operation(input: ResolvedVc<VersionInput>) -> Result<()> {+ let counters = input.await?.counters.clone();+ counters.producer_runs.fetch_add(1, Ordering::Relaxed);+ let version = current_version(*input).to_resolved().await?;+ for index in 0..MANY_EFFECTS {+ VersionedEffect {+ index,+ version,+ counters: counters.clone(),+ }+ .resolved_cell()+ .emit();+ }+ Ok(())+}++#[turbo_tasks::function(operation, root)]+async fn extract_versioned_effects(input: ResolvedVc<VersionInput>) -> Result<Vc<Effects>> {+ let producer = versioned_producer_operation(input);+ let _ = producer.resolve().strongly_consistent().await?;+ Ok(take_effects(producer).await?.cell())+}++/// Cell reads by captures on worker threads are dependencies of the task calling `take_effects`.+/// Changing the read cell recaptures every effect, although the effects themselves are unchanged.+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]+async fn many_effects_capture_reads_are_tracked() {+ let tt = create_tt();+ tt.run_once(async move {+ let version = Arc::new(State::new(0));+ let counters = Arc::new(VersionCounters {+ producer_runs: AtomicU64::new(0),+ captures_of_version_1: AtomicU64::new(0),+ });+ let input = VersionInput {+ version: version.clone(),+ counters: counters.clone(),+ }+ .resolved_cell();+ let op = extract_versioned_effects(input);++ op.read_strongly_consistent().await?;+ assert_eq!(counters.producer_runs.load(Ordering::Relaxed), 1);+ assert_eq!(counters.captures_of_version_1.load(Ordering::Relaxed), 0);++ version.set(1);+ op.read_strongly_consistent().await?;+ assert_eq!(+ counters.producer_runs.load(Ordering::Relaxed),+ 1,+ "the emitted effects must stay unchanged"+ );+ assert_eq!(+ counters.captures_of_version_1.load(Ordering::Relaxed),+ MANY_EFFECTS as u64,+ "every capture must be invalidated by its cell read"+ );++ anyhow::Ok(())+ })+ .await+ .unwrap()+}turbopack/crates/turbo-tasks/Cargo.toml1 + / 0 −
@@ -37,6 +37,7 @@ async-trait = { workspace = true } auto-hash-map = { workspace = true } bincode = { workspace = true } concurrent-queue = { workspace = true }+crossbeam-utils = { workspace = true } dashmap = { workspace = true } either = { workspace = true } event-listener = "5.4.0"turbopack/crates/turbo-tasks/src/effect.rs132 + / 8 −
@@ -3,11 +3,16 @@ use std::{ error::Error as StdError, future::Future, mem::{forget, replace},- sync::Arc,+ num::NonZeroUsize,+ sync::{+ Arc, OnceLock,+ atomic::{AtomicUsize, Ordering},+ }, }; use anyhow::Result; use async_trait::async_trait;+use crossbeam_utils::CachePadded; use futures::{StreamExt, TryStreamExt}; use parking_lot::{Mutex, MutexGuard}; use rustc_hash::FxHashMap;@@ -20,8 +25,10 @@ use crate::{ invalidation::{Invalidator, get_invalidator}, manager::{ debug_assert_in_top_level_task, debug_assert_not_in_top_level_task, mark_top_level_task,- unmark_top_level_task_may_leak_eventually_consistent_state, with_turbo_tasks,+ spawn_in_current_task, unmark_top_level_task_may_leak_eventually_consistent_state,+ with_turbo_tasks, },+ parallel::available_parallelism, spawn, }; @@ -33,6 +40,10 @@ const APPLY_EFFECTS_CONCURRENCY_LIMIT: usize = 1024; pub trait Effect { /// Read any Vc data needed for `apply()` and return the [`CapturedEffect`] that performs it. ///+ /// Must not create cells (e.g. with `.cell()`): [`take_effects`] captures many effects+ /// concurrently as part of the one task calling it, so the order in which cells were created,+ /// which assigns their indices in that task, wouldn't be deterministic.+ /// /// An implementation may elect to elide capturing data if the `EffectStateStorage` state is /// already up to date. async fn capture(&self) -> Result<Box<dyn CapturedEffect>>;@@ -305,13 +316,12 @@ impl EffectStateStorage { /// ``` pub async fn take_effects(source: impl CollectiblesSource) -> Result<Effects> { debug_assert_not_in_top_level_task("take_effects");- let effects = source.take_collectibles::<Box<dyn Effect>>();-- let captured: Vec<Box<dyn CapturedEffect>> = effects+ let effects: Vec<ResolvedVc<Box<dyn Effect>>> = source+ .take_collectibles::<Box<dyn Effect>>() .into_iter()- .map(async |effect_vc| effect_vc.into_trait_ref().await?.capture().await)- .try_join()- .await?;+ .collect();++ let captured = capture_effects(effects).await?; // detect duplicate keys let unique_keys = build_unique_keys(&captured);@@ -322,6 +332,120 @@ pub async fn take_effects(source: impl CollectiblesSource) -> Result<Effects> { Ok(Effects::new(captured, unique_keys, invalidator)) } +/// [`capture_effects`] uses one worker per this many effects, so a few effects are captured on the+/// calling task's thread only.+const CAPTURE_EFFECTS_MIN_PER_WORKER: usize = 64;++/// The maximum number of workers [`capture_effects`] uses. Every capture records its reads as+/// dependencies of the one task calling [`take_effects`], which locks that task. With more workers+/// they mostly wait for that lock: on a warm build with ~200k effects, capturing took 4.3s with 1+/// worker, 1.4s with 4, 0.9s with 8, and still 0.9s with 16 or 32 workers, using 2-4x the CPU+/// time.+const CAPTURE_EFFECTS_MAX_WORKERS: usize = 8;++async fn capture_effect(effect: ResolvedVc<Box<dyn Effect>>) -> Result<Box<dyn CapturedEffect>> {+ effect.into_trait_ref().await?.capture().await+}++/// Captures `effects`, returning the captured effects in the same order.+///+/// Capturing reads every effect's cell and usually the content it writes. On a warm build that+/// data isn't in memory yet, so each read restores it from the persistent cache, synchronously on+/// the reading thread. Polling all captures in one future would do all of those restores one by+/// one on a single thread, so for many effects the captures are spread over several workers (up to+/// one per available CPU and at most [`CAPTURE_EFFECTS_MAX_WORKERS`]). The workers run as part of+/// the current task (see [`spawn_in_current_task`]), so their reads are tracked as the task's own+/// dependencies. Each worker takes the next uncaptured effect from a shared counter, which balances+/// the load when some captures are slower than others.+async fn capture_effects(+ effects: Vec<ResolvedVc<Box<dyn Effect>>>,+) -> Result<Vec<Box<dyn CapturedEffect>>> {+ let len = effects.len();+ let workers = available_parallelism()+ .map_or(1, NonZeroUsize::get)+ .min(CAPTURE_EFFECTS_MAX_WORKERS)+ .min(len / CAPTURE_EFFECTS_MIN_PER_WORKER);+ if workers <= 1 {+ return effects.into_iter().map(capture_effect).try_join().await;+ }++ let span = tracing::info_span!("capture effects", count = len, workers);+ async move {+ let state = Arc::new(CaptureEffectsState {+ effects,+ next: CachePadded::new(AtomicUsize::new(0)),+ captured: (0..len).map(|_| OnceLock::new()).collect(),+ });+ let handles = (0..workers)+ .map(|_| {+ let state = state.clone();+ spawn_in_current_task(async move {+ let result = state.capture_until_done().await;+ // Release the shared state before the result is handed to the joining side.+ drop(state);+ result+ })+ })+ .collect::<Vec<_>>();++ // Wait for every worker, even after an error, so none of them is still reading as part of+ // this task when we return.+ let results = futures::future::join_all(handles).await;+ results.into_iter().collect::<Result<()>>()?;+ let state = Arc::into_inner(state)+ .expect("capture workers finished while still holding the shared state");+ Ok(state+ .captured+ .into_iter()+ .map(|effect| {+ effect+ .into_inner()+ .expect("capture workers finished without capturing every effect")+ })+ .collect())+ }+ .instrument(span)+ .await+}++/// State shared by the workers of [`capture_effects`].+struct CaptureEffectsState {+ effects: Vec<ResolvedVc<Box<dyn Effect>>>,+ /// Index of the next effect to capture. Every worker increments it for every effect, so it is+ /// kept on its own cache line to avoid false sharing with the fields around it.+ next: CachePadded<AtomicUsize>,+ /// `captured[i]` is the captured `effects[i]`, set by the worker that took index `i`. It stays+ /// empty until then.+ captured: Box<[OnceLock<Box<dyn CapturedEffect>>]>,+}++impl CaptureEffectsState {+ /// Captures effects until there are none left or a capture fails.+ async fn capture_until_done(&self) -> Result<()> {+ let len = self.effects.len();+ loop {+ let idx = self.next.fetch_add(1, Ordering::Relaxed);+ let Some(&effect) = self.effects.get(idx) else {+ return Ok(());+ };+ let captured = match capture_effect(effect).await {+ Ok(captured) => captured,+ Err(err) => {+ // Make the other workers stop early, the result is an error anyway. Indices+ // handed out after this are `>= len`, so no index is handed out twice.+ self.next.store(len, Ordering::Relaxed);+ return Err(err);+ }+ };+ // `fetch_add` hands out every index below `len` at most once (`store` above only sets+ // the counter to `len`), so the slot is still empty.+ if self.captured[idx].set(captured).is_err() {+ panic!("effect {idx} was captured twice");+ }+ }+ }+}+ #[derive(thiserror::Error, Debug, NonLocalValue)] #[error("Conflicting effects for the same key (key length: {key_len} bytes)")] struct ConflictingEffectError {turbopack/crates/turbo-tasks/src/local_task_tracker.rs6 + / 3 −
@@ -70,19 +70,22 @@ impl LocalTaskTracker { self.decrement_in_flight(); } - /// Test-only: register an in-flight detached future (`spawn_detached_for_testing`). No+ /// Register an in-flight future that shares this task execution's state without being a local+ /// task (`spawn_in_current_task` and the test-only `spawn_detached_for_testing`). No /// `LocalTask` slot is allocated; this just bumps the counter. Balanced by a matching- /// [`decrement_in_flight`] when the wrapped future completes.+ /// [`decrement_in_flight`] when the wrapped future completes or is dropped. /// /// [`decrement_in_flight`]: LocalTaskTracker::decrement_in_flight pub(crate) fn register_detached(&mut self) { self.in_flight += 1; } /// Decrement the in-flight counter and notify the collective `done` event if it reached- /// zero. Used by the test-only detached path; the production path goes through+ /// zero. Used for futures registered with [`register_detached`]; local tasks go through /// [`complete`] which decrements as part of the slot transition. ///+ /// [`register_detached`]: LocalTaskTracker::register_detached+ /// /// [`complete`]: LocalTaskTracker::complete pub(crate) fn decrement_in_flight(&mut self) { debug_assert!(turbopack/crates/turbo-tasks/src/manager.rs41 + / 0 −
@@ -49,6 +49,7 @@ use crate::{ priority_runner::{Claimable, Executor, PriorityRunner}, registry, serialization_invalidation::SerializationInvalidator,+ spawn::JoinHandle, task::local_task::{LocalTask, LocalTaskSpec, LocalTaskType}, task_statistics::TaskStatisticsApi, util::{IdFactory, StaticOrArc},@@ -2574,6 +2575,46 @@ pub fn turbo_tasks_future_scope<T>( TURBO_TASKS.scope(tt, f) } +/// Spawns `future` on another worker thread as part of the current task execution and returns a+/// [`JoinHandle`] for its result.+///+/// Unlike [`spawn`][crate::spawn()], the future shares the current task's state, just like a local+/// task does: reads of cells and outputs in it are tracked as dependencies of the current task,+/// and the task execution doesn't complete before the future has finished (or has been dropped).+/// Use it to spread work that reads many cells over several threads, e.g. when the reads restore+/// data from the persistent cache.+///+/// A panic in `future` is resumed when the [`JoinHandle`] is awaited.+///+/// Must be called from within a task execution.+pub(crate) fn spawn_in_current_task<T: Send + 'static>(+ future: impl Future<Output = T> + Send + 'static,+) -> JoinHandle<T> {+ /// Balances the `register_detached` below, even when the future is dropped before it+ /// completes (e.g. on runtime shutdown).+ struct InFlightGuard(CurrentTaskStateHandle);+ impl Drop for InFlightGuard {+ fn drop(&mut self) {+ self.0.write().unwrap().local_tasks.decrement_in_flight();+ }+ }++ let task_state = CURRENT_TASK_STATE.with(|ts| ts.clone());+ task_state.write().unwrap().local_tasks.register_detached();+ let guard = InFlightGuard(task_state.clone());+ let future = async move {+ let result = CaptureFuture::new(future).await;+ // Mark the future as finished before the result is handed to the joining side.+ drop(guard);+ result+ };+ JoinHandle::new(tokio::task::spawn(+ TURBO_TASKS+ .scope(turbo_tasks(), CURRENT_TASK_STATE.scope(task_state, future))+ .instrument(Span::current()),+ ))+}+ /// Spawns the given future within the context of the current task. /// /// Beware: this method is not safe to use in production code. It is onlyturbopack/crates/turbo-tasks/src/spawn.rs6 + / 0 −
@@ -19,6 +19,12 @@ pub struct JoinHandle<T> { join_handle: tokio::task::JoinHandle<Result<T, TurboTasksPanic>>, } +impl<T> JoinHandle<T> {+ pub(crate) fn new(join_handle: tokio::task::JoinHandle<Result<T, TurboTasksPanic>>) -> Self {+ Self { join_handle }+ }+}+ impl<T: Send + 'static> JoinHandle<T> { pub fn join(self) -> T { block_for_future(self)