Unverified Commit 89f3649a authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

Turbopack: Panic if a top-level task attempts an eventually consistent read (#89735)

We've had some really bad bugs in the past, which can be hard to root-cause due to eventually-consistent reads a the top-level, e.g. https://github.com/vercel/next.js/pull/77511

Outside of tests, there's no good justification for doing an eventually-consistent read at the top level. It may leak incomplete computations, which can contain errors that would otherwise be resolved by a strongly consistent read.

The basic idea here is simple:

- Store a flag in `CURRENT_TASK_STATE` indicating that we're in a top-level task.
- When reading a task output or cell, check for that flag.

But, there are a few complications:

- `RawVc`'s read and resolution logic is wrong, and internally uses multiple eventually consistent operations after a strongly consistent read.
    - For this to be correct, it needs to happen as one atomic operation inside of the task backend, but it would change the backend API contract, so it's not straightforward to do that.
    - I added a `SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK` flag that I'm using for now.
- There are a ton of places that are doing eventually consistent reads for no good reason. These aren't causing problems today, but we should fix them instead of suppressing them. Claude helped with this, but it's still a lot.
- Some tests actually do need eventually-consistent reads because they're testing some internal behavior of turbo-tasks. I added an intentionally long-named `unmark_top_level_task_may_leak_eventually_consistent_state` helper for this.

I manually tested `turbopack-cli` against our bundler-benchmark repository that uses it.
parent 8f5afa35
...@@ -9676,6 +9676,7 @@ dependencies = [ ...@@ -9676,6 +9676,7 @@ dependencies = [
"serde", "serde",
"tokio", "tokio",
"trybuild", "trybuild",
"turbo-rcstr",
"turbo-tasks", "turbo-tasks",
"turbo-tasks-backend", "turbo-tasks-backend",
"turbo-tasks-testing", "turbo-tasks-testing",
......
...@@ -291,10 +291,8 @@ impl DebugBuildPathsRouteKeys { ...@@ -291,10 +291,8 @@ impl DebugBuildPathsRouteKeys {
Serialize, Serialize,
Deserialize, Deserialize,
Clone, Clone,
TaskInput,
PartialEq, PartialEq,
Eq, Eq,
Hash,
TraceRawVcs, TraceRawVcs,
NonLocalValue, NonLocalValue,
OperationValue, OperationValue,
...@@ -458,8 +456,8 @@ pub struct ProjectContainer { ...@@ -458,8 +456,8 @@ pub struct ProjectContainer {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ProjectContainer { impl ProjectContainer {
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
pub fn new(name: RcStr, dev: bool) -> Result<Vc<Self>> { pub fn new_operation(name: RcStr, dev: bool) -> Result<Vc<Self>> {
Ok(ProjectContainer { Ok(ProjectContainer {
name, name,
// we only need to enable versioning in dev mode, since build // we only need to enable versioning in dev mode, since build
...@@ -566,10 +564,18 @@ fn define_env_diff_report(old: &DefineEnv, new: &DefineEnv) -> String { ...@@ -566,10 +564,18 @@ fn define_env_diff_report(old: &DefineEnv, new: &DefineEnv) -> String {
} }
impl ProjectContainer { impl ProjectContainer {
pub async fn initialize(self: ResolvedVc<Self>, options: ProjectOptions) -> Result<()> { /// Set up filesystems, watchers, and construct the [`Project`] instance inside the container.
///
/// This function is intended to be called inside of [`turbo_tasks::TurboTasks::run`], but not
/// part of a [`turbo_tasks::function`]. We don't want it to be possibly re-executed.
///
/// This is an associated function instead of a method because we don't currently implement
/// [`std::ops::Receiver`] on [`OperationVc`].
pub async fn initialize(this_op: OperationVc<Self>, options: ProjectOptions) -> Result<()> {
let this = this_op.read_strongly_consistent().await?;
let span = tracing::info_span!( let span = tracing::info_span!(
"initialize project", "initialize project",
project_name = %self.await?.name, project_name = %this.name,
version = options.next_version.as_str(), version = options.next_version.as_str(),
env_diff = Empty env_diff = Empty
); );
...@@ -577,7 +583,6 @@ impl ProjectContainer { ...@@ -577,7 +583,6 @@ impl ProjectContainer {
async move { async move {
let watch = options.watch; let watch = options.watch;
let this = self.await?;
if let Some(old_options) = &*this.options_state.get_untracked() { if let Some(old_options) = &*this.options_state.get_untracked() {
span.record( span.record(
"env_diff", "env_diff",
...@@ -586,7 +591,15 @@ impl ProjectContainer { ...@@ -586,7 +591,15 @@ impl ProjectContainer {
} }
this.options_state.set(Some(options)); this.options_state.set(Some(options));
let project = self.project().to_resolved().await?; #[turbo_tasks::function(operation)]
fn project_from_container_operation(
container: OperationVc<ProjectContainer>,
) -> Vc<Project> {
container.connect().project()
}
let project = project_from_container_operation(this_op)
.resolve_strongly_consistent()
.await?;
let project_fs = project_fs_operation(project) let project_fs = project_fs_operation(project)
.read_strongly_consistent() .read_strongly_consistent()
.await?; .await?;
...@@ -612,7 +625,7 @@ impl ProjectContainer { ...@@ -612,7 +625,7 @@ impl ProjectContainer {
.await .await
} }
pub async fn update(self: Vc<Self>, options: PartialProjectOptions) -> Result<()> { pub async fn update(self: ResolvedVc<Self>, options: PartialProjectOptions) -> Result<()> {
let span = tracing::info_span!( let span = tracing::info_span!(
"update project options", "update project options",
project_name = %self.await?.name, project_name = %self.await?.name,
...@@ -620,6 +633,20 @@ impl ProjectContainer { ...@@ -620,6 +633,20 @@ impl ProjectContainer {
); );
let span_clone = span.clone(); let span_clone = span.clone();
async move { async move {
// HACK: `update` is called from a top-level function. Top-level functions are not
// allowed to perform eventually consistent reads. Create a stub operation
// to upgrade the `ResolvedVc` to an `OperationVc`. This is mostly okay
// because we can assume the `ProjectContainer` was originally resolved with
// strong consistency, and is rarely updated.
#[turbo_tasks::function(operation)]
fn project_container_operation_hack(
container: ResolvedVc<ProjectContainer>,
) -> Vc<ProjectContainer> {
*container
}
let this = project_container_operation_hack(self)
.read_strongly_consistent()
.await?;
let PartialProjectOptions { let PartialProjectOptions {
root_path, root_path,
project_path, project_path,
...@@ -637,9 +664,6 @@ impl ProjectContainer { ...@@ -637,9 +664,6 @@ impl ProjectContainer {
debug_build_paths, debug_build_paths,
} = options; } = options;
let resolved_self = self.to_resolved().await?;
let this = resolved_self.await?;
let mut new_options = this let mut new_options = this
.options_state .options_state
.get() .get()
...@@ -692,7 +716,7 @@ impl ProjectContainer { ...@@ -692,7 +716,7 @@ impl ProjectContainer {
// TODO: Handle mode switch, should prevent mode being switched. // TODO: Handle mode switch, should prevent mode being switched.
let watch = new_options.watch; let watch = new_options.watch;
let project = project_operation(resolved_self) let project = project_operation(self)
.resolve_strongly_consistent() .resolve_strongly_consistent()
.await?; .await?;
let prev_project_fs = project_fs_operation(project) let prev_project_fs = project_fs_operation(project)
...@@ -710,7 +734,7 @@ impl ProjectContainer { ...@@ -710,7 +734,7 @@ impl ProjectContainer {
); );
} }
this.options_state.set(Some(new_options)); this.options_state.set(Some(new_options));
let project = project_operation(resolved_self) let project = project_operation(self)
.resolve_strongly_consistent() .resolve_strongly_consistent()
.await?; .await?;
let project_fs = project_fs_operation(project) let project_fs = project_fs_operation(project)
......
...@@ -8,6 +8,7 @@ use std::{str::FromStr, time::Instant}; ...@@ -8,6 +8,7 @@ use std::{str::FromStr, time::Instant};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use futures_util::{StreamExt, TryStreamExt}; use futures_util::{StreamExt, TryStreamExt};
use next_api::{ use next_api::{
entrypoints::Entrypoints,
project::{HmrTarget, ProjectContainer, ProjectOptions}, project::{HmrTarget, ProjectContainer, ProjectOptions},
route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk}, route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk},
}; };
...@@ -39,15 +40,25 @@ pub async fn main_inner( ...@@ -39,15 +40,25 @@ pub async fn main_inner(
let project = tt let project = tt
.run(async { .run(async {
let project = ProjectContainer::new(rcstr!("next-build-test"), options.dev); let container_op = ProjectContainer::new_operation(rcstr!("next.js"), options.dev);
let project = project.to_resolved().await?; ProjectContainer::initialize(container_op, options).await?;
project.initialize(options).await?; container_op.resolve_strongly_consistent().await
Ok(project)
}) })
.await?; .await?;
tracing::info!("collecting endpoints"); tracing::info!("collecting endpoints");
let entrypoints = tt.run(async move { project.entrypoints().await }).await?;
#[turbo_tasks::function(operation)]
fn project_entrypoints_operation(project: ResolvedVc<ProjectContainer>) -> Vc<Entrypoints> {
project.entrypoints()
}
let entrypoints = tt
.run(async move {
project_entrypoints_operation(project)
.read_strongly_consistent()
.await
})
.await?;
let mut routes = if let Some(files) = files { let mut routes = if let Some(files) = files {
tracing::info!("building only the files:"); tracing::info!("building only the files:");
...@@ -84,7 +95,7 @@ pub async fn main_inner( ...@@ -84,7 +95,7 @@ pub async fn main_inner(
} }
if matches!(strategy, Strategy::Development { .. }) { if matches!(strategy, Strategy::Development { .. }) {
hmr(tt, *project).await?; hmr(tt, project).await?;
} }
Ok(()) Ok(())
...@@ -252,13 +263,24 @@ pub fn endpoint_write_to_disk_operation( ...@@ -252,13 +263,24 @@ pub fn endpoint_write_to_disk_operation(
async fn hmr( async fn hmr(
tt: &TurboTasks<TurboTasksBackend<NoopBackingStorage>>, tt: &TurboTasks<TurboTasksBackend<NoopBackingStorage>>,
project: Vc<ProjectContainer>, project: ResolvedVc<ProjectContainer>,
) -> Result<()> { ) -> Result<()> {
tracing::info!("HMR..."); tracing::info!("HMR...");
let session = TransientInstance::new(()); let session = TransientInstance::new(());
#[turbo_tasks::function(operation)]
fn project_hmr_chunk_names_operation(project: ResolvedVc<ProjectContainer>) -> Vc<Vec<RcStr>> {
project.hmr_chunk_names(HmrTarget::Client)
}
let idents = tt let idents = tt
.run(async move { project.hmr_chunk_names(HmrTarget::Client).await }) .run(async move {
project_hmr_chunk_names_operation(project)
.read_strongly_consistent()
.await
})
.await?; .await?;
let start = Instant::now(); let start = Instant::now();
for ident in idents { for ident in idents {
if !ident.ends_with(".js") { if !ident.ends_with(".js") {
......
...@@ -3,7 +3,7 @@ use std::time::{Duration, Instant}; ...@@ -3,7 +3,7 @@ use std::time::{Duration, Instant};
use criterion::{BenchmarkId, Criterion, black_box}; use criterion::{BenchmarkId, Criterion, black_box};
use futures::{FutureExt, StreamExt, stream::FuturesUnordered}; use futures::{FutureExt, StreamExt, stream::FuturesUnordered};
use tokio::spawn; use tokio::spawn;
use turbo_tasks::TurboTasks; use turbo_tasks::{TurboTasks, unmark_top_level_task_may_leak_eventually_consistent_state};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
#[global_allocator] #[global_allocator]
...@@ -183,6 +183,7 @@ fn run_turbo<Mode: TurboMode>( ...@@ -183,6 +183,7 @@ fn run_turbo<Mode: TurboMode>(
async move { async move {
tt.run(async move { tt.run(async move {
unmark_top_level_task_may_leak_eventually_consistent_state();
// If cached run once outside the loop to ensure the tasks are cached. // If cached run once outside the loop to ensure the tasks are cached.
if Mode::is_cached() { if Mode::is_cached() {
for i in 0..iters { for i in 0..iters {
......
...@@ -49,7 +49,9 @@ pub fn scope_stress(c: &mut Criterion) { ...@@ -49,7 +49,9 @@ pub fn scope_stress(c: &mut Criterion) {
async move { async move {
Ok(tt Ok(tt
.run(async move { .run(async move {
rectangle(a, b).strongly_consistent().await?; rectangle_operation(a, b)
.read_strongly_consistent()
.await?;
Ok(()) Ok(())
}) })
.await?) .await?)
...@@ -69,13 +71,13 @@ pub fn scope_stress(c: &mut Criterion) { ...@@ -69,13 +71,13 @@ pub fn scope_stress(c: &mut Criterion) {
/// This fills a rectagle from (0, 0) to (a, b) by /// This fills a rectagle from (0, 0) to (a, b) by
/// first filling (0, 0) to (a - 1, b) and then (0, 0) to (a, b - 1) recursively /// first filling (0, 0) to (a - 1, b) and then (0, 0) to (a, b - 1) recursively
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
async fn rectangle(a: u32, b: u32) -> Result<Vc<Completion>> { async fn rectangle_operation(a: u32, b: u32) -> Result<Vc<Completion>> {
if a > 0 { if a > 0 {
rectangle(a - 1, b).await?; rectangle_operation(a - 1, b).connect().await?;
} }
if b > 0 { if b > 0 {
rectangle(a, b - 1).await?; rectangle_operation(a, b - 1).connect().await?;
} }
Ok(Completion::new()) Ok(Completion::new())
} }
use anyhow::Result; use anyhow::Result;
use criterion::{BenchmarkId, Criterion}; use criterion::{BenchmarkId, Criterion};
use turbo_tasks::{TryJoinIterExt, TurboTasks, Vc}; use turbo_tasks::{
TryJoinIterExt, TurboTasks, Vc, unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
pub fn fibonacci(c: &mut Criterion) { pub fn fibonacci(c: &mut Criterion) {
...@@ -38,6 +40,7 @@ pub fn fibonacci(c: &mut Criterion) { ...@@ -38,6 +40,7 @@ pub fn fibonacci(c: &mut Criterion) {
)); ));
async move { async move {
tt.run(async move { tt.run(async move {
unmark_top_level_task_may_leak_eventually_consistent_state();
// Number of tasks: // Number of tasks:
// 1 root task // 1 root task
// size >= 1 => + fib(0) = 1 // size >= 1 => + fib(0) = 1
......
...@@ -10,56 +10,70 @@ use turbo_tasks_testing::{Registration, register, run_once}; ...@@ -10,56 +10,70 @@ use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn all_in_one() { async fn test_all_in_one() {
run_once(&REGISTRATION, || async { let mut nonce = 0;
let a: Vc<u32> = Vc::cell(4242); run_once(&REGISTRATION, move || {
assert_eq!(*a.await?, 4242); // pass a nonce to re-run the test body on every turbo-tasks restart
nonce += 1;
async move {
test_all_in_one_operation(nonce)
.read_strongly_consistent()
.await
}
})
.await
.unwrap()
}
let a: Vc<MyTransparentValue> = Vc::cell(4242); #[turbo_tasks::function(operation)]
assert_eq!(*a.await?, 4242); async fn test_all_in_one_operation(nonce: u32) -> Result<Vc<()>> {
let _ = nonce; // ensure the nonce is part of our cache key
let b = MyEnumValue::cell(MyEnumValue::More(MyEnumValue::Yeah(42).resolved_cell())); let a: Vc<u32> = Vc::cell(4242);
assert_eq!(*b.to_string().await?, "42"); assert_eq!(*a.await?, 4242);
let c = MyStructValue { let a: Vc<MyTransparentValue> = Vc::cell(4242);
value: 42, assert_eq!(*a.await?, 4242);
next: Some(MyStructValue::new(a).to_resolved().await?),
}
.cell();
let result = my_function(a, b.get_last(), c, MyEnumValue::Yeah(42)); let b = MyEnumValue::cell(MyEnumValue::More(MyEnumValue::Yeah(42).resolved_cell()));
assert_eq!(*result.my_trait_function().await?, "42"); assert_eq!(*b.to_string().await?, "42");
assert_eq!(*result.my_trait_function2().await?, "42");
assert_eq!(*result.my_trait_function3().await?, "4242");
assert_eq!(*result.to_string().await?, "42");
// Testing Vc<Self> in traits let c = MyStructValue {
value: 42,
next: Some(MyStructValue::new(a).to_resolved().await?),
}
.cell();
let a: Vc<Number> = Vc::cell(32); let result = my_function(a, b.get_last(), c, MyEnumValue::Yeah(42));
let b: Vc<Number> = Vc::cell(10); assert_eq!(*result.my_trait_function().await?, "42");
let c: Vc<Number> = a.add(Vc::upcast(b)); assert_eq!(*result.my_trait_function2().await?, "42");
assert_eq!(*result.my_trait_function3().await?, "4242");
assert_eq!(*result.to_string().await?, "42");
assert_eq!(*c.await?, 42); // Testing Vc<Self> in traits
let a_erased: Vc<Box<dyn Add>> = Vc::upcast(a); let a: Vc<Number> = Vc::cell(32);
let b_erased: Vc<Box<dyn Add>> = Vc::upcast(b); let b: Vc<Number> = Vc::cell(10);
let c_erased: Vc<Box<dyn Add>> = a_erased.add(b_erased); let c: Vc<Number> = a.add(Vc::upcast(b));
assert_eq!( assert_eq!(*c.await?, 42);
*ResolvedVc::try_downcast_type::<Number>(c_erased.to_resolved().await?)
.unwrap()
.await?,
42
);
let b_erased_other: Vc<Box<dyn Add>> = Vc::upcast(Vc::<NumberB>::cell(10)); let a_erased: Vc<Box<dyn Add>> = Vc::upcast(a);
let c_erased_invalid: Vc<Box<dyn Add>> = a_erased.add(b_erased_other); let b_erased: Vc<Box<dyn Add>> = Vc::upcast(b);
assert!(c_erased_invalid.resolve().await.is_err()); let c_erased: Vc<Box<dyn Add>> = a_erased.add(b_erased);
anyhow::Ok(()) assert_eq!(
}) *ResolvedVc::try_downcast_type::<Number>(c_erased.to_resolved().await?)
.await .unwrap()
.unwrap() .await?,
42
);
let b_erased_other: Vc<Box<dyn Add>> = Vc::upcast(Vc::<NumberB>::cell(10));
let c_erased_invalid: Vc<Box<dyn Add>> = a_erased.add(b_erased_other);
assert!(c_erased_invalid.resolve().await.is_err());
Ok(Vc::cell(()))
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
......
...@@ -9,28 +9,38 @@ use turbo_tasks_testing::{Registration, register, run_once}; ...@@ -9,28 +9,38 @@ use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn basic() { async fn test_basic() {
run_once(&REGISTRATION, || async { let mut nonce = 0;
let output1 = func_without_args(); run_once(&REGISTRATION, move || {
assert_eq!(output1.await?.value, 123); // pass a nonce to re-run the test body on every turbo-tasks restart
nonce += 1;
async move { test_basic_operation(nonce).read_strongly_consistent().await }
})
.await
.unwrap()
}
let input = Value { value: 42 }.cell(); #[turbo_tasks::function(operation)]
let output2 = func_transient(input); async fn test_basic_operation(nonce: u32) -> Result<Vc<()>> {
assert_eq!(output2.await?.value, 42); let _ = nonce; // ensure the nonce is part of our cache key
let output3 = func_persistent(output1); let output1 = func_without_args();
assert_eq!(output3.await?.value, 123); assert_eq!(output1.await?.value, 123);
let output4 = nested_func_without_args_waiting(); let input = Value { value: 42 }.cell();
assert_eq!(output4.await?.value, 123); let output2 = func_transient(input);
assert_eq!(output2.await?.value, 42);
let output5 = nested_func_without_args_non_waiting(); let output3 = func_persistent(output1);
assert_eq!(output5.await?.value, 123); assert_eq!(output3.await?.value, 123);
anyhow::Ok(()) let output4 = nested_func_without_args_waiting();
}) assert_eq!(output4.await?.value, 123);
.await
.unwrap() let output5 = nested_func_without_args_non_waiting();
assert_eq!(output5.await?.value, 123);
Ok(Vc::cell(()))
} }
#[turbo_tasks::value] #[turbo_tasks::value]
......
...@@ -25,157 +25,169 @@ struct TaskSpec { ...@@ -25,157 +25,169 @@ struct TaskSpec {
struct TasksSpec(Vec<TaskSpec>); struct TasksSpec(Vec<TaskSpec>);
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn graph_bug() { async fn test_graph_bug() {
let mut nonce = 0;
run_once(&REGISTRATION, move || async move {
// pass a nonce to re-run the test body on every turbo-tasks restart
nonce += 1;
test_graph_bug_operation(nonce)
.read_strongly_consistent()
.await
})
.await
.unwrap()
}
#[turbo_tasks::function(operation)]
async fn test_graph_bug_operation(nonce: u32) -> Result<Vc<()>> {
let _ = nonce; // ensure the nonce is part of our cache key
// see https://github.com/vercel/next.js/pull/79451 // see https://github.com/vercel/next.js/pull/79451
run_once(&REGISTRATION, || async { let spec = vec![
let spec = vec![ TaskSpec {
TaskSpec { references: vec![
references: vec![ TaskReferenceSpec {
TaskReferenceSpec { task: 3,
task: 3, read: false,
read: false, read_strongly_consistent: true,
read_strongly_consistent: true, },
}, TaskReferenceSpec {
TaskReferenceSpec { task: 1,
task: 1,
read: true,
read_strongly_consistent: false,
},
TaskReferenceSpec {
task: 12,
read: false,
read_strongly_consistent: true,
},
],
},
TaskSpec {
references: vec![TaskReferenceSpec {
task: 2,
read: true, read: true,
read_strongly_consistent: false,
},
TaskReferenceSpec {
task: 12,
read: false,
read_strongly_consistent: true, read_strongly_consistent: true,
}], },
}, ],
TaskSpec { },
references: vec![TaskReferenceSpec { TaskSpec {
task: 4, references: vec![TaskReferenceSpec {
task: 2,
read: true,
read_strongly_consistent: true,
}],
},
TaskSpec {
references: vec![TaskReferenceSpec {
task: 4,
read: false,
read_strongly_consistent: false,
}],
},
TaskSpec {
references: vec![TaskReferenceSpec {
task: 6,
read: false,
read_strongly_consistent: false,
}],
},
TaskSpec {
references: vec![
TaskReferenceSpec {
task: 5,
read: false, read: false,
read_strongly_consistent: false, read_strongly_consistent: false,
}], },
}, TaskReferenceSpec {
TaskSpec { task: 13,
references: vec![TaskReferenceSpec {
task: 6,
read: false, read: false,
read_strongly_consistent: false, read_strongly_consistent: false,
}], },
}, ],
TaskSpec { },
references: vec![ TaskSpec {
TaskReferenceSpec { references: vec![
task: 5, TaskReferenceSpec {
read: false, task: 11,
read_strongly_consistent: false, read: false,
}, read_strongly_consistent: true,
TaskReferenceSpec { },
task: 13, TaskReferenceSpec {
read: false, task: 14,
read_strongly_consistent: false, read: false,
}, read_strongly_consistent: false,
], },
}, TaskReferenceSpec {
TaskSpec { task: 7,
references: vec![
TaskReferenceSpec {
task: 11,
read: false,
read_strongly_consistent: true,
},
TaskReferenceSpec {
task: 14,
read: false,
read_strongly_consistent: false,
},
TaskReferenceSpec {
task: 7,
read: false,
read_strongly_consistent: false,
},
TaskReferenceSpec {
task: 8,
read: false,
read_strongly_consistent: false,
},
],
},
TaskSpec {
references: vec![TaskReferenceSpec {
task: 9,
read: false, read: false,
read_strongly_consistent: false, read_strongly_consistent: false,
}], },
}, TaskReferenceSpec {
TaskSpec { references: vec![] }, task: 8,
TaskSpec {
references: vec![
TaskReferenceSpec {
task: 12,
read: false,
read_strongly_consistent: false,
},
TaskReferenceSpec {
task: 11,
read: false,
read_strongly_consistent: false,
},
],
},
TaskSpec {
references: vec![TaskReferenceSpec {
task: 10,
read: false, read: false,
read_strongly_consistent: false, read_strongly_consistent: false,
}], },
}, ],
TaskSpec { },
references: vec![TaskReferenceSpec { TaskSpec {
references: vec![TaskReferenceSpec {
task: 9,
read: false,
read_strongly_consistent: false,
}],
},
TaskSpec { references: vec![] },
TaskSpec {
references: vec![
TaskReferenceSpec {
task: 12, task: 12,
read: false, read: false,
read_strongly_consistent: false, read_strongly_consistent: false,
}], },
}, TaskReferenceSpec {
TaskSpec { references: vec![] }, task: 11,
TaskSpec {
references: vec![TaskReferenceSpec {
task: 14,
read: false, read: false,
read_strongly_consistent: false, read_strongly_consistent: false,
}], },
}, ],
TaskSpec { references: vec![] }, },
TaskSpec { TaskSpec {
references: vec![ references: vec![TaskReferenceSpec {
TaskReferenceSpec { task: 10,
task: 16, read: false,
read: false, read_strongly_consistent: false,
read_strongly_consistent: true, }],
}, },
TaskReferenceSpec { TaskSpec {
task: 15, references: vec![TaskReferenceSpec {
read: false, task: 12,
read_strongly_consistent: true, read: false,
}, read_strongly_consistent: false,
], }],
}, },
TaskSpec { references: vec![] }, TaskSpec { references: vec![] },
TaskSpec { references: vec![] }, TaskSpec {
]; references: vec![TaskReferenceSpec {
let spec: Vc<TasksSpec> = Vc::cell(spec); task: 14,
run_task(spec, 0).await?; read: false,
read_strongly_consistent: false,
}],
},
TaskSpec { references: vec![] },
TaskSpec {
references: vec![
TaskReferenceSpec {
task: 16,
read: false,
read_strongly_consistent: true,
},
TaskReferenceSpec {
task: 15,
read: false,
read_strongly_consistent: true,
},
],
},
TaskSpec { references: vec![] },
TaskSpec { references: vec![] },
];
let spec: Vc<TasksSpec> = Vc::cell(spec);
run_task(spec, 0).await?;
anyhow::Ok(()) Ok(Vc::cell(()))
})
.await
.unwrap()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -34,49 +34,63 @@ pub struct TaskSpec { ...@@ -34,49 +34,63 @@ pub struct TaskSpec {
struct Iteration(State<usize>); struct Iteration(State<usize>);
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn graph_bug() { async fn test_graph_bug() {
run_once(&REGISTRATION, move || async move { let mut nonce = 0;
let spec = vec![ run_once(&REGISTRATION, move || {
TaskSpec { // pass a nonce to re-run the test body on every turbo-tasks restart
nonce += 1;
async move {
test_graph_bug_operation(nonce)
.read_strongly_consistent()
.await
}
})
.await
.unwrap()
}
#[turbo_tasks::function(operation)]
async fn test_graph_bug_operation(nonce: u32) -> Result<Vc<()>> {
let _ = nonce; // ensure the nonce is part of our cache key
let spec = vec![
TaskSpec {
references: vec![TaskReferenceSpec {
task: 1,
chain: 0,
read: false,
read_strongly_consistent: false,
}],
children: 0,
change: Some(Box::new(TaskSpec {
references: vec![TaskReferenceSpec { references: vec![TaskReferenceSpec {
task: 1, task: 1,
chain: 0, chain: 254,
read: false, read: false,
read_strongly_consistent: false, read_strongly_consistent: false,
}], }],
children: 0, children: 0,
change: Some(Box::new(TaskSpec {
references: vec![TaskReferenceSpec {
task: 1,
chain: 254,
read: false,
read_strongly_consistent: false,
}],
children: 0,
change: None,
})),
},
TaskSpec {
references: vec![],
children: 0,
change: None, change: None,
}, })),
]; },
TaskSpec {
references: vec![],
children: 0,
change: None,
},
];
let it = create_iteration().resolve().await?; let it = create_iteration().resolve().await?;
it.await?.set(0); it.await?.set(0);
println!("🚀 Initial"); println!("🚀 Initial");
let task = run_task(Arc::new(spec), it, 0); let task = run_task(Arc::new(spec), it, 0);
task.strongly_consistent().await?; task.strongly_consistent().await?;
println!("🚀 Set iteration to 1"); println!("🚀 Set iteration to 1");
it.await?.set(1); it.await?.set(1);
task.strongly_consistent().await?; task.strongly_consistent().await?;
println!("🚀 Finished strongly consistent wait"); println!("🚀 Finished strongly consistent wait");
anyhow::Ok(()) Ok(Vc::cell(()))
})
.await
.unwrap()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -9,20 +9,34 @@ use turbo_tasks_testing::{Registration, register, run_once}; ...@@ -9,20 +9,34 @@ use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn functions() { async fn test_functions() {
run_once(&REGISTRATION, || async { let mut nonce = 0;
assert_eq!(*fn_plain().await?, 42); run_once(&REGISTRATION, move || {
assert_eq!(*fn_arg(43).await?, 43); // pass a nonce to re-run the test body on every turbo-tasks restart
assert_eq!(*fn_vc_arg(Vc::cell(44)).await?, 44); nonce += 1;
assert_eq!(*async_fn_plain().await?, 42); async move {
assert_eq!(*async_fn_arg(43).await?, 43); test_functions_operation(nonce)
assert_eq!(*async_fn_vc_arg(Vc::cell(44)).await?, 44); .read_strongly_consistent()
anyhow::Ok(()) .await
}
}) })
.await .await
.unwrap() .unwrap()
} }
#[turbo_tasks::function(operation)]
async fn test_functions_operation(nonce: u32) -> Result<Vc<()>> {
let _ = nonce; // ensure the nonce is part of our cache key
assert_eq!(*fn_plain().await?, 42);
assert_eq!(*fn_arg(43).await?, 43);
assert_eq!(*fn_vc_arg(Vc::cell(44)).await?, 44);
assert_eq!(*async_fn_plain().await?, 42);
assert_eq!(*async_fn_arg(43).await?, 43);
assert_eq!(*async_fn_vc_arg(Vc::cell(44)).await?, 44);
Ok(Vc::cell(()))
}
#[turbo_tasks::function] #[turbo_tasks::function]
fn fn_plain() -> Vc<u32> { fn fn_plain() -> Vc<u32> {
Vc::cell(42) Vc::cell(42)
...@@ -54,22 +68,28 @@ async fn async_fn_vc_arg(n: Vc<u32>) -> Result<Vc<u32>> { ...@@ -54,22 +68,28 @@ async fn async_fn_vc_arg(n: Vc<u32>) -> Result<Vc<u32>> {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn methods() { async fn test_methods() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
assert_eq!(*Value::static_method().await?, 42); test_methods_operation().read_strongly_consistent().await?;
assert_eq!(*Value::async_static_method().await?, 42);
let value = Value(43).cell();
assert_eq!(*value.method().await?, 43);
assert_eq!(*value.async_method().await?, 43);
assert_eq!(*value.vc_method().await?, 42);
assert_eq!(*value.async_vc_method().await?, 43);
anyhow::Ok(()) anyhow::Ok(())
}) })
.await .await
.unwrap() .unwrap()
} }
#[turbo_tasks::function(operation)]
async fn test_methods_operation() -> Result<Vc<()>> {
assert_eq!(*Value::static_method().await?, 42);
assert_eq!(*Value::async_static_method().await?, 42);
let value = Value(43).cell();
assert_eq!(*value.method().await?, 43);
assert_eq!(*value.async_method().await?, 43);
assert_eq!(*value.vc_method().await?, 42);
assert_eq!(*value.async_vc_method().await?, 43);
Ok(Vc::cell(()))
}
#[turbo_tasks::value] #[turbo_tasks::value]
struct Value(u32); struct Value(u32);
...@@ -107,40 +127,48 @@ impl Value { ...@@ -107,40 +127,48 @@ impl Value {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn trait_methods() { async fn test_trait_methods() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
assert_eq!(*Value::static_trait_method().await?, 42); test_trait_methods_operation()
assert_eq!(*Value::async_static_trait_method().await?, 42); .read_strongly_consistent()
.await?;
let value = Value(43).cell();
assert_eq!(*value.trait_method().await?, 43);
assert_eq!(*value.async_trait_method().await?, 43);
assert_eq!(*value.default_trait_method().await?, 42);
assert_eq!(*value.default_async_trait_method().await?, 42);
let trait_value: Vc<Box<dyn ValueTrait>> = Vc::upcast(value);
assert_eq!(*trait_value.trait_method().await?, 43);
assert_eq!(*trait_value.async_trait_method().await?, 43);
assert_eq!(*trait_value.default_trait_method().await?, 42);
assert_eq!(*trait_value.default_async_trait_method().await?, 42);
let value = wrap_value(value);
assert_eq!(*value.trait_method().await?, 43);
assert_eq!(*value.async_trait_method().await?, 43);
assert_eq!(*value.default_trait_method().await?, 42);
assert_eq!(*value.default_async_trait_method().await?, 42);
let trait_value = wrap_trait_value(trait_value);
assert_eq!(*trait_value.trait_method().await?, 43);
assert_eq!(*trait_value.async_trait_method().await?, 43);
assert_eq!(*trait_value.default_trait_method().await?, 42);
assert_eq!(*trait_value.default_async_trait_method().await?, 42);
anyhow::Ok(()) anyhow::Ok(())
}) })
.await .await
.unwrap() .unwrap()
} }
#[turbo_tasks::function(operation)]
async fn test_trait_methods_operation() -> Result<Vc<()>> {
assert_eq!(*Value::static_trait_method().await?, 42);
assert_eq!(*Value::async_static_trait_method().await?, 42);
let value = Value(43).cell();
assert_eq!(*value.trait_method().await?, 43);
assert_eq!(*value.async_trait_method().await?, 43);
assert_eq!(*value.default_trait_method().await?, 42);
assert_eq!(*value.default_async_trait_method().await?, 42);
let trait_value: Vc<Box<dyn ValueTrait>> = Vc::upcast(value);
assert_eq!(*trait_value.trait_method().await?, 43);
assert_eq!(*trait_value.async_trait_method().await?, 43);
assert_eq!(*trait_value.default_trait_method().await?, 42);
assert_eq!(*trait_value.default_async_trait_method().await?, 42);
let value = wrap_value(value);
assert_eq!(*value.trait_method().await?, 43);
assert_eq!(*value.async_trait_method().await?, 43);
assert_eq!(*value.default_trait_method().await?, 42);
assert_eq!(*value.default_async_trait_method().await?, 42);
let trait_value = wrap_trait_value(trait_value);
assert_eq!(*trait_value.trait_method().await?, 43);
assert_eq!(*trait_value.async_trait_method().await?, 43);
assert_eq!(*trait_value.default_trait_method().await?, 42);
assert_eq!(*trait_value.default_async_trait_method().await?, 42);
Ok(Vc::cell(()))
}
#[turbo_tasks::function] #[turbo_tasks::function]
fn wrap_value(v: Vc<Value>) -> Vc<Value> { fn wrap_value(v: Vc<Value>) -> Vc<Value> {
v v
......
...@@ -9,14 +9,18 @@ use auto_hash_map::AutoSet; ...@@ -9,14 +9,18 @@ use auto_hash_map::AutoSet;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use tokio::time::sleep; use tokio::time::sleep;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{CollectiblesSource, ResolvedVc, ValueToString, Vc, emit}; use turbo_tasks::{
CollectiblesSource, ResolvedVc, ValueToString, Vc, emit,
unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn transitive_emitting() { async fn test_transitive_emitting() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!("")); let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!(""));
let result_val = result_op.connect().strongly_consistent().await?; let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.peek_collectibles::<Box<dyn ValueToString>>(); let list = result_op.peek_collectibles::<Box<dyn ValueToString>>();
...@@ -33,8 +37,9 @@ async fn transitive_emitting() { ...@@ -33,8 +37,9 @@ async fn transitive_emitting() {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn transitive_emitting_indirect() { async fn test_transitive_emitting_indirect() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!("")); let result_op = my_transitive_emitting_function(rcstr!(""), rcstr!(""));
let collectibles_op = my_transitive_emitting_function_collectibles(rcstr!(""), rcstr!("")); let collectibles_op = my_transitive_emitting_function_collectibles(rcstr!(""), rcstr!(""));
let list = collectibles_op.connect().strongly_consistent().await?; let list = collectibles_op.connect().strongly_consistent().await?;
...@@ -51,8 +56,9 @@ async fn transitive_emitting_indirect() { ...@@ -51,8 +56,9 @@ async fn transitive_emitting_indirect() {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn multi_emitting() { async fn test_multi_emitting() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let result_op = my_multi_emitting_function(); let result_op = my_multi_emitting_function();
let result_val = result_op.connect().strongly_consistent().await?; let result_val = result_op.connect().strongly_consistent().await?;
let list = result_op.peek_collectibles::<Box<dyn ValueToString>>(); let list = result_op.peek_collectibles::<Box<dyn ValueToString>>();
......
...@@ -4,152 +4,207 @@ ...@@ -4,152 +4,207 @@
use std::sync::Mutex; use std::sync::Mutex;
use turbo_tasks::{ResolvedVc, Vc, debug::ValueDebug}; use turbo_tasks::{
ResolvedVc, Vc,
debug::{ValueDebug, ValueDebugString},
};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[turbo_tasks::function(operation)]
fn dbg_operation(value: ResolvedVc<Box<dyn ValueDebug>>) -> Vc<ValueDebugString> {
value.dbg()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn primitive_debug() { async fn test_primitive_debug() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, move || async move {
let a: Vc<u32> = Vc::cell(42); let a = ResolvedVc::<u32>::cell(42);
assert_eq!(format!("{:?}", a.dbg().await?), "42"); assert_eq!(
anyhow::Ok(()) format!(
"{:?}",
dbg_operation(ResolvedVc::upcast(a))
.read_strongly_consistent()
.await?,
),
"42",
);
Ok(())
}) })
.await .await
.unwrap() .unwrap()
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn transparent_debug() { async fn test_transparent_debug() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, move || async move {
let a: Vc<Transparent> = Transparent(42).cell(); let a = Transparent(42).resolved_cell();
assert_eq!(format!("{:?}", a.dbg().await?), "42"); assert_eq!(
format!(
anyhow::Ok(()) "{:?}",
dbg_operation(ResolvedVc::upcast(a))
.read_strongly_consistent()
.await?,
),
"42",
);
Ok(())
}) })
.await .await
.unwrap() .unwrap()
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn enum_none_debug() { async fn test_enum_none_debug() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, move || async move {
let a: Vc<Enum> = Enum::None.cell(); let a = Enum::None.resolved_cell();
assert_eq!(format!("{:?}", a.dbg().await?), "Enum :: None"); assert_eq!(
format!(
anyhow::Ok(()) "{:?}",
dbg_operation(ResolvedVc::upcast(a))
.read_strongly_consistent()
.await?,
),
"Enum :: None",
);
Ok(())
}) })
.await .await
.unwrap() .unwrap()
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn enum_transparent_debug() { async fn test_enum_transparent_debug() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, move || async move {
let a: Vc<Enum> = Enum::Transparent(Transparent(42).resolved_cell()).cell(); let a = Enum::Transparent(Transparent(42).resolved_cell()).resolved_cell();
assert_eq!( assert_eq!(
format!("{:?}", a.dbg().await?), format!(
r#"Enum :: Transparent( "{:?}",
42, dbg_operation(ResolvedVc::upcast(a))
)"# .read_strongly_consistent()
.await?,
),
"Enum :: Transparent(\n 42,\n)",
); );
anyhow::Ok(()) Ok(())
}) })
.await .await
.unwrap() .unwrap()
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn enum_inner_vc_debug() { async fn test_enum_inner_vc_debug() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, move || async move {
let a: Vc<Enum> = Enum::Enum(Enum::None.resolved_cell()).cell(); let a = Enum::Enum(Enum::None.resolved_cell()).resolved_cell();
assert_eq!( assert_eq!(
format!("{:?}", a.dbg().await?), format!(
r#"Enum :: Enum( "{:?}",
Enum :: None, dbg_operation(ResolvedVc::upcast(a))
)"# .read_strongly_consistent()
.await?,
),
"Enum :: Enum(\n Enum :: None,\n)",
); );
anyhow::Ok(()) Ok(())
}) })
.await .await
.unwrap() .unwrap()
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn struct_unit_debug() { async fn test_struct_unit_debug() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, move || async move {
let a: Vc<StructUnit> = StructUnit.cell(); let a = StructUnit.resolved_cell();
assert_eq!(format!("{:?}", a.dbg().await?), "StructUnit"); assert_eq!(
anyhow::Ok(()) format!(
"{:?}",
dbg_operation(ResolvedVc::upcast(a))
.read_strongly_consistent()
.await?,
),
"StructUnit",
);
Ok(())
}) })
.await .await
.unwrap() .unwrap()
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn struct_transparent_debug() { async fn test_struct_transparent_debug() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, move || async move {
let a: Vc<StructWithTransparent> = StructWithTransparent { let a = StructWithTransparent {
transparent: Transparent(42).resolved_cell(), transparent: Transparent(42).resolved_cell(),
} }
.cell(); .resolved_cell();
assert_eq!( assert_eq!(
format!("{:?}", a.dbg().await?), format!(
r#"StructWithTransparent { "{:?}",
transparent: 42, dbg_operation(ResolvedVc::upcast(a))
}"# .read_strongly_consistent()
.await?,
),
"StructWithTransparent {\n transparent: 42,\n}",
); );
anyhow::Ok(()) Ok(())
}) })
.await .await
.unwrap() .unwrap()
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn struct_vec_debug() { async fn test_struct_vec_debug() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
let a: Vc<StructWithVec> = StructWithVec { vec: vec![] }.cell(); let a = StructWithVec { vec: Vec::new() }.resolved_cell();
assert_eq!( assert_eq!(
format!("{:?}", a.dbg().await?), format!(
r#"StructWithVec { "{:?}",
vec: [], dbg_operation(ResolvedVc::upcast(a))
}"# .read_strongly_consistent()
.await?,
),
"StructWithVec {\n vec: [],\n}"
); );
let b: Vc<StructWithVec> = StructWithVec { let b = StructWithVec {
vec: vec![Transparent(42).resolved_cell()], vec: vec![Transparent(42).resolved_cell()],
} }
.cell(); .resolved_cell();
assert_eq!( assert_eq!(
format!("{:?}", b.dbg().await?), format!(
r#"StructWithVec { "{:?}",
vec: [ dbg_operation(ResolvedVc::upcast(b))
42, .read_strongly_consistent()
], .await?,
}"# ),
"StructWithVec {\n vec: [\n 42,\n ],\n}",
); );
anyhow::Ok(())
Ok(())
}) })
.await .await
.unwrap() .unwrap()
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn struct_ignore_debug() { async fn test_struct_ignore_debug() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
let a: Vc<StructWithIgnore> = StructWithIgnore { let a = StructWithIgnore {
dont_ignore: 42, dont_ignore: 42,
ignore: Mutex::new(()), ignore: Mutex::new(()),
} }
.cell(); .resolved_cell();
assert_eq!( assert_eq!(
format!("{:?}", a.dbg().await?), format!(
r#"StructWithIgnore { "{:?}",
dont_ignore: 42, dbg_operation(ResolvedVc::upcast(a))
}"# .read_strongly_consistent()
.await?,
),
"StructWithIgnore {\n dont_ignore: 42,\n}",
); );
anyhow::Ok(()) Ok(())
}) })
.await .await
.unwrap() .unwrap()
......
...@@ -10,6 +10,11 @@ use turbo_tasks_testing::{Registration, register, run_once}; ...@@ -10,6 +10,11 @@ use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[turbo_tasks::function(operation)]
fn to_string_operation(value: ResolvedVc<Box<dyn ValueToString>>) -> Vc<RcStr> {
value.to_string()
}
// --- Test types --- // --- Test types ---
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
...@@ -99,8 +104,12 @@ enum MixedEnum { ...@@ -99,8 +104,12 @@ enum MixedEnum {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_display_delegation() { async fn test_display_delegation() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
let v: Vc<SimpleDisplay> = SimpleDisplay(42).cell(); let v: ResolvedVc<Box<dyn ValueToString>> =
assert_eq!(&*v.to_string().await?, "simple:42"); ResolvedVc::upcast(SimpleDisplay(42).resolved_cell());
assert_eq!(
&*to_string_operation(v).read_strongly_consistent().await?,
"simple:42"
);
anyhow::Ok(()) anyhow::Ok(())
}) })
.await .await
...@@ -111,18 +120,31 @@ async fn test_display_delegation() { ...@@ -111,18 +120,31 @@ async fn test_display_delegation() {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_struct_format_strings() { async fn test_struct_format_strings() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
let v1: Vc<NamedFields> = NamedFields { let v1: ResolvedVc<Box<dyn ValueToString>> = ResolvedVc::upcast(
name: "foo".into(), NamedFields {
count: 7, name: "foo".into(),
} count: 7,
.cell(); }
assert_eq!(&*v1.to_string().await?, "item foo (count: 7)"); .resolved_cell(),
);
assert_eq!(
&*to_string_operation(v1).read_strongly_consistent().await?,
"item foo (count: 7)"
);
let v2: Vc<TupleStruct> = TupleStruct(99).cell(); let v2: ResolvedVc<Box<dyn ValueToString>> =
assert_eq!(&*v2.to_string().await?, "wrapped(99)"); ResolvedVc::upcast(TupleStruct(99).resolved_cell());
assert_eq!(
&*to_string_operation(v2).read_strongly_consistent().await?,
"wrapped(99)"
);
let v3: Vc<ConstantString> = ConstantString.cell(); let v3: ResolvedVc<Box<dyn ValueToString>> =
assert_eq!(&*v3.to_string().await?, "constant-value"); ResolvedVc::upcast(ConstantString.resolved_cell());
assert_eq!(
&*to_string_operation(v3).read_strongly_consistent().await?,
"constant-value"
);
anyhow::Ok(()) anyhow::Ok(())
}) })
...@@ -134,12 +156,17 @@ async fn test_struct_format_strings() { ...@@ -134,12 +156,17 @@ async fn test_struct_format_strings() {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_struct_direct_expr() { async fn test_struct_direct_expr() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
let v: Vc<DirectExpr> = DirectExpr { let v: ResolvedVc<Box<dyn ValueToString>> = ResolvedVc::upcast(
name: "hello".into(), DirectExpr {
other: 42, name: "hello".into(),
} other: 42,
.cell(); }
assert_eq!(&*v.to_string().await?, "hello"); .resolved_cell(),
);
assert_eq!(
&*to_string_operation(v).read_strongly_consistent().await?,
"hello"
);
anyhow::Ok(()) anyhow::Ok(())
}) })
.await .await
...@@ -150,20 +177,29 @@ async fn test_struct_direct_expr() { ...@@ -150,20 +177,29 @@ async fn test_struct_direct_expr() {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_struct_format_exprs() { async fn test_struct_format_exprs() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
let v1: Vc<FormatExprs> = FormatExprs { let v1: ResolvedVc<Box<dyn ValueToString>> = ResolvedVc::upcast(
name: "test".into(), FormatExprs {
count: 5, name: "test".into(),
} count: 5,
.cell(); }
assert_eq!(&*v1.to_string().await?, "prefix(test) suffix(5)"); .resolved_cell(),
);
assert_eq!(
&*to_string_operation(v1).read_strongly_consistent().await?,
"prefix(test) suffix(5)"
);
let inner = NamedFields { let inner = NamedFields {
name: "bar".into(), name: "bar".into(),
count: 3, count: 3,
} }
.resolved_cell(); .resolved_cell();
let v2: Vc<VcExprDelegate> = VcExprDelegate { inner }.cell(); let v2: ResolvedVc<Box<dyn ValueToString>> =
assert_eq!(&*v2.to_string().await?, "inner: item bar (count: 3)"); ResolvedVc::upcast(VcExprDelegate { inner }.resolved_cell());
assert_eq!(
&*to_string_operation(v2).read_strongly_consistent().await?,
"inner: item bar (count: 3)"
);
anyhow::Ok(()) anyhow::Ok(())
}) })
...@@ -176,24 +212,45 @@ async fn test_struct_format_exprs() { ...@@ -176,24 +212,45 @@ async fn test_struct_format_exprs() {
async fn test_enum_variants() { async fn test_enum_variants() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
// Per-variant attributes // Per-variant attributes
assert_eq!(&*Kind::Module.cell().to_string().await?, "module");
assert_eq!( assert_eq!(
&*Kind::Asset("main.js".into()).cell().to_string().await?, &*to_string_operation(ResolvedVc::upcast(Kind::Module.resolved_cell()))
.read_strongly_consistent()
.await?,
"module"
);
assert_eq!(
&*to_string_operation(ResolvedVc::upcast(
Kind::Asset("main.js".into()).resolved_cell()
))
.read_strongly_consistent()
.await?,
"asset(main.js)" "asset(main.js)"
); );
assert_eq!( assert_eq!(
&*(Kind::Entry { &*to_string_operation(ResolvedVc::upcast(
name: "index".into() Kind::Entry {
}) name: "index".into(),
.cell() }
.to_string() .resolved_cell(),
))
.read_strongly_consistent()
.await?, .await?,
"entry index" "entry index"
); );
// Default variant names (no attribute) // Default variant names (no attribute)
assert_eq!(&*DefaultNames::Alpha.cell().to_string().await?, "Alpha"); assert_eq!(
assert_eq!(&*DefaultNames::Beta.cell().to_string().await?, "Beta"); &*to_string_operation(ResolvedVc::upcast(DefaultNames::Alpha.resolved_cell()))
.read_strongly_consistent()
.await?,
"Alpha"
);
assert_eq!(
&*to_string_operation(ResolvedVc::upcast(DefaultNames::Beta.resolved_cell()))
.read_strongly_consistent()
.await?,
"Beta"
);
anyhow::Ok(()) anyhow::Ok(())
}) })
...@@ -205,17 +262,31 @@ async fn test_enum_variants() { ...@@ -205,17 +262,31 @@ async fn test_enum_variants() {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_mixed_enum() { async fn test_mixed_enum() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
assert_eq!(&*MixedEnum::Literal.cell().to_string().await?, "literal"); assert_eq!(
&*to_string_operation(ResolvedVc::upcast(MixedEnum::Literal.resolved_cell()))
.read_strongly_consistent()
.await?,
"literal"
);
let inner = ConstantString.resolved_cell(); let inner = ConstantString.resolved_cell();
let v2: Vc<MixedEnum> = MixedEnum::Delegate(inner).cell(); let v2: ResolvedVc<Box<dyn ValueToString>> =
assert_eq!(&*v2.to_string().await?, "constant-value"); ResolvedVc::upcast(MixedEnum::Delegate(inner).resolved_cell());
assert_eq!(
let v3: Vc<MixedEnum> = (MixedEnum::ExprNamed { &*to_string_operation(v2).read_strongly_consistent().await?,
name: "world".into(), "constant-value"
}) );
.cell();
assert_eq!(&*v3.to_string().await?, "wrapped(world)"); let v3: ResolvedVc<Box<dyn ValueToString>> = ResolvedVc::upcast(
(MixedEnum::ExprNamed {
name: "world".into(),
})
.resolved_cell(),
);
assert_eq!(
&*to_string_operation(v3).read_strongly_consistent().await?,
"wrapped(world)"
);
anyhow::Ok(()) anyhow::Ok(())
}) })
......
...@@ -9,7 +9,7 @@ use tokio::{ ...@@ -9,7 +9,7 @@ use tokio::{
use turbo_tasks::{ use turbo_tasks::{
State, TransientInstance, Vc, prevent_gc, State, TransientInstance, Vc, prevent_gc,
trace::{TraceRawVcs, TraceRawVcsContext}, trace::{TraceRawVcs, TraceRawVcsContext},
turbo_tasks, turbo_tasks, unmark_top_level_task_may_leak_eventually_consistent_state,
}; };
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
...@@ -87,6 +87,7 @@ async fn spawns_detached( ...@@ -87,6 +87,7 @@ async fn spawns_detached(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_spawns_detached_changing() -> anyhow::Result<()> { async fn test_spawns_detached_changing() -> anyhow::Result<()> {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
// HACK: The watch channel we use has an incorrect implementation of `TraceRawVcs` // HACK: The watch channel we use has an incorrect implementation of `TraceRawVcs`
prevent_gc(); prevent_gc();
// timeout: prevent the test from hanging, and fail instead if this is broken // timeout: prevent the test from hanging, and fail instead if this is broken
......
...@@ -6,13 +6,13 @@ use std::time::Duration; ...@@ -6,13 +6,13 @@ use std::time::Duration;
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{CollectiblesSource, ResolvedVc, State, ValueToString, Vc, emit}; use turbo_tasks::{CollectiblesSource, ReadRef, ResolvedVc, State, ValueToString, Vc, emit};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn dirty_in_progress() { async fn test_dirty_in_progress() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
let cases = [ let cases = [
(1, 3, 2, 2, ""), (1, 3, 2, 2, ""),
...@@ -24,24 +24,23 @@ async fn dirty_in_progress() { ...@@ -24,24 +24,23 @@ async fn dirty_in_progress() {
]; ];
for (a, b, c, value, collectible) in cases { for (a, b, c, value, collectible) in cases {
println!("{a} -> {b} -> {c} = {value} {collectible}"); println!("{a} -> {b} -> {c} = {value} {collectible}");
let input = ChangingInput { let input_val = ReadRef::new_owned(ChangingInput {
state: State::new(a), state: State::new(a),
} });
.cell(); let input_vc = ReadRef::resolved_cell(input_val.clone());
let input_val = input.await?; let output_op = compute_operation(input_vc);
let output = compute(input); output_op.read_strongly_consistent().await?;
output.await?;
println!("update to {b}"); println!("update to {b}");
input_val.state.set(b); input_val.state.set(b);
tokio::time::sleep(Duration::from_millis(50)).await; tokio::time::sleep(Duration::from_millis(50)).await;
println!("update to {c}"); println!("update to {c}");
input_val.state.set(c); input_val.state.set(c);
let read = output.strongly_consistent().await?; let read = output_op.read_strongly_consistent().await?;
assert_eq!(read.value, value); assert_eq!(read.value, value);
assert_eq!(read.collectible, collectible); assert_eq!(read.collectible, collectible);
println!("\n"); println!("\n");
} }
anyhow::Ok(()) Ok(())
}) })
.await .await
.unwrap() .unwrap()
...@@ -89,8 +88,8 @@ async fn inner_compute(input: ResolvedVc<ChangingInput>) -> Result<Vc<u32>> { ...@@ -89,8 +88,8 @@ async fn inner_compute(input: ResolvedVc<ChangingInput>) -> Result<Vc<u32>> {
} }
} }
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
async fn compute(input: ResolvedVc<ChangingInput>) -> Result<Vc<Output>> { async fn compute_operation(input: ResolvedVc<ChangingInput>) -> Result<Vc<Output>> {
println!("start compute"); println!("start compute");
let operation = inner_compute(input); let operation = inner_compute(input);
let value = *operation.connect().await?; let value = *operation.connect().await?;
......
...@@ -3,38 +3,41 @@ ...@@ -3,38 +3,41 @@
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{State, Vc}; use turbo_tasks::{ResolvedVc, State, Vc};
use turbo_tasks_testing::{Registration, register, run}; use turbo_tasks_testing::{Registration, register, run};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn recompute() { async fn test_emptied_cells() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
let input = get_state().resolve().await?; let input_op = get_state_operation();
input.await?.state.set(0); let input_vc = input_op.resolve_strongly_consistent().await?;
let output = compute(input); let input = input_op.read_strongly_consistent().await?;
assert_eq!(*output.strongly_consistent().await?, 0); input.state.set(0);
let output = compute_operation(input_vc);
assert_eq!(*output.read_strongly_consistent().await?, 0);
println!("changing input"); println!("changing input");
input.await?.state.set(10); input.state.set(10);
assert_eq!(*output.strongly_consistent().await?, 10); assert_eq!(*output.read_strongly_consistent().await?, 10);
println!("changing input"); println!("changing input");
input.await?.state.set(5); input.state.set(5);
assert_eq!(*output.strongly_consistent().await?, 5); assert_eq!(*output.read_strongly_consistent().await?, 5);
println!("changing input"); println!("changing input");
input.await?.state.set(20); input.state.set(20);
assert_eq!(*output.strongly_consistent().await?, 20); assert_eq!(*output.read_strongly_consistent().await?, 20);
println!("changing input"); println!("changing input");
input.await?.state.set(15); input.state.set(15);
assert_eq!(*output.strongly_consistent().await?, 15); assert_eq!(*output.read_strongly_consistent().await?, 15);
println!("changing input"); println!("changing input");
input.await?.state.set(1); input.state.set(1);
assert_eq!(*output.strongly_consistent().await?, 1); assert_eq!(*output.read_strongly_consistent().await?, 1);
anyhow::Ok(()) anyhow::Ok(())
}) })
...@@ -42,8 +45,8 @@ async fn recompute() { ...@@ -42,8 +45,8 @@ async fn recompute() {
.unwrap(); .unwrap();
} }
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
fn get_state() -> Vc<ChangingInput> { fn get_state_operation() -> Vc<ChangingInput> {
ChangingInput { ChangingInput {
state: State::new(0), state: State::new(0),
} }
...@@ -55,10 +58,10 @@ struct ChangingInput { ...@@ -55,10 +58,10 @@ struct ChangingInput {
state: State<u32>, state: State<u32>,
} }
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
async fn compute(input: Vc<ChangingInput>) -> Result<Vc<u32>> { async fn compute_operation(input: ResolvedVc<ChangingInput>) -> Result<Vc<u32>> {
println!("compute()"); println!("compute_operation()");
let value = *inner_compute(input).await?; let value = *inner_compute(*input).await?;
Ok(Vc::cell(value)) Ok(Vc::cell(value))
} }
......
...@@ -3,38 +3,41 @@ ...@@ -3,38 +3,41 @@
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{State, Vc, mark_session_dependent}; use turbo_tasks::{ResolvedVc, State, Vc, mark_session_dependent};
use turbo_tasks_testing::{Registration, register, run}; use turbo_tasks_testing::{Registration, register, run};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn recompute() { async fn test_emptied_cells_session_dependent() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
let input = get_state().resolve().await?; let input_op = get_state_operation();
input.await?.state.set(0); let input_vc = input_op.resolve_strongly_consistent().await?;
let output = compute(input); let input = input_op.read_strongly_consistent().await?;
assert_eq!(*output.strongly_consistent().await?, 0); input.state.set(0);
let output = compute_operation(input_vc);
assert_eq!(*output.read_strongly_consistent().await?, 0);
println!("changing input"); println!("changing input");
input.await?.state.set(10); input.state.set(10);
assert_eq!(*output.strongly_consistent().await?, 10); assert_eq!(*output.read_strongly_consistent().await?, 10);
println!("changing input"); println!("changing input");
input.await?.state.set(5); input.state.set(5);
assert_eq!(*output.strongly_consistent().await?, 5); assert_eq!(*output.read_strongly_consistent().await?, 5);
println!("changing input"); println!("changing input");
input.await?.state.set(20); input.state.set(20);
assert_eq!(*output.strongly_consistent().await?, 20); assert_eq!(*output.read_strongly_consistent().await?, 20);
println!("changing input"); println!("changing input");
input.await?.state.set(15); input.state.set(15);
assert_eq!(*output.strongly_consistent().await?, 15); assert_eq!(*output.read_strongly_consistent().await?, 15);
println!("changing input"); println!("changing input");
input.await?.state.set(1); input.state.set(1);
assert_eq!(*output.strongly_consistent().await?, 1); assert_eq!(*output.read_strongly_consistent().await?, 1);
anyhow::Ok(()) anyhow::Ok(())
}) })
...@@ -42,8 +45,8 @@ async fn recompute() { ...@@ -42,8 +45,8 @@ async fn recompute() {
.unwrap(); .unwrap();
} }
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
fn get_state() -> Vc<ChangingInput> { fn get_state_operation() -> Vc<ChangingInput> {
ChangingInput { ChangingInput {
state: State::new(0), state: State::new(0),
} }
...@@ -55,10 +58,10 @@ struct ChangingInput { ...@@ -55,10 +58,10 @@ struct ChangingInput {
state: State<u32>, state: State<u32>,
} }
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
async fn compute(input: Vc<ChangingInput>) -> Result<Vc<u32>> { async fn compute_operation(input: ResolvedVc<ChangingInput>) -> Result<Vc<u32>> {
println!("compute()"); println!("compute_operation()");
let value = *inner_compute(input).await?; let value = *inner_compute(*input).await?;
Ok(Vc::cell(value)) Ok(Vc::cell(value))
} }
......
...@@ -8,7 +8,9 @@ use std::{ ...@@ -8,7 +8,9 @@ use std::{
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use indoc::indoc; use indoc::indoc;
use turbo_tasks::{PrettyPrintError, Vc}; use turbo_tasks::{
PrettyPrintError, Vc, unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_testing::{Registration, register, run}; use turbo_tasks_testing::{Registration, register, run};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
...@@ -21,6 +23,7 @@ async fn assert_error<T: Debug>( ...@@ -21,6 +23,7 @@ async fn assert_error<T: Debug>(
future: impl IntoFuture<Output = Result<T>>, future: impl IntoFuture<Output = Result<T>>,
expected: &'static str, expected: &'static str,
) -> Result<()> { ) -> Result<()> {
unmark_top_level_task_may_leak_eventually_consistent_state();
let error = future.into_future().await.unwrap_err(); let error = future.into_future().await.unwrap_err();
assert_eq!( assert_eq!(
&PrettyPrintError(&error).to_string(), &PrettyPrintError(&error).to_string(),
......
...@@ -3,14 +3,16 @@ ...@@ -3,14 +3,16 @@
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use anyhow::Result; use anyhow::Result;
use turbo_tasks::Vc; use turbo_tasks::{Vc, unmark_top_level_task_may_leak_eventually_consistent_state};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn filtered_impl_method_args() -> Result<()> { async fn test_filtered_impl_method_args() -> Result<()> {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let uses_arg = UsesArg(0).cell(); let uses_arg = UsesArg(0).cell();
assert_eq!( assert_eq!(
uses_arg.method_with_arg(0).to_resolved().await?, uses_arg.method_with_arg(0).to_resolved().await?,
...@@ -37,8 +39,10 @@ async fn filtered_impl_method_args() -> Result<()> { ...@@ -37,8 +39,10 @@ async fn filtered_impl_method_args() -> Result<()> {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn filtered_trait_method_args() -> Result<()> { async fn test_filtered_trait_method_args() -> Result<()> {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let uses_arg = UsesArg(0).cell(); let uses_arg = UsesArg(0).cell();
assert_eq!( assert_eq!(
uses_arg.trait_method_with_arg(0).to_resolved().await?, uses_arg.trait_method_with_arg(0).to_resolved().await?,
...@@ -65,8 +69,10 @@ async fn filtered_trait_method_args() -> Result<()> { ...@@ -65,8 +69,10 @@ async fn filtered_trait_method_args() -> Result<()> {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn filtered_impl_method_self() -> Result<()> { async fn test_filtered_impl_method_self() -> Result<()> {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let uses_arg = UsesArg(0).cell(); let uses_arg = UsesArg(0).cell();
let uses_arg2 = UsesArg(1).cell(); let uses_arg2 = UsesArg(1).cell();
assert_eq!( assert_eq!(
...@@ -99,8 +105,10 @@ async fn filtered_impl_method_self() -> Result<()> { ...@@ -99,8 +105,10 @@ async fn filtered_impl_method_self() -> Result<()> {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn filtered_trait_method_self() -> Result<()> { async fn test_filtered_trait_method_self() -> Result<()> {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let uses_arg = UsesArg(0).cell(); let uses_arg = UsesArg(0).cell();
let uses_arg2 = UsesArg(1).cell(); let uses_arg2 = UsesArg(1).cell();
assert_eq!( assert_eq!(
...@@ -133,8 +141,10 @@ async fn filtered_trait_method_self() -> Result<()> { ...@@ -133,8 +141,10 @@ async fn filtered_trait_method_self() -> Result<()> {
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn filtered_plain_method_args() -> Result<()> { async fn test_filtered_plain_method_args() -> Result<()> {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
assert_eq!( assert_eq!(
method_with_arg(0).to_resolved().await?, method_with_arg(0).to_resolved().await?,
method_with_arg(0).to_resolved().await?, method_with_arg(0).to_resolved().await?,
......
...@@ -3,14 +3,15 @@ ...@@ -3,14 +3,15 @@
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{State, Vc}; use turbo_tasks::{State, Vc, unmark_top_level_task_may_leak_eventually_consistent_state};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn hidden_mutate() { async fn test_hidden_mutate() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let input = create_input().resolve().await?; let input = create_input().resolve().await?;
input.await?.state.set(1); input.await?.state.set(1);
let changing_value = compute(input); let changing_value = compute(input);
......
...@@ -12,18 +12,20 @@ static REGISTRATION: Registration = register!(); ...@@ -12,18 +12,20 @@ static REGISTRATION: Registration = register!();
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
struct Step(State<u32>); struct Step(State<u32>);
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
fn create_state() -> Vc<Step> { fn create_state_operation() -> Vc<Step> {
Step(State::new(0)).cell() Step(State::new(0)).cell()
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn invalidation_map() { async fn test_invalidation_map() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
let state = create_state().to_resolved().await?; let state_op = create_state_operation();
state.await?.set(1); let state_vc = state_op.resolve_strongly_consistent().await?;
let state = state_op.read_strongly_consistent().await?;
state.set(1);
let map = create_map(state); let map = create_map(state_vc);
let a = get_value(map, "a".to_string()); let a = get_value(map, "a".to_string());
let b = get_value(map, "b".to_string()); let b = get_value(map, "b".to_string());
let c = get_value(map, "c".to_string()); let c = get_value(map, "c".to_string());
...@@ -36,7 +38,7 @@ async fn invalidation_map() { ...@@ -36,7 +38,7 @@ async fn invalidation_map() {
assert_eq!(b_ref.value, Some(2)); assert_eq!(b_ref.value, Some(2));
assert_eq!(c_ref.value, None); assert_eq!(c_ref.value, None);
state.await?.set(2); state.set(2);
let a_ref2 = a.read_strongly_consistent().await?; let a_ref2 = a.read_strongly_consistent().await?;
let b_ref2 = b.read_strongly_consistent().await?; let b_ref2 = b.read_strongly_consistent().await?;
...@@ -48,7 +50,7 @@ async fn invalidation_map() { ...@@ -48,7 +50,7 @@ async fn invalidation_map() {
assert_eq!(a_ref.random, a_ref2.random); assert_eq!(a_ref.random, a_ref2.random);
assert_eq!(c_ref.random, c_ref2.random); assert_eq!(c_ref.random, c_ref2.random);
state.await?.set(3); state.set(3);
let a_ref3 = a.read_strongly_consistent().await?; let a_ref3 = a.read_strongly_consistent().await?;
let b_ref3 = b.read_strongly_consistent().await?; let b_ref3 = b.read_strongly_consistent().await?;
...@@ -96,12 +98,14 @@ async fn get_value(map: OperationVc<Map>, key: String) -> Result<Vc<GetValueResu ...@@ -96,12 +98,14 @@ async fn get_value(map: OperationVc<Map>, key: String) -> Result<Vc<GetValueResu
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn invalidation_set() { async fn test_invalidation_set() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
let state = create_state().to_resolved().await?; let state_op = create_state_operation();
state.await?.set(1); let state_vc = state_op.resolve_strongly_consistent().await?;
let state = state_op.read_strongly_consistent().await?;
state.set(1);
let set = create_set(state); let set = create_set(state_vc);
let a = has_value(set, "a".to_string()); let a = has_value(set, "a".to_string());
let b = has_value(set, "b".to_string()); let b = has_value(set, "b".to_string());
let c = has_value(set, "c".to_string()); let c = has_value(set, "c".to_string());
...@@ -114,7 +118,7 @@ async fn invalidation_set() { ...@@ -114,7 +118,7 @@ async fn invalidation_set() {
assert!(b_ref.value); assert!(b_ref.value);
assert!(!c_ref.value); assert!(!c_ref.value);
state.await?.set(2); state.set(2);
let a_ref2 = a.read_strongly_consistent().await?; let a_ref2 = a.read_strongly_consistent().await?;
let b_ref2 = b.read_strongly_consistent().await?; let b_ref2 = b.read_strongly_consistent().await?;
...@@ -127,7 +131,7 @@ async fn invalidation_set() { ...@@ -127,7 +131,7 @@ async fn invalidation_set() {
assert_eq!(b_ref.random, b_ref2.random); assert_eq!(b_ref.random, b_ref2.random);
assert_eq!(c_ref.random, c_ref2.random); assert_eq!(c_ref.random, c_ref2.random);
state.await?.set(3); state.set(3);
let a_ref3 = a.read_strongly_consistent().await?; let a_ref3 = a.read_strongly_consistent().await?;
let b_ref3 = b.read_strongly_consistent().await?; let b_ref3 = b.read_strongly_consistent().await?;
......
...@@ -19,7 +19,7 @@ async fn multiply(value: OperationVc<i32>, coefficient: ResolvedVc<i32>) -> Resu ...@@ -19,7 +19,7 @@ async fn multiply(value: OperationVc<i32>, coefficient: ResolvedVc<i32>) -> Resu
Ok(Vc::cell((*value.connect().await?) * (*coefficient.await?))) Ok(Vc::cell((*value.connect().await?) * (*coefficient.await?)))
} }
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
fn use_operations() -> Vc<i32> { fn use_operations() -> Vc<i32> {
let twenty_one: OperationVc<i32> = bare_op_fn(); let twenty_one: OperationVc<i32> = bare_op_fn();
let forty_two: OperationVc<i32> = multiply(twenty_one, ResolvedVc::cell(2)); let forty_two: OperationVc<i32> = multiply(twenty_one, ResolvedVc::cell(2));
...@@ -29,7 +29,7 @@ fn use_operations() -> Vc<i32> { ...@@ -29,7 +29,7 @@ fn use_operations() -> Vc<i32> {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_use_operations() -> Result<()> { async fn test_use_operations() -> Result<()> {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
assert_eq!(*use_operations().await?, 42); assert_eq!(*use_operations().read_strongly_consistent().await?, 42);
Ok(()) Ok(())
}) })
.await .await
......
...@@ -13,6 +13,7 @@ use turbo_tasks::{ ...@@ -13,6 +13,7 @@ use turbo_tasks::{
Vc, Vc,
backend::TurboTasksExecutionError, backend::TurboTasksExecutionError,
panic_hooks::{handle_panic, register_panic_hook}, panic_hooks::{handle_panic, register_panic_hook},
unmark_top_level_task_may_leak_eventually_consistent_state,
}; };
use turbo_tasks_testing::{Registration, register, run_once_without_cache_check}; use turbo_tasks_testing::{Registration, register, run_once_without_cache_check};
...@@ -39,9 +40,11 @@ async fn test_panic_hook() { ...@@ -39,9 +40,11 @@ async fn test_panic_hook() {
Box::new(move |_| hook_was_called.store(true, Ordering::SeqCst)) Box::new(move |_| hook_was_called.store(true, Ordering::SeqCst))
}); });
let result = let result = run_once_without_cache_check(&REGISTRATION, async move {
run_once_without_cache_check(&REGISTRATION, async move { anyhow::Ok(*double(3).await?) }) unmark_top_level_task_may_leak_eventually_consistent_state();
.await; anyhow::Ok(*double(3).await?)
})
.await;
assert!(hook_was_called.load(Ordering::SeqCst)); assert!(hook_was_called.load(Ordering::SeqCst));
......
...@@ -10,16 +10,18 @@ use turbo_tasks_testing::{Registration, register, run_once}; ...@@ -10,16 +10,18 @@ use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn random_change() { async fn test_random_change() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
let state = make_state_operation().resolve_strongly_consistent().await?; let state_op = make_state_operation();
let state_vc = state_op.resolve_strongly_consistent().await?;
let state = state_op.read_strongly_consistent().await?;
let mut rng = StdRng::from_seed(Default::default()); let mut rng = StdRng::from_seed(Default::default());
let func_op = func_operation(state); let func_op = func_operation(state_vc);
let func2_op = func2_operation(state); let func2_op = func2_operation(state_vc);
for _i in 0..10 { for _i in 0..10 {
let value = rng.random_range(0..100); let value = rng.random_range(0..100);
state.await?.state.set(value); state.state.set(value);
let result = func_op.read_strongly_consistent().await?; let result = func_op.read_strongly_consistent().await?;
assert_eq!(result.value, value); assert_eq!(result.value, value);
......
...@@ -5,14 +5,18 @@ ...@@ -5,14 +5,18 @@
use std::{collections::HashSet, mem::take, sync::Mutex}; use std::{collections::HashSet, mem::take, sync::Mutex};
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{Invalidator, ReadRef, Vc, get_invalidator, with_turbo_tasks}; use turbo_tasks::{
Invalidator, ReadRef, Vc, get_invalidator,
unmark_top_level_task_may_leak_eventually_consistent_state, with_turbo_tasks,
};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn read_ref() { async fn test_read_ref() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let counter = Counter::cell(Counter { let counter = Counter::cell(Counter {
value: Mutex::new((0, Default::default())), value: Mutex::new((0, Default::default())),
}); });
......
...@@ -3,7 +3,9 @@ ...@@ -3,7 +3,9 @@
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{ResolvedVc, State, Vc}; use turbo_tasks::{
ResolvedVc, State, Vc, unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_testing::{Registration, register, run, run_once}; use turbo_tasks_testing::{Registration, register, run, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
...@@ -11,6 +13,7 @@ static REGISTRATION: Registration = register!(); ...@@ -11,6 +13,7 @@ static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn recompute() { async fn recompute() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let input = ChangingInput { let input = ChangingInput {
state: State::new(1), state: State::new(1),
} }
...@@ -61,6 +64,7 @@ async fn recompute() { ...@@ -61,6 +64,7 @@ async fn recompute() {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn immutable_analysis() { async fn immutable_analysis() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let input = ChangingInput { let input = ChangingInput {
state: State::new(1), state: State::new(1),
} }
...@@ -146,6 +150,7 @@ async fn compute2(input: Vc<ChangingInput>) -> Result<Vc<u32>> { ...@@ -146,6 +150,7 @@ async fn compute2(input: Vc<ChangingInput>) -> Result<Vc<u32>> {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn recompute_dependency() { async fn recompute_dependency() {
run(&REGISTRATION, || async { run(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let input = get_dependency_input().resolve().await?; let input = get_dependency_input().resolve().await?;
// Reset state to 1 at the start of each iteration (important for multi-run tests) // Reset state to 1 at the start of each iteration (important for multi-run tests)
input.await?.state.set(1); input.await?.state.set(1);
......
...@@ -4,7 +4,10 @@ ...@@ -4,7 +4,10 @@
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::{CollectiblesSource, ResolvedVc, State, ValueToString, Vc, emit}; use turbo_tasks::{
CollectiblesSource, ResolvedVc, State, ValueToString, Vc, emit,
unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
...@@ -12,6 +15,7 @@ static REGISTRATION: Registration = register!(); ...@@ -12,6 +15,7 @@ static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn recompute() { async fn recompute() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let input = ChangingInput::new(1).resolve().await?; let input = ChangingInput::new(1).resolve().await?;
let input2 = ChangingInput::new(2).resolve().await?; let input2 = ChangingInput::new(2).resolve().await?;
input.await?.state.set(1); input.await?.state.set(1);
......
...@@ -25,55 +25,93 @@ fn assert_resolved(input: ResolvedVc<u32>) { ...@@ -25,55 +25,93 @@ fn assert_resolved(input: ResolvedVc<u32>) {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_conversion() -> Result<()> { async fn test_conversion() -> Result<()> {
run_once(&REGISTRATION, || async { // pass a nonce to re-run the test body on every turbo-tasks restart
let unresolved: Vc<u32> = Vc::cell(42); let mut nonce = 0;
let resolved: ResolvedVc<u32> = unresolved.to_resolved().await?; run_once(&REGISTRATION, move || {
let _: Vc<u32> = *resolved; nonce += 1;
let _: ReadRef<u32> = resolved.await?; async move {
let _: ReadRef<u32> = (&resolved).await?; #[turbo_tasks::function(operation)]
let _: u32 = *resolved.await?; async fn test_operation(nonce: u32) -> Result<Vc<()>> {
let _: u32 = *(&resolved).await?; let _ = nonce; // ensure the nonce is part of our cache key
Ok(()) let unresolved: Vc<u32> = Vc::cell(42);
let resolved: ResolvedVc<u32> = unresolved.to_resolved().await?;
let _: Vc<u32> = *resolved;
let _: ReadRef<u32> = resolved.await?;
let _: ReadRef<u32> = (&resolved).await?;
let _: u32 = *resolved.await?;
let _: u32 = *(&resolved).await?;
Ok(Vc::cell(()))
}
test_operation(nonce).read_strongly_consistent().await
}
}) })
.await .await
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_cell_construction() -> Result<()> { async fn test_cell_construction() -> Result<()> {
run_once(&REGISTRATION, || async { let mut nonce = 0;
let a: ResolvedVc<u32> = ResolvedVc::cell(42); run_once(&REGISTRATION, move || {
assert_eq!(*a.await?, 42); nonce += 1;
let b: ResolvedVc<Wrapper> = Wrapper(42).resolved_cell(); async move {
assert_eq!(b.await?.0, 42); #[turbo_tasks::function(operation)]
Ok(()) async fn test_operation(nonce: u32) -> Result<Vc<()>> {
let _ = nonce;
let a: ResolvedVc<u32> = ResolvedVc::cell(42);
assert_eq!(*a.await?, 42);
let b: ResolvedVc<Wrapper> = Wrapper(42).resolved_cell();
assert_eq!(b.await?.0, 42);
Ok(Vc::cell(()))
}
test_operation(nonce).read_strongly_consistent().await
}
}) })
.await .await
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_resolved_vc_as_arg() -> Result<()> { async fn test_resolved_vc_as_arg() -> Result<()> {
run_once(&REGISTRATION, || async { let mut nonce = 0;
let unresolved: Vc<u32> = returns_int(42); run_once(&REGISTRATION, move || {
assert!(!unresolved.is_resolved()); nonce += 1;
// calling a function should cause it's arguments to get resolved automatically async move {
assert_resolved(unresolved).await?; #[turbo_tasks::function(operation)]
Ok(()) async fn test_operation(nonce: u32) -> Result<Vc<()>> {
dbg!(nonce);
let _ = nonce;
let unresolved: Vc<u32> = returns_int(42);
assert!(!unresolved.is_resolved());
// calling a function should cause it's arguments to get resolved automatically
assert_resolved(unresolved).await?;
Ok(Vc::cell(()))
}
test_operation(nonce).read_strongly_consistent().await
}
}) })
.await .await
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_into_future() -> Result<()> { async fn test_into_future() -> Result<()> {
run_once(&REGISTRATION, || async { let mut nonce = 0;
let mut resolved = ResolvedVc::cell(42); run_once(&REGISTRATION, move || {
let _: ReadRef<u32> = resolved.await?; nonce += 1;
let _: ReadRef<u32> = (&resolved).await?; async move {
let _: ReadRef<u32> = (&mut resolved).await?; #[turbo_tasks::function(operation)]
let mut unresolved = Vc::cell(42); async fn test_operation(nonce: u32) -> Result<Vc<()>> {
let _: ReadRef<u32> = unresolved.await?; let _ = nonce;
let _: ReadRef<u32> = (&unresolved).await?; let mut resolved = ResolvedVc::cell(42);
let _: ReadRef<u32> = (&mut unresolved).await?; let _: ReadRef<u32> = resolved.await?;
Ok(()) let _: ReadRef<u32> = (&resolved).await?;
let _: ReadRef<u32> = (&mut resolved).await?;
let mut unresolved = Vc::cell(42);
let _: ReadRef<u32> = unresolved.await?;
let _: ReadRef<u32> = (&unresolved).await?;
let _: ReadRef<u32> = (&mut unresolved).await?;
Ok(Vc::cell(()))
}
test_operation(nonce).read_strongly_consistent().await
}
}) })
.await .await
} }
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use anyhow::Result; use anyhow::Result;
use turbo_tasks::Vc; use turbo_tasks::{ResolvedVc, Vc};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
...@@ -14,10 +14,12 @@ struct Wrapper(Vec<u32>); ...@@ -14,10 +14,12 @@ struct Wrapper(Vec<u32>);
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_shrink_to_fit() -> Result<()> { async fn test_shrink_to_fit() -> Result<()> {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
// `Vec::shrink_to_fit` is implicitly called when a cell is constructed. #[turbo_tasks::function(operation)]
let a: Vc<Wrapper> = Vc::cell(Vec::with_capacity(100)); async fn capacity_operation(wrapper: ResolvedVc<Wrapper>) -> Result<Vc<usize>> {
assert_eq!(a.await?.capacity(), 0); Ok(Vc::cell(wrapper.await?.capacity()))
}
let a = ResolvedVc::<Wrapper>::cell(Vec::with_capacity(100));
assert_eq!(*capacity_operation(a).read_strongly_consistent().await?, 0);
Ok(()) Ok(())
}) })
.await .await
......
...@@ -6,7 +6,7 @@ use std::future::IntoFuture; ...@@ -6,7 +6,7 @@ use std::future::IntoFuture;
use anyhow::Result; use anyhow::Result;
use serde_json::json; use serde_json::json;
use turbo_tasks::Vc; use turbo_tasks::{Vc, unmark_top_level_task_may_leak_eventually_consistent_state};
use turbo_tasks_testing::{Registration, register, run_without_cache_check}; use turbo_tasks_testing::{Registration, register, run_without_cache_check};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
...@@ -14,6 +14,7 @@ static REGISTRATION: Registration = register!(); ...@@ -14,6 +14,7 @@ static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_simple_task() -> Result<()> { async fn test_simple_task() -> Result<()> {
run_without_cache_check(&REGISTRATION, async move { run_without_cache_check(&REGISTRATION, async move {
unmark_top_level_task_may_leak_eventually_consistent_state();
enable_stats(); enable_stats();
for i in 0..10 { for i in 0..10 {
double(i).await.unwrap(); double(i).await.unwrap();
...@@ -40,6 +41,7 @@ async fn test_simple_task() -> Result<()> { ...@@ -40,6 +41,7 @@ async fn test_simple_task() -> Result<()> {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_await_same_vc_multiple_times() -> Result<()> { async fn test_await_same_vc_multiple_times() -> Result<()> {
run_without_cache_check(&REGISTRATION, async move { run_without_cache_check(&REGISTRATION, async move {
unmark_top_level_task_may_leak_eventually_consistent_state();
enable_stats(); enable_stats();
let dvc = double(0); let dvc = double(0);
// this is awaited multiple times, but only resolved once // this is awaited multiple times, but only resolved once
...@@ -62,6 +64,7 @@ async fn test_await_same_vc_multiple_times() -> Result<()> { ...@@ -62,6 +64,7 @@ async fn test_await_same_vc_multiple_times() -> Result<()> {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_vc_receiving_task() -> Result<()> { async fn test_vc_receiving_task() -> Result<()> {
run_without_cache_check(&REGISTRATION, async move { run_without_cache_check(&REGISTRATION, async move {
unmark_top_level_task_may_leak_eventually_consistent_state();
enable_stats(); enable_stats();
for i in 0..10 { for i in 0..10 {
let dvc = double(i); let dvc = double(i);
...@@ -94,6 +97,7 @@ async fn test_vc_receiving_task() -> Result<()> { ...@@ -94,6 +97,7 @@ async fn test_vc_receiving_task() -> Result<()> {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_trait_methods() -> Result<()> { async fn test_trait_methods() -> Result<()> {
run_without_cache_check(&REGISTRATION, async move { run_without_cache_check(&REGISTRATION, async move {
unmark_top_level_task_may_leak_eventually_consistent_state();
enable_stats(); enable_stats();
for i in 0..10 { for i in 0..10 {
let wvc = wrap(i); let wvc = wrap(i);
...@@ -131,6 +135,7 @@ async fn test_trait_methods() -> Result<()> { ...@@ -131,6 +135,7 @@ async fn test_trait_methods() -> Result<()> {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_dyn_trait_methods() -> Result<()> { async fn test_dyn_trait_methods() -> Result<()> {
run_without_cache_check(&REGISTRATION, async move { run_without_cache_check(&REGISTRATION, async move {
unmark_top_level_task_may_leak_eventually_consistent_state();
enable_stats(); enable_stats();
for i in 0..10 { for i in 0..10 {
let wvc: Vc<Box<dyn Doublable>> = Vc::upcast(wrap(i)); let wvc: Vc<Box<dyn Doublable>> = Vc::upcast(wrap(i));
...@@ -175,6 +180,7 @@ async fn test_dyn_trait_methods() -> Result<()> { ...@@ -175,6 +180,7 @@ async fn test_dyn_trait_methods() -> Result<()> {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_no_execution() -> Result<()> { async fn test_no_execution() -> Result<()> {
run_without_cache_check(&REGISTRATION, async move { run_without_cache_check(&REGISTRATION, async move {
unmark_top_level_task_may_leak_eventually_consistent_state();
enable_stats(); enable_stats();
wrap_vc(double_vc(double(123))) wrap_vc(double_vc(double(123)))
.double() .double()
...@@ -214,6 +220,7 @@ async fn test_no_execution() -> Result<()> { ...@@ -214,6 +220,7 @@ async fn test_no_execution() -> Result<()> {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_inline_definitions() -> Result<()> { async fn test_inline_definitions() -> Result<()> {
run_without_cache_check(&REGISTRATION, async move { run_without_cache_check(&REGISTRATION, async move {
unmark_top_level_task_may_leak_eventually_consistent_state();
enable_stats(); enable_stats();
inline_definitions().await?; inline_definitions().await?;
assert_eq!( assert_eq!(
......
#![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::{
Vc, mark_top_level_task, unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!();
#[turbo_tasks::value]
#[derive(Clone, Debug)]
struct Value {
value: u32,
}
#[turbo_tasks::function(operation)]
async fn returns_value_operation() -> Result<Vc<Value>> {
Ok(Value { value: 42 }.cell())
}
/// Test that eventually consistent reads (default .await) cause an error in top-level tasks
/// The panic happens but we just verify it's an error, not the exact message
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic]
async fn test_eventual_read_in_top_level_task_fails() {
run_once(&REGISTRATION, || async {
// This should fail because we're in a top-level task (run_once)
// and doing an eventually consistent read (default .await)
returns_value_operation().connect().await
})
.await
.unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic]
async fn test_cell_read_in_top_level_task_fails() {
run_once(&REGISTRATION, || async {
let cell = returns_value_operation()
.resolve_strongly_consistent()
.await?;
let _ = cell.await?;
Ok(())
})
.await
.unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_manual_mark_unmark_top_level_task() {
run_once(&REGISTRATION, || async {
// We're in a top-level task initially, but let's unmark it
unmark_top_level_task_may_leak_eventually_consistent_state();
// Now eventually consistent reads should work
let value = returns_value_operation().connect().await?;
assert_eq!(value.value, 42);
// Re-mark as top-level task
mark_top_level_task();
anyhow::Ok(())
})
.await
.unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[should_panic]
async fn test_manual_mark_top_level_task_causes_error() {
#[turbo_tasks::function(operation)]
async fn operation() -> Result<Vc<Value>> {
// Manually mark as top-level task
mark_top_level_task();
// This should panic because we marked it as a top-level task
returns_value_operation().connect().await?;
Ok(Value { value: 42 }.cell())
}
run_once(&REGISTRATION, || async {
operation().read_strongly_consistent().await
})
.await
.unwrap()
}
...@@ -21,15 +21,13 @@ Adder::add_method (read cell of type u64) ...@@ -21,15 +21,13 @@ Adder::add_method (read cell of type u64)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_trace_transient() { async fn test_trace_transient() {
let result = run_once_without_cache_check(&REGISTRATION, async { let result = run_once_without_cache_check(&REGISTRATION, async {
read_incorrect_task_input_operation(IncorrectTaskInput( test_trace_transient_operation(
Adder::new(Vc::cell(())) ResolvedVc::cell(()),
.add_method(Vc::cell(2), Vc::cell(3)) ResolvedVc::<u16>::cell(2),
.to_resolved() ResolvedVc::<u32>::cell(3),
.await?, )
))
.read_strongly_consistent() .read_strongly_consistent()
.await?; .await
anyhow::Ok(())
}) })
.await; .await;
...@@ -37,6 +35,19 @@ async fn test_trace_transient() { ...@@ -37,6 +35,19 @@ async fn test_trace_transient() {
assert!(message.contains(&EXPECTED_TRACE.to_string())); assert!(message.contains(&EXPECTED_TRACE.to_string()));
} }
#[turbo_tasks::function(operation)]
async fn test_trace_transient_operation(
arg1: ResolvedVc<()>,
arg2: ResolvedVc<u16>,
arg3: ResolvedVc<u32>,
) -> Result<Vc<u64>> {
let resolved = Adder::new(*arg1)
.add_method(*arg2, *arg3)
.to_resolved()
.await?;
Ok(read_incorrect_task_input(IncorrectTaskInput(resolved)))
}
#[turbo_tasks::value] #[turbo_tasks::value]
struct Adder; struct Adder;
...@@ -55,8 +66,8 @@ impl Adder { ...@@ -55,8 +66,8 @@ impl Adder {
} }
} }
#[turbo_tasks::function(operation)] #[turbo_tasks::function]
async fn read_incorrect_task_input_operation(value: IncorrectTaskInput) -> Result<Vc<u64>> { async fn read_incorrect_task_input(value: IncorrectTaskInput) -> Result<Vc<u64>> {
Ok(Vc::cell(*value.0.await?)) Ok(Vc::cell(*value.0.await?))
} }
......
...@@ -5,7 +5,10 @@ ...@@ -5,7 +5,10 @@
use std::{collections::HashSet, mem::take, sync::Mutex}; use std::{collections::HashSet, mem::take, sync::Mutex};
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{IntoTraitRef, Invalidator, TraitRef, Vc, get_invalidator, with_turbo_tasks}; use turbo_tasks::{
IntoTraitRef, Invalidator, TraitRef, Vc, get_invalidator,
unmark_top_level_task_may_leak_eventually_consistent_state, with_turbo_tasks,
};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
...@@ -13,6 +16,7 @@ static REGISTRATION: Registration = register!(); ...@@ -13,6 +16,7 @@ static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn trait_ref() { async fn trait_ref() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let counter = Counter::cell(Counter { let counter = Counter::cell(Counter {
value: Mutex::new((0, Default::default())), value: Mutex::new((0, Default::default())),
}); });
......
...@@ -2,7 +2,10 @@ ...@@ -2,7 +2,10 @@
#![feature(arbitrary_self_types_pointers)] #![feature(arbitrary_self_types_pointers)]
use anyhow::Result; use anyhow::Result;
use turbo_tasks::{IntoTraitRef, State, TraitRef, Upcast, Vc}; use turbo_tasks::{
IntoTraitRef, State, TraitRef, Upcast, Vc,
unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
...@@ -12,6 +15,7 @@ static REGISTRATION: Registration = register!(); ...@@ -12,6 +15,7 @@ static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_trait_ref_shared_cell_mode() { async fn test_trait_ref_shared_cell_mode() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let input = CellIdSelector { let input = CellIdSelector {
value: 42, value: 42,
cell_idx: State::new(0), cell_idx: State::new(0),
...@@ -47,6 +51,7 @@ async fn test_trait_ref_shared_cell_mode() { ...@@ -47,6 +51,7 @@ async fn test_trait_ref_shared_cell_mode() {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_trait_ref_new_cell_mode() { async fn test_trait_ref_new_cell_mode() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
unmark_top_level_task_may_leak_eventually_consistent_state();
let input = CellIdSelector { let input = CellIdSelector {
value: 42, value: 42,
cell_idx: State::new(0), cell_idx: State::new(0),
......
This diff is collapsed.
...@@ -11,9 +11,10 @@ bincode = { workspace = true } ...@@ -11,9 +11,10 @@ bincode = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
trybuild = { version = "1.0.116" } trybuild = { version = "1.0.116" }
turbo-rcstr = { workspace = true }
turbo-tasks = { workspace = true } turbo-tasks = { workspace = true }
turbo-tasks-testing = { workspace = true }
turbo-tasks-backend = { workspace = true } turbo-tasks-backend = { workspace = true }
turbo-tasks-testing = { workspace = true }
[lints] [lints]
workspace = true workspace = true
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
//! macro and the `#[turbo_tasks::function]` macro. //! macro and the `#[turbo_tasks::function]` macro.
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use anyhow::Result;
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use turbo_tasks::{Completion, ReadRef, TaskInput, Vc, trace::TraceRawVcs}; use turbo_tasks::{Completion, ReadRef, TaskInput, Vc, trace::TraceRawVcs};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
...@@ -21,10 +22,14 @@ fn one_unnamed_field(input: OneUnnamedField) -> Vc<Completion> { ...@@ -21,10 +22,14 @@ fn one_unnamed_field(input: OneUnnamedField) -> Vc<Completion> {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tests() { async fn tests() {
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
assert!(ReadRef::ptr_eq( #[turbo_tasks::function(operation)]
&one_unnamed_field(OneUnnamedField(42)).await?, async fn equality_operation() -> Result<Vc<bool>> {
&Completion::immutable().await?, Ok(Vc::cell(ReadRef::ptr_eq(
)); &one_unnamed_field(OneUnnamedField(42)).await?,
&Completion::immutable().await?,
)))
}
equality_operation().read_strongly_consistent().await?;
anyhow::Ok(()) anyhow::Ok(())
}) })
.await .await
......
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this #![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use turbo_tasks::debug::ValueDebugFormat; use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_tasks::{Vc, debug::ValueDebugFormat};
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!(); static REGISTRATION: Registration = register!();
...@@ -20,8 +22,15 @@ async fn ignored_indexes() { ...@@ -20,8 +22,15 @@ async fn ignored_indexes() {
); );
run_once(&REGISTRATION, || async { run_once(&REGISTRATION, || async {
let input = IgnoredIndexes(-1, 2, -3); #[turbo_tasks::function(operation)]
let debug = input.value_debug_format(usize::MAX).try_to_string().await?; async fn value_debug_format_operation() -> Result<Vc<RcStr>> {
let input = IgnoredIndexes(-1, 2, -3);
let debug = input.value_debug_format(usize::MAX).try_to_string().await?;
Ok(Vc::cell(RcStr::from(debug)))
}
let debug = value_debug_format_operation()
.read_strongly_consistent()
.await?;
assert!(!debug.contains("-1")); assert!(!debug.contains("-1"));
assert!(debug.contains('2')); assert!(debug.contains('2'));
assert!(!debug.contains("-3")); assert!(!debug.contains("-3"));
......
...@@ -70,7 +70,7 @@ fn closure_to_name<T>(value: &T) -> String { ...@@ -70,7 +70,7 @@ fn closure_to_name<T>(value: &T) -> String {
pub async fn run_once<T, F>( pub async fn run_once<T, F>(
registration: &Registration, registration: &Registration,
fut: impl Fn() -> F + Send + 'static, mut fut: impl FnMut() -> F + Send + 'static,
) -> Result<()> ) -> Result<()>
where where
F: Future<Output = Result<T>> + Send + 'static, F: Future<Output = Result<T>> + Send + 'static,
...@@ -81,7 +81,7 @@ where ...@@ -81,7 +81,7 @@ where
pub async fn run<T, F>( pub async fn run<T, F>(
registration: &Registration, registration: &Registration,
fut: impl Fn() -> F + Send + 'static, mut fut: impl FnMut() -> F + Send + 'static,
) -> Result<()> ) -> Result<()>
where where
F: Future<Output = Result<T>> + Send + 'static, F: Future<Output = Result<T>> + Send + 'static,
...@@ -92,7 +92,7 @@ where ...@@ -92,7 +92,7 @@ where
pub async fn run_with_tt<T, F>( pub async fn run_with_tt<T, F>(
registration: &Registration, registration: &Registration,
fut: impl Fn(Arc<dyn TurboTasksApi>) -> F + Send + 'static, mut fut: impl FnMut(Arc<dyn TurboTasksApi>) -> F + Send + 'static,
) -> Result<()> ) -> Result<()>
where where
F: Future<Output = Result<T>> + Send + 'static, F: Future<Output = Result<T>> + Send + 'static,
......
...@@ -116,8 +116,9 @@ pub use crate::{ ...@@ -116,8 +116,9 @@ pub use crate::{
CurrentCellRef, ReadCellTracking, ReadConsistency, ReadTracking, TaskPersistence, CurrentCellRef, ReadCellTracking, ReadConsistency, ReadTracking, TaskPersistence,
TaskPriority, TurboTasks, TurboTasksApi, TurboTasksBackendApi, TurboTasksCallApi, Unused, TaskPriority, TurboTasks, TurboTasksApi, TurboTasksBackendApi, TurboTasksCallApi, Unused,
UpdateInfo, dynamic_call, emit, get_serialization_invalidator, mark_finished, UpdateInfo, dynamic_call, emit, get_serialization_invalidator, mark_finished,
mark_session_dependent, mark_stateful, prevent_gc, run, run_once, run_once_with_reason, mark_session_dependent, mark_stateful, mark_top_level_task, prevent_gc, run, run_once,
trait_call, turbo_tasks, turbo_tasks_scope, turbo_tasks_weak, with_turbo_tasks, run_once_with_reason, trait_call, turbo_tasks, turbo_tasks_scope, turbo_tasks_weak,
unmark_top_level_task_may_leak_eventually_consistent_state, with_turbo_tasks,
}, },
mapped_read_ref::MappedReadRef, mapped_read_ref::MappedReadRef,
output::OutputContent, output::OutputContent,
......
...@@ -525,6 +525,10 @@ struct CurrentTaskState { ...@@ -525,6 +525,10 @@ struct CurrentTaskState {
/// True if the current task uses an external invalidator /// True if the current task uses an external invalidator
has_invalidator: bool, has_invalidator: bool,
/// True if we're in a top-level task (e.g. `.run_once(...)` or `.run(...)`).
/// Eventually consistent reads are not allowed in top-level tasks.
in_top_level_task: bool,
/// Tracks how many cells of each type has been allocated so far during this task execution. /// Tracks how many cells of each type has been allocated so far during this task execution.
/// When a task is re-executed, the cell count may not match the existing cell vec length. /// When a task is re-executed, the cell count may not match the existing cell vec length.
/// ///
...@@ -540,7 +544,12 @@ struct CurrentTaskState { ...@@ -540,7 +544,12 @@ struct CurrentTaskState {
} }
impl CurrentTaskState { impl CurrentTaskState {
fn new(task_id: TaskId, execution_id: ExecutionId, priority: TaskPriority) -> Self { fn new(
task_id: TaskId,
execution_id: ExecutionId,
priority: TaskPriority,
in_top_level_task: bool,
) -> Self {
Self { Self {
task_id: Some(task_id), task_id: Some(task_id),
execution_id, execution_id,
...@@ -548,13 +557,18 @@ impl CurrentTaskState { ...@@ -548,13 +557,18 @@ impl CurrentTaskState {
#[cfg(feature = "verify_determinism")] #[cfg(feature = "verify_determinism")]
stateful: false, stateful: false,
has_invalidator: false, has_invalidator: false,
in_top_level_task,
cell_counters: Some(AutoMap::default()), cell_counters: Some(AutoMap::default()),
local_tasks: Vec::new(), local_tasks: Vec::new(),
local_task_tracker: None, local_task_tracker: None,
} }
} }
fn new_temporary(execution_id: ExecutionId, priority: TaskPriority) -> Self { fn new_temporary(
execution_id: ExecutionId,
priority: TaskPriority,
in_top_level_task: bool,
) -> Self {
Self { Self {
task_id: None, task_id: None,
execution_id, execution_id,
...@@ -562,6 +576,7 @@ impl CurrentTaskState { ...@@ -562,6 +576,7 @@ impl CurrentTaskState {
#[cfg(feature = "verify_determinism")] #[cfg(feature = "verify_determinism")]
stateful: false, stateful: false,
has_invalidator: false, has_invalidator: false,
in_top_level_task,
cell_counters: None, cell_counters: None,
local_tasks: Vec::new(), local_tasks: Vec::new(),
local_task_tracker: None, local_task_tracker: None,
...@@ -603,6 +618,12 @@ task_local! { ...@@ -603,6 +618,12 @@ task_local! {
static TURBO_TASKS: Arc<dyn TurboTasksApi>; static TURBO_TASKS: Arc<dyn TurboTasksApi>;
static CURRENT_TASK_STATE: Arc<RwLock<CurrentTaskState>>; static CURRENT_TASK_STATE: Arc<RwLock<CurrentTaskState>>;
/// Temporarily suppresses the eventual consistency check in top-level tasks.
/// This is used by strongly consistent reads to allow them to succeed in top-level tasks.
/// This is NOT shared across local tasks (unlike CURRENT_TASK_STATE), so it's safe
/// to set/unset without race conditions.
pub(crate) static SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK: bool;
} }
impl<B: Backend + 'static> TurboTasks<B> { impl<B: Backend + 'static> TurboTasks<B> {
...@@ -702,6 +723,7 @@ impl<B: Backend + 'static> TurboTasks<B> { ...@@ -702,6 +723,7 @@ impl<B: Backend + 'static> TurboTasks<B> {
) -> Result<T> { ) -> Result<T> {
let (tx, rx) = tokio::sync::oneshot::channel(); let (tx, rx) = tokio::sync::oneshot::channel();
self.spawn_once_task(async move { self.spawn_once_task(async move {
mark_top_level_task();
let result = future.await; let result = future.await;
tx.send(result) tx.send(result)
.map_err(|_| anyhow!("unable to send result"))?; .map_err(|_| anyhow!("unable to send result"))?;
...@@ -722,6 +744,7 @@ impl<B: Backend + 'static> TurboTasks<B> { ...@@ -722,6 +744,7 @@ impl<B: Backend + 'static> TurboTasks<B> {
let current_task_state = Arc::new(RwLock::new(CurrentTaskState::new_temporary( let current_task_state = Arc::new(RwLock::new(CurrentTaskState::new_temporary(
execution_id, execution_id,
TaskPriority::initial(), TaskPriority::initial(),
true, // in_top_level_task
))); )));
let result = TURBO_TASKS let result = TURBO_TASKS
...@@ -1190,6 +1213,7 @@ impl<B: Backend> Executor<TurboTasks<B>, ScheduledTask, TaskPriority> for TurboT ...@@ -1190,6 +1213,7 @@ impl<B: Backend> Executor<TurboTasks<B>, ScheduledTask, TaskPriority> for TurboT
task_id, task_id,
execution_id, execution_id,
priority, priority,
false, // in_top_level_task
))); )));
let single_execution_future = async { let single_execution_future = async {
if this.stopped.load(Ordering::Acquire) { if this.stopped.load(Ordering::Acquire) {
...@@ -1424,11 +1448,15 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> { ...@@ -1424,11 +1448,15 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
self.backend.invalidate_serialization(task, self); self.backend.invalidate_serialization(task, self);
} }
#[track_caller]
fn try_read_task_output( fn try_read_task_output(
&self, &self,
task: TaskId, task: TaskId,
options: ReadOutputOptions, options: ReadOutputOptions,
) -> Result<Result<RawVc, EventListener>> { ) -> Result<Result<RawVc, EventListener>> {
if options.consistency == ReadConsistency::Eventual {
debug_assert_not_in_top_level_task("read_task_output");
}
self.backend.try_read_task_output( self.backend.try_read_task_output(
task, task,
current_task_if_available("reading Vcs"), current_task_if_available("reading Vcs"),
...@@ -1437,19 +1465,19 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> { ...@@ -1437,19 +1465,19 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
) )
} }
#[track_caller]
fn try_read_task_cell( fn try_read_task_cell(
&self, &self,
task: TaskId, task: TaskId,
index: CellId, index: CellId,
options: ReadCellOptions, options: ReadCellOptions,
) -> Result<Result<TypedCellContent, EventListener>> { ) -> Result<Result<TypedCellContent, EventListener>> {
self.backend.try_read_task_cell( let reader = current_task_if_available("reading Vcs");
task, if cfg!(debug_assertions) && reader != Some(task) {
index, debug_assert_not_in_top_level_task("read_task_cell");
current_task_if_available("reading Vcs"), }
options, self.backend
self, .try_read_task_cell(task, index, reader, options, self)
)
} }
fn try_read_own_task_cell( fn try_read_own_task_cell(
...@@ -1462,11 +1490,13 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> { ...@@ -1462,11 +1490,13 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
.try_read_own_task_cell(current_task, index, options, self) .try_read_own_task_cell(current_task, index, options, self)
} }
#[track_caller]
fn try_read_local_output( fn try_read_local_output(
&self, &self,
execution_id: ExecutionId, execution_id: ExecutionId,
local_task_id: LocalTaskId, local_task_id: LocalTaskId,
) -> Result<Result<RawVc, EventListener>> { ) -> Result<Result<RawVc, EventListener>> {
debug_assert_not_in_top_level_task("read_local_output");
CURRENT_TASK_STATE.with(|gts| { CURRENT_TASK_STATE.with(|gts| {
let gts_read = gts.read().unwrap(); let gts_read = gts.read().unwrap();
...@@ -1484,6 +1514,8 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> { ...@@ -1484,6 +1514,8 @@ impl<B: Backend + 'static> TurboTasksApi for TurboTasks<B> {
} }
fn read_task_collectibles(&self, task: TaskId, trait_id: TraitTypeId) -> TaskCollectiblesMap { fn read_task_collectibles(&self, task: TaskId, trait_id: TraitTypeId) -> TaskCollectiblesMap {
// TODO: Add assert_not_in_top_level_task("read_task_collectibles") check here.
// Collectible reads are eventually consistent.
self.backend.read_task_collectibles( self.backend.read_task_collectibles(
task, task,
trait_id, trait_id,
...@@ -1701,6 +1733,33 @@ pub(crate) fn current_task(from: &str) -> TaskId { ...@@ -1701,6 +1733,33 @@ pub(crate) fn current_task(from: &str) -> TaskId {
} }
} }
#[track_caller]
fn debug_assert_not_in_top_level_task(operation: &str) {
if !cfg!(debug_assertions) {
return;
}
// HACK: We set this inside of `ReadRawVcFuture` to suppress warnings about an internal
// consistency bug
let suppressed = SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK
.try_with(|&suppressed| suppressed)
.unwrap_or(false);
if suppressed {
return;
}
let in_top_level = CURRENT_TASK_STATE
.try_with(|ts| ts.read().unwrap().in_top_level_task)
.unwrap_or(false);
if in_top_level {
panic!(
"Eventually consistent read ({operation}) cannot be performed from a top-level task. \
Top-level tasks (e.g. code inside `.run_once(...)`) must use strongly consistent \
reads to avoid leaking inconsistent return values."
);
}
}
pub async fn run<T: Send + 'static>( pub async fn run<T: Send + 'static>(
tt: Arc<dyn TurboTasksApi>, tt: Arc<dyn TurboTasksApi>,
future: impl Future<Output = Result<T>> + Send + 'static, future: impl Future<Output = Result<T>> + Send + 'static,
...@@ -1816,6 +1875,7 @@ pub fn with_turbo_tasks_for_testing<T>( ...@@ -1816,6 +1875,7 @@ pub fn with_turbo_tasks_for_testing<T>(
current_task, current_task,
execution_id, execution_id,
TaskPriority::initial(), TaskPriority::initial(),
false, // in_top_level_task
))), ))),
f, f,
), ),
...@@ -1901,6 +1961,35 @@ pub fn mark_stateful() { ...@@ -1901,6 +1961,35 @@ pub fn mark_stateful() {
// No-op when verify_determinism is not enabled // No-op when verify_determinism is not enabled
} }
/// Marks the current task context as being in a top-level task. When in a top-level task,
/// eventually consistent reads will panic. It is almost always a mistake to perform an eventually
/// consistent read at the top-level of the application.
pub fn mark_top_level_task() {
if cfg!(debug_assertions) {
CURRENT_TASK_STATE.with(|cell| {
cell.write().unwrap().in_top_level_task = true;
})
}
}
/// Unmarks the current task context as being in a top-level task. The opposite of
/// [`mark_top_level_task`].
///
/// This utility can be okay in unit tests, where we're observing the internal behavior of
/// turbo-tasks, but otherwise, it is probably a mistake to call this function.
///
/// Calling this will allow eventually-consistent reads at the top-level, potentially exposing
/// incomplete computations and internal errors caused by eventual consistency that would've been
/// caught when the function was re-run. A strongly-consistent read re-runs parts of a task until
/// all of the dependencies have settled.
pub fn unmark_top_level_task_may_leak_eventually_consistent_state() {
if cfg!(debug_assertions) {
CURRENT_TASK_STATE.with(|cell| {
cell.write().unwrap().in_top_level_task = false;
})
}
}
pub fn prevent_gc() { pub fn prevent_gc() {
// TODO implement garbage collection // TODO implement garbage collection
} }
......
...@@ -2,6 +2,7 @@ use std::{ ...@@ -2,6 +2,7 @@ use std::{
fmt::{Debug, Display}, fmt::{Debug, Display},
future::Future, future::Future,
pin::Pin, pin::Pin,
sync::Arc,
task::Poll, task::Poll,
}; };
...@@ -17,7 +18,8 @@ use crate::{ ...@@ -17,7 +18,8 @@ use crate::{
event::EventListener, event::EventListener,
id::{ExecutionId, LocalTaskId}, id::{ExecutionId, LocalTaskId},
manager::{ manager::{
ReadCellTracking, ReadTracking, read_local_output, read_task_output, with_turbo_tasks, ReadCellTracking, ReadTracking, SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK,
TurboTasksApi, read_local_output, read_task_output, with_turbo_tasks,
}, },
registry::{self, get_value_type}, registry::{self, get_value_type},
turbo_tasks, turbo_tasks,
...@@ -158,10 +160,12 @@ impl RawVc { ...@@ -158,10 +160,12 @@ impl RawVc {
/// See [`crate::Vc::resolve_strongly_consistent`]. /// See [`crate::Vc::resolve_strongly_consistent`].
pub(crate) async fn resolve_strongly_consistent(self) -> Result<RawVc> { pub(crate) async fn resolve_strongly_consistent(self) -> Result<RawVc> {
self.resolve_inner(ReadOutputOptions { SuppressTopLevelTaskCheckFuture {
consistency: ReadConsistency::Strong, inner: self.resolve_inner(ReadOutputOptions {
..Default::default() consistency: ReadConsistency::Strong,
}) ..Default::default()
}),
}
.await .await
} }
...@@ -290,11 +294,36 @@ impl CollectiblesSource for RawVc { ...@@ -290,11 +294,36 @@ impl CollectiblesSource for RawVc {
} }
} }
/// A future wrapper that suppresses the top-level task eventual consistency check
/// during each [`poll`][Future::poll] call. The suppression is applied via
/// [`sync_scope`][tokio::task_local!] so it is only active during the synchronous
/// execution of the inner future's `poll`, and is never held across await points.
struct SuppressTopLevelTaskCheckFuture<F> {
inner: F,
}
impl<F: Future> Future for SuppressTopLevelTaskCheckFuture<F> {
type Output = F::Output;
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
// SAFETY: we are only projecting the pin to the inner field, not moving it
let inner = unsafe { self.map_unchecked_mut(|this| &mut this.inner) };
if cfg!(debug_assertions) {
SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK.sync_scope(true, || inner.poll(cx))
} else {
inner.poll(cx)
}
}
}
pub struct ReadRawVcFuture { pub struct ReadRawVcFuture {
current: RawVc, current: RawVc,
read_output_options: ReadOutputOptions, read_output_options: ReadOutputOptions,
read_cell_options: ReadCellOptions, read_cell_options: ReadCellOptions,
is_serializable_cell_content_unknown: bool, is_serializable_cell_content_unknown: bool,
/// This flag redundant with `read_output_options`, but `read_output_options` is mutated during
/// the read. This flag indicates that the initial read was strongly consistent.
strongly_consistent: bool,
listener: Option<EventListener>, listener: Option<EventListener>,
} }
...@@ -308,6 +337,7 @@ impl ReadRawVcFuture { ...@@ -308,6 +337,7 @@ impl ReadRawVcFuture {
..Default::default() ..Default::default()
}, },
is_serializable_cell_content_unknown: is_serializable_cell_content.is_none(), is_serializable_cell_content_unknown: is_serializable_cell_content.is_none(),
strongly_consistent: false,
listener: None, listener: None,
} }
} }
...@@ -315,6 +345,7 @@ impl ReadRawVcFuture { ...@@ -315,6 +345,7 @@ impl ReadRawVcFuture {
/// Make reads strongly consistent. /// Make reads strongly consistent.
pub fn strongly_consistent(mut self) -> Self { pub fn strongly_consistent(mut self) -> Self {
self.read_output_options.consistency = ReadConsistency::Strong; self.read_output_options.consistency = ReadConsistency::Strong;
self.strongly_consistent = true;
self self
} }
...@@ -347,9 +378,11 @@ impl Future for ReadRawVcFuture { ...@@ -347,9 +378,11 @@ impl Future for ReadRawVcFuture {
type Output = Result<TypedCellContent>; type Output = Result<TypedCellContent>;
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
with_turbo_tasks(|tt| { // SAFETY: we are not moving self
// SAFETY: we are not moving this let this = unsafe { self.get_unchecked_mut() };
let this = unsafe { self.get_unchecked_mut() };
// Extract the closure to avoid deep nesting
let poll_fn = |tt: &Arc<dyn TurboTasksApi>| -> Poll<Self::Output> {
'outer: loop { 'outer: loop {
if let Some(listener) = &mut this.listener { if let Some(listener) = &mut this.listener {
// SAFETY: listener is from previous pinned this // SAFETY: listener is from previous pinned this
...@@ -364,9 +397,14 @@ impl Future for ReadRawVcFuture { ...@@ -364,9 +397,14 @@ impl Future for ReadRawVcFuture {
let read_result = tt.try_read_task_output(task, this.read_output_options); let read_result = tt.try_read_task_output(task, this.read_output_options);
match read_result { match read_result {
Ok(Ok(vc)) => { Ok(Ok(vc)) => {
// We no longer need to read strongly consistent, as any Vc returned // turbo-tasks-backend doesn't currently have any sort of
// from the first task will be inside of the scope of the first // "transaction" or global lock mechanism to group together chains
// task. So it's already strongly consistent. // of `TaskOutput`/`TaskCell` reads.
//
// If we ignore the theoretical TOCTOU issues, we no longer need to
// read strongly consistent, as any Vc returned from the first task
// will be inside of the scope of the first task. So it's already
// strongly consistent.
this.read_output_options.consistency = ReadConsistency::Eventual; this.read_output_options.consistency = ReadConsistency::Eventual;
this.current = vc; this.current = vc;
continue 'outer; continue 'outer;
...@@ -417,7 +455,24 @@ impl Future for ReadRawVcFuture { ...@@ -417,7 +455,24 @@ impl Future for ReadRawVcFuture {
} }
}; };
} }
}) };
fn suppress_top_level_task_check<R>(strongly_consistent: bool, f: impl FnOnce() -> R) -> R {
if cfg!(debug_assertions) && strongly_consistent {
// Temporarily suppress the top-level task check
SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK.sync_scope(true, f)
} else {
f()
}
}
// HACK: Temporarily suppress top-level task check if doing strongly consistent read.
//
// This masks a bug: There's an unlikely TOCTOU race condition in `poll_fn`. Because the
// strongly consistent read isn't a single atomic operation, any inner `TaskOutput` or
// `TaskCell` could get mutated after the strongly consistent read of the outer
// `TaskOutput`.
suppress_top_level_task_check(this.strongly_consistent, || with_turbo_tasks(poll_fn))
} }
} }
......
...@@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize}; ...@@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize};
use turbo_tasks_hash::DeterministicHash; use turbo_tasks_hash::DeterministicHash;
use crate::{ use crate::{
SharedReference, Vc, VcRead, VcValueType, ResolvedVc, SharedReference, Vc, VcRead, VcValueType,
debug::{ValueDebugFormat, ValueDebugFormatString}, debug::{ValueDebugFormat, ValueDebugFormatString},
trace::{TraceRawVcs, TraceRawVcsContext}, trace::{TraceRawVcs, TraceRawVcsContext},
vc::VcCellMode, vc::VcCellMode,
...@@ -272,8 +272,7 @@ impl<T> ReadRef<T> ...@@ -272,8 +272,7 @@ impl<T> ReadRef<T>
where where
T: VcValueType, T: VcValueType,
{ {
/// Returns a new cell that points to the same value as the given /// Returns a new [`Vc`] that points to the same value as the given reference.
/// reference.
pub fn cell(read_ref: ReadRef<T>) -> Vc<T> { pub fn cell(read_ref: ReadRef<T>) -> Vc<T> {
let type_id = T::get_value_type_id(); let type_id = T::get_value_type_id();
Vc { Vc {
...@@ -283,6 +282,13 @@ where ...@@ -283,6 +282,13 @@ where
_t: PhantomData, _t: PhantomData,
} }
} }
/// Returns a new [`ResolvedVc`] that points to the same value as the given reference.
pub fn resolved_cell(read_ref: ReadRef<T>) -> ResolvedVc<T> {
ResolvedVc {
node: ReadRef::cell(read_ref),
}
}
} }
impl<T> ReadRef<T> impl<T> ReadRef<T>
......
...@@ -5,12 +5,12 @@ ...@@ -5,12 +5,12 @@
use anyhow::Result; use anyhow::Result;
use serde_json::json; use serde_json::json;
use turbo_rcstr::rcstr; use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{OperationVc, ResolvedVc, Vc};
use turbo_tasks_fs::{ use turbo_tasks_fs::{
File, FileContent, FileSystem, FileSystemPath, VirtualFileSystem, rope::Rope, File, FileContent, FileSystem, FileSystemPath, VirtualFileSystem, rope::Rope,
}; };
use turbo_tasks_testing::{Registration, register, run_once}; use turbo_tasks_testing::{Registration, register, run_once};
use turbopack_analyze::split_chunk::{ChunkPartRange, split_output_asset_into_parts}; use turbopack_analyze::split_chunk::{ChunkPartRange, ChunkParts, split_output_asset_into_parts};
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
code_builder::{Code, CodeBuilder}, code_builder::{Code, CodeBuilder},
...@@ -50,14 +50,18 @@ async fn split_chunk() { ...@@ -50,14 +50,18 @@ async fn split_chunk() {
code += "This is the end of the file.\n"; code += "This is the end of the file.\n";
let code = code.build(); let code = code.build();
let asset = Vc::upcast( let asset = TestAsset {
TestAsset { code: code.resolved_cell(),
code: code.resolved_cell(), }
} .resolved_cell();
.cell(),
); #[turbo_tasks::function(operation)]
fn split_parts_operation(asset: ResolvedVc<TestAsset>) -> Vc<ChunkParts> {
split_output_asset_into_parts(Vc::upcast(*asset))
}
let parts = split_output_asset_into_parts(asset).await.unwrap(); let parts_op = split_parts_operation(asset);
let parts = parts_op.read_strongly_consistent().await?;
assert_eq!(parts.len(), 2); assert_eq!(parts.len(), 2);
...@@ -92,10 +96,25 @@ async fn split_chunk() { ...@@ -92,10 +96,25 @@ async fn split_chunk() {
}] }]
); );
assert_eq!(parts[0].get_compressed_size().await.unwrap(), 43); #[turbo_tasks::function(operation)]
assert_eq!(parts[1].get_compressed_size().await.unwrap(), 28); async fn compressed_size_operation(
parts: OperationVc<ChunkParts>,
index: usize,
) -> Result<Vc<u32>> {
Ok(Vc::cell(
parts.connect().await?[index].get_compressed_size().await?,
))
}
let compressed_size_0 = compressed_size_operation(parts_op, 0)
.read_strongly_consistent()
.await?;
let compressed_size_1 = compressed_size_operation(parts_op, 1)
.read_strongly_consistent()
.await?;
assert_eq!(*compressed_size_0, 43);
assert_eq!(*compressed_size_1, 28);
println!("{:#?}", parts);
anyhow::Ok(()) anyhow::Ok(())
}) })
.await .await
......
...@@ -445,7 +445,8 @@ fn clean_additional_extensions(s: &str) -> String { ...@@ -445,7 +445,8 @@ fn clean_additional_extensions(s: &str) -> String {
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use turbo_rcstr::rcstr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::Vc;
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{FileSystem, VirtualFileSystem}; use turbo_tasks_fs::{FileSystem, VirtualFileSystem};
...@@ -458,13 +459,19 @@ pub mod tests { ...@@ -458,13 +459,19 @@ pub mod tests {
noop_backing_storage(), noop_backing_storage(),
)); ));
tt.run_once(async move { tt.run_once(async move {
let fs = VirtualFileSystem::new_with_name(rcstr!("test")); #[turbo_tasks::function(operation)]
let root = fs.root().owned().await?; async fn output_name_operation() -> anyhow::Result<Vc<RcStr>> {
let fs = VirtualFileSystem::new_with_name(rcstr!("test"));
let root = fs.root().owned().await?;
let asset_ident = AssetIdent::from_path(root.join("a:b?c#d.js")?);
let output_name = asset_ident
.output_name(root, Some(rcstr!("prefix")), rcstr!(".js"))
.await?;
Ok(Vc::cell((*output_name).clone()))
}
let asset_ident = AssetIdent::from_path(root.join("a:b?c#d.js")?); let output_name = output_name_operation().read_strongly_consistent().await?;
let output_name = asset_ident
.output_name(root.clone(), Some(rcstr!("prefix")), rcstr!(".js"))
.await?;
assert_eq!(&*output_name, "prefix-a_b_c_d.js"); assert_eq!(&*output_name, "prefix-a_b_c_d.js");
Ok(()) Ok(())
......
...@@ -3668,34 +3668,56 @@ mod tests { ...@@ -3668,34 +3668,56 @@ mod tests {
)); ));
tt.run_once(async move { tt.run_once(async move {
let fs = Vc::upcast::<Box<dyn FileSystem>>(DiskFileSystem::new(rcstr!("temp"), path)); #[turbo_tasks::value(transparent)]
let lookup_path = fs.root().owned().await?; struct ResolveRelativeRequestOutput(Vec<(String, String)>);
#[turbo_tasks::function(operation)]
async fn resolve_relative_request_operation(
path: RcStr,
pattern: Pattern,
enable_typescript_with_output_extension: bool,
fully_specified: bool,
) -> anyhow::Result<Vc<ResolveRelativeRequestOutput>> {
let fs = DiskFileSystem::new(rcstr!("temp"), path);
let lookup_path = fs.root().owned().await?;
let result = resolve_relative_helper(
lookup_path,
pattern,
enable_typescript_with_output_extension,
fully_specified,
)
.await?;
let results: Vec<(String, String)> = result
.primary
.iter()
.map(async |(k, v)| {
Ok((
k.to_string(),
if let ResolveResultItem::Source(source) = v {
source.ident().await?.path.path.to_string()
} else {
unreachable!()
},
))
})
.try_join()
.await?;
let result = resolve_relative_helper( Ok(Vc::cell(results))
lookup_path, }
let results = resolve_relative_request_operation(
path,
pattern, pattern,
enable_typescript_with_output_extension, enable_typescript_with_output_extension,
fully_specified, fully_specified,
) )
.read_strongly_consistent()
.await?; .await?;
let results: Vec<(String, String)> = result assert_eq!(&*results, &expected_owned);
.primary
.iter()
.map(async |(k, v)| {
Ok((
k.to_string(),
if let ResolveResultItem::Source(source) = v {
source.ident().await?.path.path.to_string()
} else {
unreachable!()
},
))
})
.try_join()
.await?;
assert_eq!(results, expected_owned);
Ok(()) Ok(())
}) })
......
...@@ -1902,6 +1902,7 @@ mod tests { ...@@ -1902,6 +1902,7 @@ mod tests {
use rstest::*; use rstest::*;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::Vc;
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{DiskFileSystem, FileSystem}; use turbo_tasks_fs::{DiskFileSystem, FileSystem};
...@@ -2656,22 +2657,28 @@ mod tests { ...@@ -2656,22 +2657,28 @@ mod tests {
noop_backing_storage(), noop_backing_storage(),
)); ));
tt.run_once(async { tt.run_once(async {
let root = DiskFileSystem::new( #[turbo_tasks::value]
rcstr!("test"), struct ReadMatchesOutput {
Path::new(env!("CARGO_MANIFEST_DIR")) dynamic: Vec<String>,
.join("tests/pattern/read_matches") dynamic_file_suffix: Vec<String>,
.to_str() node_modules_dynamic: Vec<String>,
.unwrap() }
.into(),
) #[turbo_tasks::function(operation)]
.root() async fn read_matches_operation() -> anyhow::Result<Vc<ReadMatchesOutput>> {
.owned() let root = DiskFileSystem::new(
.await?; rcstr!("test"),
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/pattern/read_matches")
.to_str()
.unwrap()
.into(),
)
.root()
.owned()
.await?;
// node_modules shouldn't be matched by Dynamic here let dynamic = read_matches(
assert_eq!(
vec!["index.js", "sub", "sub/", "sub/foo-a.js", "sub/foo-b.js"],
read_matches(
root.clone(), root.clone(),
rcstr!(""), rcstr!(""),
false, false,
...@@ -2679,14 +2686,10 @@ mod tests { ...@@ -2679,14 +2686,10 @@ mod tests {
) )
.await? .await?
.into_iter() .into_iter()
.map(|m| m.name()) .map(|m| m.name().to_string())
.collect::<Vec<_>>() .collect::<Vec<_>>();
);
// basic dynamic file suffix let dynamic_file_suffix = read_matches(
assert_eq!(
vec!["sub/foo-a.js", "sub/foo-b.js"],
read_matches(
root.clone(), root.clone(),
rcstr!(""), rcstr!(""),
false, false,
...@@ -2697,27 +2700,47 @@ mod tests { ...@@ -2697,27 +2700,47 @@ mod tests {
) )
.await? .await?
.into_iter() .into_iter()
.map(|m| m.name()) .map(|m| m.name().to_string())
.collect::<Vec<_>>() .collect::<Vec<_>>();
);
// read_matches "node_modules/<dynamic>" should not return anything inside. We never let node_modules_dynamic = read_matches(
// want to enumerate the list of packages here. root,
assert_eq!(
vec!["node_modules"] as Vec<&str>,
read_matches(
root.clone(),
rcstr!(""), rcstr!(""),
false, false,
Pattern::new(Pattern::Constant(rcstr!("node_modules")).or_any_nested_file()), Pattern::new(Pattern::Constant(rcstr!("node_modules")).or_any_nested_file()),
) )
.await? .await?
.into_iter() .into_iter()
.map(|m| m.name()) .map(|m| m.name().to_string())
.collect::<Vec<_>>() .collect::<Vec<_>>();
Ok(ReadMatchesOutput {
dynamic,
dynamic_file_suffix,
node_modules_dynamic,
}
.cell())
}
let matches = read_matches_operation().read_strongly_consistent().await?;
// node_modules shouldn't be matched by Dynamic here
assert_eq!(
matches.dynamic,
&["index.js", "sub", "sub/", "sub/foo-a.js", "sub/foo-b.js"]
); );
anyhow::Ok(()) // basic dynamic file suffix
assert_eq!(
matches.dynamic_file_suffix,
&["sub/foo-a.js", "sub/foo-b.js"]
);
// read_matches "node_modules/<dynamic>" should not return anything inside. We never
// want to enumerate the list of packages here.
assert_eq!(matches.node_modules_dynamic, &["node_modules"]);
Ok(())
}) })
.await .await
.unwrap(); .unwrap();
......
...@@ -35,7 +35,7 @@ pub async fn node_file_trace( ...@@ -35,7 +35,7 @@ pub async fn node_file_trace(
max_depth: Option<usize>, max_depth: Option<usize>,
) -> Result<()> { ) -> Result<()> {
let op = node_file_trace_operation(project_root.clone(), input.clone(), graph, max_depth); let op = node_file_trace_operation(project_root.clone(), input.clone(), graph, max_depth);
let result = op.resolve_strongly_consistent().await?; let result = op.read_strongly_consistent().await?;
if show_issues { if show_issues {
let issue_reporter: Vc<Box<dyn IssueReporter>> = let issue_reporter: Vc<Box<dyn IssueReporter>> =
...@@ -51,7 +51,7 @@ pub async fn node_file_trace( ...@@ -51,7 +51,7 @@ pub async fn node_file_trace(
} }
println!("FILELIST:"); println!("FILELIST:");
for a in result.await? { for a in result {
println!("{a}"); println!("{a}");
} }
......
...@@ -31,7 +31,7 @@ use turbo_tasks::{ ...@@ -31,7 +31,7 @@ use turbo_tasks::{
ResolvedVc, TurboTasks, ValueToString, Vc, apply_effects, backend::Backend, trace::TraceRawVcs, ResolvedVc, TurboTasks, ValueToString, Vc, apply_effects, backend::Backend, trace::TraceRawVcs,
}; };
use turbo_tasks_backend::TurboTasksBackend; use turbo_tasks_backend::TurboTasksBackend;
use turbo_tasks_fs::{DiskFileSystem, FileSystem}; use turbo_tasks_fs::{DiskFileSystem, FileSystem, FileSystemPath};
use turbopack::{ use turbopack::{
ModuleAssetContext, emit_assets_into_dir_operation, ModuleAssetContext, emit_assets_into_dir_operation,
module_options::{ module_options::{
...@@ -469,10 +469,7 @@ fn node_file_trace<B: Backend + 'static>( ...@@ -469,10 +469,7 @@ fn node_file_trace<B: Backend + 'static>(
let input = input.clone(); let input = input.clone();
let directory = directory.clone(); let directory = directory.clone();
let task = async move { let task = async move {
#[allow(unused)]
let bench_suites = bench_suites.clone();
let before_start = Instant::now(); let before_start = Instant::now();
let rebased = node_file_trace_operation( let rebased = node_file_trace_operation(
package_root.clone(), package_root.clone(),
input.clone(), input.clone(),
...@@ -480,11 +477,13 @@ fn node_file_trace<B: Backend + 'static>( ...@@ -480,11 +477,13 @@ fn node_file_trace<B: Backend + 'static>(
) )
.resolve_strongly_consistent() .resolve_strongly_consistent()
.await?; .await?;
let duration = before_start.elapsed();
print_graph(ResolvedVc::upcast(rebased)).await?; print_graph_operation(ResolvedVc::upcast(rebased))
.read_strongly_consistent()
.await?;
if cfg!(feature = "bench_against_node_nft") { if cfg!(feature = "bench_against_node_nft") {
let duration = before_start.elapsed();
let node_start = Instant::now(); let node_start = Instant::now();
exec_node(&package_root, &input).await?; exec_node(&package_root, &input).await?;
let node_duration = node_start.elapsed(); let node_duration = node_start.elapsed();
...@@ -517,7 +516,10 @@ fn node_file_trace<B: Backend + 'static>( ...@@ -517,7 +516,10 @@ fn node_file_trace<B: Backend + 'static>(
stderr: String::new(), stderr: String::new(),
}) })
} else { } else {
let output_path = &rebased.path().await?.path; let output_path = &asset_path_operation(ResolvedVc::upcast(rebased))
.read_strongly_consistent()
.await?
.path;
let original_output = let original_output =
exec_node(&package_root, &format!("{package_root}/tests/{input}")).await?; exec_node(&package_root, &format!("{package_root}/tests/{input}")).await?;
let output = exec_node(&directory, output_path).await?; let output = exec_node(&directory, output_path).await?;
...@@ -747,7 +749,13 @@ impl std::str::FromStr for CaseInput { ...@@ -747,7 +749,13 @@ impl std::str::FromStr for CaseInput {
} }
} }
async fn print_graph(asset: ResolvedVc<Box<dyn OutputAsset>>) -> Result<()> { #[turbo_tasks::function(operation)]
async fn asset_path_operation(asset: ResolvedVc<Box<dyn OutputAsset>>) -> Vc<FileSystemPath> {
asset.path()
}
#[turbo_tasks::function(operation)]
async fn print_graph_operation(asset: ResolvedVc<Box<dyn OutputAsset>>) -> Result<()> {
let mut visited = HashSet::new(); let mut visited = HashSet::new();
let mut queue = Vec::new(); let mut queue = Vec::new();
queue.push((0, asset)); queue.push((0, asset));
......
...@@ -477,13 +477,13 @@ pub mod tests { ...@@ -477,13 +477,13 @@ pub mod tests {
BackendOptions::default(), BackendOptions::default(),
noop_backing_storage(), noop_backing_storage(),
)); ));
tt.run_once(async { run_leaves_test().await }) tt.run_once(async { run_leaves_test_operation().read_strongly_consistent().await })
.await .await
.unwrap(); .unwrap();
} }
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
pub async fn run_leaves_test() -> Result<()> { pub async fn run_leaves_test_operation() -> Result<()> {
let fs = VirtualFileSystem::new(); let fs = VirtualFileSystem::new();
let virtual_path = fs.root().await?.join("foo.js")?; let virtual_path = fs.root().await?.join("foo.js")?;
let virtual_source = Vc::upcast::<Box<dyn Source>>(VirtualSource::new( let virtual_source = Vc::upcast::<Box<dyn Source>>(VirtualSource::new(
...@@ -610,13 +610,17 @@ pub mod tests { ...@@ -610,13 +610,17 @@ pub mod tests {
BackendOptions::default(), BackendOptions::default(),
noop_backing_storage(), noop_backing_storage(),
)); ));
tt.run_once(async { run_rule_condition_tree_test().await }) tt.run_once(async {
.await run_rule_condition_tree_test_operation()
.unwrap(); .read_strongly_consistent()
.await
})
.await
.unwrap();
} }
#[turbo_tasks::function] #[turbo_tasks::function(operation)]
pub async fn run_rule_condition_tree_test() -> Result<()> { pub async fn run_rule_condition_tree_test_operation() -> Result<()> {
let fs = VirtualFileSystem::new(); let fs = VirtualFileSystem::new();
let virtual_path = fs.root().await?.join("foo.js")?; let virtual_path = fs.root().await?.join("foo.js")?;
let virtual_source = Vc::upcast::<Box<dyn Source>>(VirtualSource::new( let virtual_source = Vc::upcast::<Box<dyn Source>>(VirtualSource::new(
......
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