Unverified Commit a29bfa2b authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

chore(turbo-tasks): Remove support for local_cells (a specific mode of local…

chore(turbo-tasks): Remove support for local_cells (a specific mode of local tasks we ended up not using) (#75672)

Local cells would allow us to avoid allocating real cells for data
passed to local task functions.

Unfortunately, in practice, we manually resolve most arguments passed to
local task functions, which would defeat this optimization.

I was holding onto this in the hopes that we might end up using it, but
that seems fleeting:
- We could get similar benefits by scanning for unreferenced cells at
the end of function execution using `TraceRawVcs` at the cost of a bit
of execution time. This would work even on `Vc`s that were resolved.
- For ergonomics reasons, we want to eventually rename `ResolvedVc` to
`Vc` (and `Vc` to something like `UnresolvedVc`), which will probably
lead to us resolving even more stuff, breaking this potential
optimization even more.
- Cache eviction may do a good enough job of removing cells, the bigger
enemy are the harder-to-evict tasks, which our current version of local
tasks does do a good job of reducing.

Meanwhile, it makes the code harder to follow, and could cause issues if
this codepath somehow got activated.
parent e8b41f6e
......@@ -91,9 +91,6 @@ impl UpdateOutputOperation {
cell,
})
}
Ok(Ok(RawVc::LocalCell(_, _))) => {
panic!("LocalCell must not be output of a task");
}
Ok(Ok(RawVc::LocalOutput(_, _))) => {
panic!("LocalOutput must not be output of a task");
}
......
../../turbo-tasks-testing/tests/local_cell.rs
\ No newline at end of file
error: unexpected token, expected one of: "fs", "network", "operation", "local", or "local_cells"
error: unexpected token, expected one of: "fs", "network", "operation", "local"
--> tests/function/fail_attribute_invalid_args.rs:9:25
|
9 | #[turbo_tasks::function(invalid_argument)]
......
error: unexpected token, expected one of: "fs", "network", "operation", "local", or "local_cells"
error: unexpected token, expected one of: "fs", "network", "operation", "local"
--> tests/function/fail_attribute_invalid_args_inherent_impl.rs:14:29
|
14 | #[turbo_tasks::function(invalid_argument)]
......
......@@ -756,7 +756,7 @@ pub struct FunctionArguments {
/// perform IO should not be manually annotated.
io_markers: FxHashSet<IoMarker>,
/// Should the function return an `OperationVc` instead of a `Vc`? Also ensures that all
/// arguments are `OperationValue`s. Mutually exclusive with the `local_cells` flag.
/// arguments are `OperationValue`s. Mutually exclusive with the `local` flag.
///
/// If there is an error due to this option being set, it should be reported to this span.
operation: Option<Span>,
......@@ -764,11 +764,6 @@ pub struct FunctionArguments {
/// task-local state. The function call itself will not be cached, but cells will be created on
/// the parent task.
pub local: Option<Span>,
/// Changes the behavior of `Vc::cell` to create local cells that are not cached across task
/// executions. Cells can be converted to their non-local versions by calling `Vc::resolve`.
///
/// If there is an error due to this option being set, it should be reported to this span.
pub local_cells: Option<Span>,
}
impl Parse for FunctionArguments {
......@@ -796,26 +791,19 @@ impl Parse for FunctionArguments {
("local", Meta::Path(_)) => {
parsed_args.local = Some(meta.span());
}
("local_cells", Meta::Path(_)) => {
parsed_args.local_cells = Some(meta.span());
}
(_, meta) => {
return Err(syn::Error::new_spanned(
meta,
"unexpected token, expected one of: \"fs\", \"network\", \"operation\", \
\"local\", or \"local_cells\"",
\"local\"",
))
}
}
}
if let (Some(_), Some(span)) = (
parsed_args.local.or(parsed_args.local_cells),
parsed_args.operation,
) {
if let (Some(_), Some(span)) = (parsed_args.local, parsed_args.operation) {
return Err(syn::Error::new(
span,
"\"operation\" is mutually exclusive with the \"local\" and \"local_cells\" \
options",
"\"operation\" is mutually exclusive with the \"local\" option",
));
}
Ok(parsed_args)
......@@ -1101,7 +1089,6 @@ pub struct NativeFn {
pub is_method: bool,
pub filter_trait_call_args: Option<FilterTraitCallArgsTokens>,
pub local: bool,
pub local_cells: bool,
}
impl NativeFn {
......@@ -1116,7 +1103,6 @@ impl NativeFn {
is_method,
filter_trait_call_args,
local,
local_cells,
} = self;
if *is_method {
......@@ -1141,7 +1127,6 @@ impl NativeFn {
#function_path_string.to_owned(),
turbo_tasks::macro_helpers::FunctionMeta {
local: #local,
local_cells: #local_cells,
},
#arg_filter,
#function_path,
......@@ -1156,7 +1141,6 @@ impl NativeFn {
#function_path_string.to_owned(),
turbo_tasks::macro_helpers::FunctionMeta {
local: #local,
local_cells: #local_cells,
},
#function_path,
)
......
......@@ -40,7 +40,6 @@ pub fn function(args: TokenStream, input: TokenStream) -> TokenStream {
.inspect_err(|err| errors.push(err.to_compile_error()))
.unwrap_or_default();
let local = args.local.is_some();
let local_cells = args.local_cells.is_some();
let Some(turbo_fn) = TurboFn::new(&sig, DefinitionContext::NakedFn, args) else {
return quote! {
......@@ -61,7 +60,6 @@ pub fn function(args: TokenStream, input: TokenStream) -> TokenStream {
is_method: turbo_fn.is_method(),
filter_trait_call_args: None, // not a trait method
local,
local_cells,
};
let native_function_ident = get_native_function_ident(ident);
let native_function_ty = native_fn.ty();
......
......@@ -123,7 +123,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
.inspect_err(|err| errors.push(err.to_compile_error()))
.unwrap_or_default();
let local = func_args.local.is_some();
let local_cells = func_args.local_cells.is_some();
let Some(turbo_fn) =
TurboFn::new(sig, DefinitionContext::ValueInherentImpl, func_args)
......@@ -142,7 +141,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
is_method: turbo_fn.is_method(),
filter_trait_call_args: None, // not a trait method
local,
local_cells,
};
let native_function_ident = get_inherent_impl_function_ident(ty_ident, ident);
......@@ -225,7 +223,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
.inspect_err(|err| errors.push(err.to_compile_error()))
.unwrap_or_default();
let local = func_args.local.is_some();
let local_cells = func_args.local_cells.is_some();
let Some(turbo_fn) =
TurboFn::new(sig, DefinitionContext::ValueTraitImpl, func_args)
......@@ -255,7 +252,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
is_method: turbo_fn.is_method(),
filter_trait_call_args: turbo_fn.filter_trait_call_args(),
local,
local_cells,
};
let native_function_ident =
......
......@@ -323,16 +323,6 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
let content = self;
turbo_tasks::ResolvedVc::cell_private(#cell_access_content)
}
/// Places a value in a task-local cell stored in the current task.
///
/// Task-local cells are stored in a task-local arena, and do not persist outside the
/// lifetime of the current task (including child tasks). Task-local cells can be resolved
/// to be converted into normal cells.
#cell_prefix fn local_cell(self) -> turbo_tasks::Vc<Self> {
let content = self;
turbo_tasks::Vc::local_cell_private(#cell_access_content)
}
};
let into = if let IntoMode::New | IntoMode::Shared = into_mode {
......
......@@ -121,12 +121,11 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
},
is_method: turbo_fn.is_method(),
filter_trait_call_args: turbo_fn.filter_trait_call_args(),
// `local` and `local_cells` are currently unsupported here because:
// `local` is currently unsupported here because:
// - The `#[turbo_tasks::function]` macro needs to be present for us to read this
// argument. (This could be fixed)
// - This only makes sense when a default implementation is present.
local: false,
local_cells: false,
};
let native_function_ident = get_trait_default_impl_function_ident(trait_ident, ident);
......
../../turbo-tasks-testing/tests/local_cell.rs
\ No newline at end of file
......@@ -20,7 +20,7 @@ use turbo_tasks::{
registry,
test_helpers::with_turbo_tasks_for_testing,
util::{SharedError, StaticOrArc},
CellId, ExecutionId, InvalidationReason, LocalTaskId, MagicAny, RawVc, ReadConsistency, TaskId,
CellId, InvalidationReason, LocalTaskId, MagicAny, RawVc, ReadConsistency, TaskId,
TaskPersistence, TraitTypeId, TurboTasksApi, TurboTasksCallApi,
};
......@@ -57,11 +57,9 @@ impl VcStorage {
i
};
let task_id = TaskId::from(i as u32 + 1);
let execution_id = ExecutionId::from(i as u64 + 1);
handle.spawn(with_turbo_tasks_for_testing(
this.clone(),
task_id,
execution_id,
async move {
let result = AssertUnwindSafe(future).catch_unwind().await;
......@@ -316,7 +314,6 @@ impl VcStorage {
..Default::default()
}),
TaskId::from(u32::MAX),
ExecutionId::from(u64::MAX),
f,
)
}
......
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use anyhow::Result;
use turbo_tasks::{
debug::ValueDebug, test_helpers::current_task_for_testing, ResolvedVc, ValueDefault, Vc,
};
use turbo_tasks_testing::{register, run, Registration};
static REGISTRATION: Registration = register!();
#[turbo_tasks::value]
struct Wrapper(u32);
#[turbo_tasks::value(transparent)]
struct TransparentWrapper(u32);
#[tokio::test]
async fn test_store_and_read() -> Result<()> {
run(&REGISTRATION, || async {
let a: Vc<u32> = Vc::local_cell(42);
assert_eq!(*a.await.unwrap(), 42);
let b = Wrapper(42).local_cell();
assert_eq!((*b.await.unwrap()).0, 42);
let c = TransparentWrapper(42).local_cell();
assert_eq!(*c.await.unwrap(), 42);
Ok(())
})
.await
}
#[turbo_tasks::function(local_cells)]
async fn returns_resolved_local_vc() -> Vc<u32> {
let cell = Vc::<u32>::cell(42);
assert!(cell.is_local());
cell.resolve().await.unwrap()
}
#[ignore]
#[tokio::test]
async fn test_return_resolved() -> Result<()> {
run(&REGISTRATION, || async {
assert_eq!(*returns_resolved_local_vc().await.unwrap(), 42);
Ok(())
})
.await
}
#[turbo_tasks::value_trait]
trait UnimplementedTrait {}
#[tokio::test]
async fn test_try_resolve_sidecast() -> Result<()> {
run(&REGISTRATION, || async {
let trait_vc: Vc<Box<dyn ValueDebug>> = Vc::upcast(Vc::<u32>::local_cell(42));
// `u32` is both a `ValueDebug` and a `ValueDefault`, so this sidecast is valid
let sidecast_vc = Vc::try_resolve_sidecast::<Box<dyn ValueDefault>>(trait_vc)
.await
.unwrap();
assert!(sidecast_vc.is_some());
// `u32` is not an `UnimplementedTrait` though, so this should return None
let wrongly_sidecast_vc = Vc::try_resolve_sidecast::<Box<dyn UnimplementedTrait>>(trait_vc)
.await
.unwrap();
assert!(wrongly_sidecast_vc.is_none());
Ok(())
})
.await
}
#[tokio::test]
async fn test_try_resolve_downcast_type() -> Result<()> {
run(&REGISTRATION, || async {
let trait_vc: Vc<Box<dyn ValueDebug>> = Vc::upcast(Vc::<u32>::local_cell(42));
let downcast_vc: Vc<u32> = Vc::try_resolve_downcast_type(trait_vc)
.await
.unwrap()
.unwrap();
assert_eq!(*downcast_vc.await.unwrap(), 42);
let wrongly_downcast_vc: Option<Vc<i64>> =
Vc::try_resolve_downcast_type(trait_vc).await.unwrap();
assert!(wrongly_downcast_vc.is_none());
Ok(())
})
.await
}
#[tokio::test]
async fn test_get_task_id() -> Result<()> {
run(&REGISTRATION, || async {
// the task id as reported by the RawVc
let vc_task_id = Vc::into_raw(Vc::<()>::local_cell(())).get_task_id();
assert_eq!(vc_task_id, current_task_for_testing());
Ok(())
})
.await
}
#[turbo_tasks::value(eq = "manual")]
#[derive(Default)]
struct Untracked {
#[turbo_tasks(debug_ignore, trace_ignore)]
#[serde(skip)]
cell: ResolvedVc<u32>,
}
impl PartialEq for Untracked {
fn eq(&self, other: &Self) -> bool {
std::ptr::eq(self as *const _, other as *const _)
}
}
impl Eq for Untracked {}
#[turbo_tasks::function(local_cells)]
async fn get_untracked_local_cell() -> Vc<Untracked> {
Untracked {
cell: ResolvedVc::cell(42),
}
.cell()
.resolve()
.await
.unwrap()
}
#[ignore]
#[tokio::test]
#[should_panic(expected = "Local Vcs must only be accessed within their own task")]
async fn test_panics_on_local_cell_escape_read() {
run(&REGISTRATION, || async {
get_untracked_local_cell()
.await
.unwrap()
.cell
.await
.unwrap();
Ok(())
})
.await
.unwrap()
}
#[ignore]
#[tokio::test]
#[should_panic(expected = "Local Vcs must only be accessed within their own task")]
async fn test_panics_on_local_cell_escape_get_task_id() {
run(&REGISTRATION, || async {
Vc::into_raw(*get_untracked_local_cell().await.unwrap().cell).get_task_id();
Ok(())
})
.await
.unwrap()
}
......@@ -18,9 +18,6 @@ async fn test_shrink_to_fit() -> Result<()> {
let a: Vc<Wrapper> = Vc::cell(Vec::with_capacity(100));
assert_eq!(a.await?.capacity(), 0);
let b: Vc<Wrapper> = Vc::local_cell(Vec::with_capacity(100));
assert_eq!(b.await?.capacity(), 0);
Ok(())
})
.await
......
......@@ -12,7 +12,7 @@ use auto_hash_map::AutoMap;
use rustc_hash::FxHasher;
use tracing::Span;
pub use crate::id::{BackendJobId, ExecutionId};
pub use crate::id::BackendJobId;
use crate::{
event::EventListener,
magic_any::MagicAny,
......@@ -433,7 +433,7 @@ pub trait Backend: Sync + Send {
///
/// This data may be shared across multiple threads (must be `Sync`) in order to support
/// detached futures ([`crate::TurboTasksApi::detached_for_testing`]) and [pseudo-tasks using
/// `local_cells`][crate::function]. A [`RwLock`][std::sync::RwLock] is used to provide
/// `local` execution][crate::function]. A [`RwLock`][std::sync::RwLock] is used to provide
/// concurrent access.
type TaskState: Send + Sync + 'static;
......
......@@ -77,19 +77,12 @@ define_id!(FunctionId: u32);
define_id!(ValueTypeId: u32);
define_id!(TraitTypeId: u32);
define_id!(BackendJobId: u32);
define_id!(ExecutionId: u64, derive(Debug));
define_id!(SessionId: u32, derive(Debug, Serialize, Deserialize), serde(transparent));
define_id!(
LocalCellId: u32,
derive(Debug),
doc = "Represents the nth call to `Vc::cell()` with `local_cells` inside of the parent ",
doc = "non-local task.",
);
define_id!(
LocalTaskId: u32,
derive(Debug, Serialize, Deserialize),
serde(transparent),
doc = "Represents the nth `local_cells` function call inside a task.",
doc = "Represents the nth `local` function call inside a task.",
);
impl Debug for TaskId {
......
......@@ -92,8 +92,7 @@ pub use completion::{Completion, Completions};
pub use display::ValueToString;
pub use effect::{apply_effects, effect, get_effects, Effects};
pub use id::{
ExecutionId, FunctionId, LocalTaskId, SessionId, TaskId, TraitTypeId, ValueTypeId,
TRANSIENT_TASK_BIT,
FunctionId, LocalTaskId, SessionId, TaskId, TraitTypeId, ValueTypeId, TRANSIENT_TASK_BIT,
};
pub use invalidation::{
get_invalidator, DynamicEqHash, InvalidationReason, InvalidationReasonKind,
......
......@@ -31,20 +31,13 @@ use crate::{
},
capture_future::{self, CaptureFuture},
event::{Event, EventListener},
id::{
BackendJobId, ExecutionId, FunctionId, LocalCellId, LocalTaskId, TraitTypeId,
TRANSIENT_TASK_BIT,
},
id_factory::{IdFactory, IdFactoryWithReuse},
id::{BackendJobId, FunctionId, LocalTaskId, TraitTypeId, TRANSIENT_TASK_BIT},
id_factory::IdFactoryWithReuse,
magic_any::MagicAny,
native_function::FunctionMeta,
raw_vc::{CellId, RawVc},
registry::{self, get_function},
registry,
serialization_invalidation::SerializationInvalidator,
task::{
local_task::{LocalTask, LocalTaskType},
shared_reference::TypedSharedReference,
},
task::local_task::{LocalTask, LocalTaskType},
task_statistics::TaskStatisticsApi,
trace::TraceRawVcs,
trait_helpers::get_trait_method,
......@@ -346,7 +339,6 @@ pub struct TurboTasks<B: Backend + 'static> {
backend: B,
task_id_factory: IdFactoryWithReuse<TaskId>,
transient_task_id_factory: IdFactoryWithReuse<TaskId>,
execution_id_factory: IdFactory<ExecutionId>,
stopped: AtomicBool,
currently_scheduled_tasks: AtomicUsize,
currently_scheduled_foreground_jobs: AtomicUsize,
......@@ -361,15 +353,15 @@ pub struct TurboTasks<B: Backend + 'static> {
program_start: Instant,
}
/// Information about a "global" task. A global task can contain multiple "local" tasks (see
/// [`CurrentLocalTaskState`]), which all share the same global state.
/// Information about a non-local task. A non-local task can contain multiple "local" tasks, which
/// all share the same non-local task state.
///
/// A global task is one that:
/// A non-local task is one that:
///
/// - Has a unique task id.
/// - Is potentially cached.
/// - The backend is aware of.
struct CurrentGlobalTaskState {
struct CurrentTaskState {
task_id: TaskId,
/// Affected tasks, that are tracked during task execution. These tasks will
......@@ -386,10 +378,6 @@ struct CurrentGlobalTaskState {
/// This is taken (and becomes `None`) during teardown of a task.
cell_counters: Option<AutoMap<ValueTypeId, u32, BuildHasherDefault<FxHasher>, 8>>,
/// Cells for locally allocated Vcs (`RawVc::LocalCell`). This is freed (along with
/// `CurrentGlobalTaskState`) when the task finishes executing.
local_cells: Vec<TypedSharedReference>,
/// Local tasks created while this global task has been running. Indexed by `LocalTaskId`.
local_tasks: Vec<LocalTask>,
......@@ -400,14 +388,13 @@ struct CurrentGlobalTaskState {
backend_state: Box<dyn Any + Send + Sync>,
}
impl CurrentGlobalTaskState {
impl CurrentTaskState {
fn new(task_id: TaskId, backend_state: Box<dyn Any + Send + Sync>) -> Self {
Self {
task_id,
tasks_to_notify: Vec::new(),
stateful: false,
cell_counters: Some(AutoMap::default()),
local_cells: Vec::new(),
local_tasks: Vec::new(),
local_task_tracker: TaskTracker::new(),
backend_state,
......@@ -442,38 +429,12 @@ impl CurrentGlobalTaskState {
}
}
/// Information specific to the current "local" task. A local task re-uses it's parent global task's
/// [`CurrentGlobalTaskState`].
///
/// Even if a task itself isn't local, it will have a `CurrentLocalTaskState` representing the root
/// of the global task.
#[derive(Clone)]
struct CurrentLocalTaskState {
/// A unique identifier created for each unique[`CurrentLocalTaskState`]. Used to check that
/// [`CurrentTaskState::local_cells`] are valid for the currant [`RawVc::LocalCell`].
execution_id: ExecutionId,
/// The function's metadata if this is a persistent task. Contains information about arguments
/// passed to the `#[turbo_tasks::function(...)]` macro.
function_meta: Option<&'static FunctionMeta>,
}
impl CurrentLocalTaskState {
fn new(execution_id: ExecutionId, function_meta: Option<&'static FunctionMeta>) -> Self {
Self {
execution_id,
function_meta,
}
}
}
// TODO implement our own thread pool and make these thread locals instead
task_local! {
/// The current TurboTasks instance
static TURBO_TASKS: Arc<dyn TurboTasksApi>;
static CURRENT_GLOBAL_TASK_STATE: Arc<RwLock<CurrentGlobalTaskState>>;
static CURRENT_LOCAL_TASK_STATE: CurrentLocalTaskState;
static CURRENT_TASK_STATE: Arc<RwLock<CurrentTaskState>>;
}
impl<B: Backend + 'static> TurboTasks<B> {
......@@ -491,7 +452,6 @@ impl<B: Backend + 'static> TurboTasks<B> {
backend,
task_id_factory,
transient_task_id_factory,
execution_id_factory: IdFactory::new(1, u64::MAX),
stopped: AtomicBool::new(false),
currently_scheduled_tasks: AtomicUsize::new(0),
currently_scheduled_background_jobs: AtomicUsize::new(0),
......@@ -673,16 +633,10 @@ impl<B: Backend + 'static> TurboTasks<B> {
let mut schedule_again = true;
while schedule_again {
let backend_state = this.backend.new_task_state(task_id);
let global_task_state = Arc::new(RwLock::new(CurrentGlobalTaskState::new(
let current_task_state = Arc::new(RwLock::new(CurrentTaskState::new(
task_id,
Box::new(backend_state),
)));
let local_task_state = CurrentLocalTaskState::new(
this.execution_id_factory.get(),
this.backend
.try_get_function_id(task_id)
.map(|func_id| &get_function(func_id).function_meta),
);
let single_execution_future = async {
if this.stopped.load(Ordering::Acquire) {
return false;
......@@ -698,8 +652,8 @@ impl<B: Backend + 'static> TurboTasks<B> {
let (result, duration, memory_usage) =
CaptureFuture::new(AssertUnwindSafe(future).catch_unwind()).await;
// wait for all spawned local tasks using `local_cells` to finish
let ltt = CURRENT_GLOBAL_TASK_STATE
// wait for all spawned local tasks using `local` to finish
let ltt = CURRENT_TASK_STATE
.with(|ts| ts.read().unwrap().local_task_tracker.clone());
ltt.close();
ltt.wait().await;
......@@ -713,7 +667,7 @@ impl<B: Backend + 'static> TurboTasks<B> {
});
this.backend.task_execution_result(task_id, result, &*this);
let stateful = this.finish_current_task_state();
let cell_counters = CURRENT_GLOBAL_TASK_STATE
let cell_counters = CURRENT_TASK_STATE
.with(|ts| ts.write().unwrap().cell_counters.take().unwrap());
let schedule_again = this.backend.task_execution_completed(
task_id,
......@@ -730,11 +684,8 @@ impl<B: Backend + 'static> TurboTasks<B> {
.instrument(span)
.await
};
schedule_again = CURRENT_GLOBAL_TASK_STATE
.scope(
global_task_state,
CURRENT_LOCAL_TASK_STATE.scope(local_task_state, single_execution_future),
)
schedule_again = CURRENT_TASK_STATE
.scope(current_task_state, single_execution_future)
.await;
}
this.finish_primary_job();
......@@ -765,23 +716,16 @@ impl<B: Backend + 'static> TurboTasks<B> {
use crate::OutputContent;
let ty = Arc::new(ty);
let (global_task_state, local_task_id, parent_task_id) =
CURRENT_GLOBAL_TASK_STATE.with(|gts| {
let mut gts_write = gts.write().unwrap();
let local_task_id = gts_write.create_local_task(LocalTask::Scheduled {
done_event: Event::new({
let ty = Arc::clone(&ty);
move || format!("LocalTask({})::done_event", ty)
}),
});
(Arc::clone(gts), local_task_id, gts_write.task_id)
let (global_task_state, local_task_id, parent_task_id) = CURRENT_TASK_STATE.with(|gts| {
let mut gts_write = gts.write().unwrap();
let local_task_id = gts_write.create_local_task(LocalTask::Scheduled {
done_event: Event::new({
let ty = Arc::clone(&ty);
move || format!("LocalTask({})::done_event", ty)
}),
});
let local_task_state = CurrentLocalTaskState::new(
self.execution_id_factory.get(),
ty.try_get_function_id()
.map(|func_id| &get_function(func_id).function_meta),
);
(Arc::clone(gts), local_task_id, gts_write.task_id)
});
#[cfg(feature = "tokio_tracing")]
let description = format!(
......@@ -813,7 +757,7 @@ impl<B: Backend + 'static> TurboTasks<B> {
},
};
let done_event = CURRENT_GLOBAL_TASK_STATE.with(move |gts| {
let done_event = CURRENT_TASK_STATE.with(move |gts| {
let mut gts_write = gts.write().unwrap();
let scheduled_task =
std::mem::replace(gts_write.get_mut_local_task(local_task_id), local_task);
......@@ -832,8 +776,7 @@ impl<B: Backend + 'static> TurboTasks<B> {
.unwrap()
.local_task_tracker
.track_future(future);
let future = CURRENT_LOCAL_TASK_STATE.scope(local_task_state, future);
let future = CURRENT_GLOBAL_TASK_STATE.scope(global_task_state, future);
let future = CURRENT_TASK_STATE.scope(global_task_state, future);
let future = TURBO_TASKS.scope(self.pin(), future).in_current_span();
#[cfg(feature = "tokio_tracing")]
......@@ -1142,8 +1085,8 @@ impl<B: Backend + 'static> TurboTasks<B> {
}
fn finish_current_task_state(&self) -> bool {
let (stateful, tasks) = CURRENT_GLOBAL_TASK_STATE.with(|cell| {
let CurrentGlobalTaskState {
let (stateful, tasks) = CURRENT_TASK_STATE.with(|cell| {
let CurrentTaskState {
tasks_to_notify,
stateful,
..
......@@ -1258,9 +1201,9 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
}
fn notify_scheduled_tasks(&self) {
let _ = CURRENT_GLOBAL_TASK_STATE.try_with(|cell| {
let _ = CURRENT_TASK_STATE.try_with(|cell| {
let tasks = {
let CurrentGlobalTaskState {
let CurrentTaskState {
tasks_to_notify, ..
} = &mut *cell.write().unwrap();
take(tasks_to_notify)
......@@ -1321,7 +1264,7 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
parent_task_id: TaskId,
local_task_id: LocalTaskId,
) -> Result<Result<RawVc, EventListener>> {
CURRENT_GLOBAL_TASK_STATE.with(|gts| {
CURRENT_TASK_STATE.with(|gts| {
let gts_read = gts.read().unwrap();
// Local Vcs are local to their parent task, and do not exist outside of it. This is
......@@ -1414,18 +1357,14 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>> {
// this is similar to what happens for a local task, except that we keep the local task's
// state as well.
let global_task_state = CURRENT_GLOBAL_TASK_STATE.with(|ts| ts.clone());
let local_task_state = CURRENT_LOCAL_TASK_STATE.with(|ts| ts.clone());
let global_task_state = CURRENT_TASK_STATE.with(|ts| ts.clone());
let tracked_fut = {
let ts = global_task_state.read().unwrap();
ts.local_task_tracker.track_future(fut)
};
Box::pin(TURBO_TASKS.scope(
turbo_tasks(),
CURRENT_GLOBAL_TASK_STATE.scope(
global_task_state,
CURRENT_LOCAL_TASK_STATE.scope(local_task_state, tracked_fut),
),
CURRENT_TASK_STATE.scope(global_task_state, tracked_fut),
))
}
......@@ -1502,8 +1441,8 @@ impl<B: Backend + 'static> TurboTasksBackendApi<B> for TurboTasks<B> {
/// Enqueues tasks for notification of changed dependencies. This will
/// eventually call `dependent_cell_updated()` on all tasks.
fn schedule_notify_tasks(&self, tasks: &[TaskId]) {
let result = CURRENT_GLOBAL_TASK_STATE.try_with(|cell| {
let CurrentGlobalTaskState {
let result = CURRENT_TASK_STATE.try_with(|cell| {
let CurrentTaskState {
tasks_to_notify, ..
} = &mut *cell.write().unwrap();
tasks_to_notify.extend(tasks.iter());
......@@ -1517,8 +1456,8 @@ impl<B: Backend + 'static> TurboTasksBackendApi<B> for TurboTasks<B> {
/// Enqueues tasks for notification of changed dependencies. This will
/// eventually call `dependent_cell_updated()` on all tasks.
fn schedule_notify_tasks_set(&self, tasks: &TaskIdSet) {
let result = CURRENT_GLOBAL_TASK_STATE.try_with(|cell| {
let CurrentGlobalTaskState {
let result = CURRENT_TASK_STATE.try_with(|cell| {
let CurrentTaskState {
tasks_to_notify, ..
} = &mut *cell.write().unwrap();
tasks_to_notify.extend(tasks.iter());
......@@ -1557,12 +1496,12 @@ impl<B: Backend + 'static> TurboTasksBackendApi<B> for TurboTasks<B> {
}
fn read_task_state_dyn(&self, func: &mut dyn FnMut(&B::TaskState)) {
CURRENT_GLOBAL_TASK_STATE
CURRENT_TASK_STATE
.with(move |ts| func(ts.read().unwrap().backend_state.downcast_ref().unwrap()))
}
fn write_task_state_dyn(&self, func: &mut dyn FnMut(&mut B::TaskState)) {
CURRENT_GLOBAL_TASK_STATE
CURRENT_TASK_STATE
.with(move |ts| func(ts.write().unwrap().backend_state.downcast_mut().unwrap()))
}
......@@ -1572,7 +1511,7 @@ impl<B: Backend + 'static> TurboTasksBackendApi<B> for TurboTasks<B> {
}
pub(crate) fn current_task(from: &str) -> TaskId {
match CURRENT_GLOBAL_TASK_STATE.try_with(|ts| ts.read().unwrap().task_id) {
match CURRENT_TASK_STATE.try_with(|ts| ts.read().unwrap().task_id) {
Ok(id) => id,
Err(_) => panic!(
"{} can only be used in the context of turbo_tasks task execution",
......@@ -1672,20 +1611,16 @@ pub fn turbo_tasks_future_scope<T>(
pub fn with_turbo_tasks_for_testing<T>(
tt: Arc<dyn TurboTasksApi>,
current_task: TaskId,
execution_id: ExecutionId,
f: impl Future<Output = T>,
) -> impl Future<Output = T> {
TURBO_TASKS.scope(
tt,
CURRENT_GLOBAL_TASK_STATE.scope(
Arc::new(RwLock::new(CurrentGlobalTaskState::new(
CURRENT_TASK_STATE.scope(
Arc::new(RwLock::new(CurrentTaskState::new(
current_task,
Box::new(()),
))),
CURRENT_LOCAL_TASK_STATE.scope(
CurrentLocalTaskState::new(execution_id, /* function_meta */ None),
f,
),
f,
),
)
}
......@@ -1699,7 +1634,7 @@ pub fn spawn_detached_for_testing(f: impl Future<Output = Result<()>> + Send + '
}
pub fn current_task_for_testing() -> TaskId {
CURRENT_GLOBAL_TASK_STATE.with(|ts| ts.read().unwrap().task_id)
CURRENT_TASK_STATE.with(|ts| ts.read().unwrap().task_id)
}
/// Marks the current task as dirty when restored from persistent cache.
......@@ -1731,8 +1666,8 @@ pub fn mark_finished() {
/// Returns a [`SerializationInvalidator`] that can be used to invalidate the
/// serialization of the current task cells
pub fn mark_stateful() -> SerializationInvalidator {
CURRENT_GLOBAL_TASK_STATE.with(|cell| {
let CurrentGlobalTaskState {
CURRENT_TASK_STATE.with(|cell| {
let CurrentTaskState {
stateful, task_id, ..
} = &mut *cell.write().unwrap();
*stateful = true;
......@@ -1995,7 +1930,7 @@ impl From<CurrentCellRef> for RawVc {
}
pub fn find_cell_by_type(ty: ValueTypeId) -> CurrentCellRef {
CURRENT_GLOBAL_TASK_STATE.with(|ts| {
CURRENT_TASK_STATE.with(|ts| {
let current_task = current_task("celling turbo_tasks values");
let mut ts = ts.write().unwrap();
let map = ts.cell_counters.as_mut().unwrap();
......@@ -2009,48 +1944,6 @@ pub fn find_cell_by_type(ty: ValueTypeId) -> CurrentCellRef {
})
}
pub(crate) fn try_get_function_meta() -> Option<&'static FunctionMeta> {
CURRENT_LOCAL_TASK_STATE.with(|ts| ts.function_meta)
}
pub(crate) fn create_local_cell(value: TypedSharedReference) -> (ExecutionId, LocalCellId) {
let execution_id = CURRENT_LOCAL_TASK_STATE.with(|ts| ts.execution_id);
let raw_local_cell_id = CURRENT_GLOBAL_TASK_STATE.with(|ts| {
let CurrentGlobalTaskState { local_cells, .. } = &mut *ts.write().unwrap();
// store in the task-local arena
local_cells.push(value);
local_cells.len()
});
// generate a one-indexed id
let local_cell_id = if cfg!(debug_assertions) {
LocalCellId::from(u32::try_from(raw_local_cell_id).unwrap())
} else {
unsafe { LocalCellId::new_unchecked(raw_local_cell_id as u32) }
};
(execution_id, local_cell_id)
}
/// Returns the contents of the given local cell. Panics if a local cell is
/// attempted to be accessed outside of its task.
///
/// Returns [`TypedSharedReference`] instead of [`TypedCellContent`] because
/// local cells are always filled. The returned value can be cheaply converted
/// with `.into()`.
///
/// Panics if the [`ExecutionId`] does not match the current task's
/// `execution_id`.
pub(crate) fn read_local_cell(
execution_id: ExecutionId,
local_cell_id: LocalCellId,
) -> TypedSharedReference {
assert_execution_id(execution_id);
CURRENT_GLOBAL_TASK_STATE.with(|ts| {
let CurrentGlobalTaskState { local_cells, .. } = &*ts.write().unwrap();
// local cell ids are one-indexed (they use NonZeroU32)
local_cells[(*local_cell_id as usize) - 1].clone()
})
}
pub(crate) async fn read_local_output(
this: &dyn TurboTasksApi,
parent_task_id: TaskId,
......@@ -2063,19 +1956,3 @@ pub(crate) async fn read_local_output(
}
}
}
/// Panics if the [`ExecutionId`] does not match the current task's
/// `execution_id`.
pub(crate) fn assert_execution_id(execution_id: ExecutionId) {
CURRENT_LOCAL_TASK_STATE.with(|ts| {
let CurrentLocalTaskState {
execution_id: expected_execution_id,
..
} = ts;
assert_eq!(
&execution_id, expected_execution_id,
"This Vc is local. Local Vcs must only be accessed within their own task. Resolve the \
Vc to convert it into a non-local version."
);
})
}
......@@ -143,10 +143,6 @@ pub struct FunctionMeta {
/// task-local state. The function call itself will not be cached, but cells will be created on
/// the parent task.
pub local: bool,
/// Changes the behavior of `Vc::cell` to create local cells that are not
/// cached across task executions. Cells can be converted to their non-local
/// versions by calling `Vc::resolve`.
pub local_cells: bool,
}
/// A native (rust) turbo-tasks function. It's used internally by
......@@ -241,7 +237,7 @@ impl NativeFunction {
tracing::trace_span!(
"turbo_tasks::function",
name = self.name.as_str(),
local_cells = true,
local = true,
)
}
}
......
......@@ -8,10 +8,9 @@ use thiserror::Error;
use crate::{
backend::{CellContent, TypedCellContent},
event::EventListener,
id::{ExecutionId, LocalCellId, LocalTaskId},
id::LocalTaskId,
manager::{
assert_execution_id, current_task, read_local_cell, read_local_output, read_task_cell,
read_task_output, with_turbo_tasks, TurboTasksApi,
read_local_output, read_task_cell, read_task_output, with_turbo_tasks, TurboTasksApi,
},
registry::{self, get_value_type},
turbo_tasks, CollectiblesSource, ReadConsistency, TaskId, TraitTypeId, ValueType, ValueTypeId,
......@@ -61,8 +60,6 @@ pub enum RawVc {
TaskOutput(TaskId),
TaskCell(TaskId, CellId),
LocalOutput(TaskId, LocalTaskId),
#[serde(skip)]
LocalCell(ExecutionId, LocalCellId),
}
impl RawVc {
......@@ -71,7 +68,6 @@ impl RawVc {
RawVc::TaskOutput(_) => false,
RawVc::TaskCell(_, _) => true,
RawVc::LocalOutput(_, _) => false,
RawVc::LocalCell(_, _) => false,
}
}
......@@ -80,7 +76,6 @@ impl RawVc {
RawVc::TaskOutput(_) => false,
RawVc::TaskCell(_, _) => false,
RawVc::LocalOutput(_, _) => true,
RawVc::LocalCell(_, _) => true,
}
}
......@@ -89,8 +84,6 @@ impl RawVc {
RawVc::TaskOutput(task) | RawVc::TaskCell(task, _) | RawVc::LocalOutput(task, _) => {
task.is_transient()
}
// TODO track the transient flag in the highest bit of the execution id
RawVc::LocalCell(_, _) => todo!(),
}
}
......@@ -177,24 +170,11 @@ impl RawVc {
return Err(ResolveTypeError::NoContent);
}
}
RawVc::LocalOutput(task_id, local_cell_id) => {
current = read_local_output(&*tt, task_id, local_cell_id)
RawVc::LocalOutput(task_id, local_task_id) => {
current = read_local_output(&*tt, task_id, local_task_id)
.await
.map_err(|source| ResolveTypeError::TaskError { source })?;
}
RawVc::LocalCell(execution_id, local_cell_id) => {
let shared_reference = read_local_cell(execution_id, local_cell_id);
return Ok(
if let (true, value_type) = conditional(shared_reference.0) {
// re-use the `ValueType` lookup from `conditional`, if it exists
let value_type =
value_type.unwrap_or_else(|| get_value_type(shared_reference.0));
Some((value_type.raw_cell)(shared_reference))
} else {
None
},
);
}
}
}
}
......@@ -227,15 +207,9 @@ impl RawVc {
consistency = ReadConsistency::Eventual;
}
RawVc::TaskCell(_, _) => return Ok(current),
RawVc::LocalOutput(task_id, local_cell_id) => {
debug_assert_eq!(consistency, ReadConsistency::Eventual);
current = read_local_output(&*tt, task_id, local_cell_id).await?;
}
RawVc::LocalCell(execution_id, local_cell_id) => {
RawVc::LocalOutput(task_id, local_task_id) => {
debug_assert_eq!(consistency, ReadConsistency::Eventual);
let shared_reference = read_local_cell(execution_id, local_cell_id);
let value_type = get_value_type(shared_reference.0);
return Ok((value_type.raw_cell)(shared_reference));
current = read_local_output(&*tt, task_id, local_task_id).await?;
}
}
}
......@@ -248,13 +222,8 @@ impl RawVc {
let mut current = self;
loop {
match current {
RawVc::LocalOutput(task_id, local_cell_id) => {
current = read_local_output(&*tt, task_id, local_cell_id).await?;
}
RawVc::LocalCell(execution_id, local_cell_id) => {
let shared_reference = read_local_cell(execution_id, local_cell_id);
let value_type = get_value_type(shared_reference.0);
return Ok((value_type.raw_cell)(shared_reference));
RawVc::LocalOutput(task_id, local_task_id) => {
current = read_local_output(&*tt, task_id, local_task_id).await?;
}
non_local => return Ok(non_local),
}
......@@ -269,10 +238,6 @@ impl RawVc {
pub fn get_task_id(&self) -> TaskId {
match self {
RawVc::TaskOutput(t) | RawVc::TaskCell(t, _) | RawVc::LocalOutput(t, _) => *t,
RawVc::LocalCell(execution_id, _) => {
assert_execution_id(*execution_id);
current_task("RawVc::get_task_id")
}
}
}
......@@ -436,12 +401,6 @@ impl Future for ReadRawVcFuture {
Err(err) => return Poll::Ready(Err(err)),
}
}
RawVc::LocalCell(execution_id, local_cell_id) => {
debug_assert_eq!(this.consistency, ReadConsistency::Eventual);
return Poll::Ready(
Ok(read_local_cell(execution_id, local_cell_id).into()),
);
}
};
// SAFETY: listener is from previous pinned this
match unsafe { Pin::new_unchecked(&mut listener) }.poll(cx) {
......
......@@ -31,10 +31,9 @@ pub use self::{
};
use crate::{
debug::{ValueDebug, ValueDebugFormat, ValueDebugFormatString},
manager::{create_local_cell, try_get_function_meta},
registry,
trace::{TraceRawVcs, TraceRawVcsContext},
CellId, RawVc, ResolveTypeError, SharedReference, ShrinkToFit,
CellId, RawVc, ResolveTypeError, ShrinkToFit,
};
/// A "Value Cell" (`Vc` for short) is a reference to a memoized computation result stored on the
......@@ -367,38 +366,7 @@ where
pub fn cell_private(mut inner: <T::Read as VcRead<T>>::Target) -> Self {
// cell contents are immutable, so go ahead and shrink the cell's contents
ShrinkToFit::shrink_to_fit(<T::Read as VcRead<T>>::target_to_value_mut_ref(&mut inner));
if try_get_function_meta()
.map(|meta| meta.local_cells)
.unwrap_or(false)
{
Self::local_cell_private(inner)
} else {
<T::CellMode as VcCellMode<T>>::cell(inner)
}
}
// called by the `.local_cell()` method generated by the `#[turbo_tasks::value]`
// macro
#[doc(hidden)]
pub fn local_cell_private(mut inner: <T::Read as VcRead<T>>::Target) -> Self {
// Cell contents are immutable, so go ahead and shrink the cell's contents. Ideally we'd
// wait until the cell is upgraded from local to global to pay the cost of shrinking, but by
// that point it's too late to get a mutable reference (the `SharedReference` type has
// already been constructed).
ShrinkToFit::shrink_to_fit(<T::Read as VcRead<T>>::target_to_value_mut_ref(&mut inner));
// `T::CellMode` isn't applicable here, we always create new local cells. Local
// cells aren't stored across executions, so there can be no concept of
// "updating" the cell across multiple executions.
let (execution_id, local_cell_id) = create_local_cell(
SharedReference::new(triomphe::Arc::new(T::Read::target_to_repr(inner)))
.into_typed(T::get_value_type_id()),
);
Vc {
node: RawVc::LocalCell(execution_id, local_cell_id),
_t: PhantomData,
}
<T::CellMode as VcCellMode<T>>::cell(inner)
}
}
......@@ -411,13 +379,6 @@ where
pub fn cell(inner: Inner) -> Self {
Self::cell_private(inner)
}
pub fn local_cell(inner: Inner) -> Self {
// `T::CellMode` isn't applicable here, we always create new local cells. Local
// cells aren't stored across executions, so there can be no concept of
// "updating" the cell across multiple executions.
Self::local_cell_private(inner)
}
}
impl<T> Vc<T>
......@@ -488,8 +449,8 @@ where
self.node.is_resolved()
}
/// Returns `true` if the Vc was created inside a task with
/// [`#[turbo_tasks::function(local_cells)]`][crate::function] and has not yet been resolved.
/// Returns `true` if the `Vc` was by a local function call (e.g. one who's arguments were not
/// fully resolved) and has not yet been resolved.
///
/// Aside from differences in caching, a function's behavior should not be changed by using
/// local or non-local cells, so this function is mostly useful inside tests and internally in
......
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