Files
next.js/turbopack/crates/turbopack-analyze/tests/split_chunk.rs
Benjamin WoodruffandGitHub 89f3649a00 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.
2026-02-26 16:14:30 -08:00

161 lines
4.8 KiB
Rust

#![feature(arbitrary_self_types_pointers)]
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
#![cfg(test)]
use anyhow::Result;
use serde_json::json;
use turbo_rcstr::rcstr;
use turbo_tasks::{OperationVc, ResolvedVc, Vc};
use turbo_tasks_fs::{
File, FileContent, FileSystem, FileSystemPath, VirtualFileSystem, rope::Rope,
};
use turbo_tasks_testing::{Registration, register, run_once};
use turbopack_analyze::split_chunk::{ChunkPartRange, ChunkParts, split_output_asset_into_parts};
use turbopack_core::{
asset::{Asset, AssetContent},
code_builder::{Code, CodeBuilder},
output::{OutputAsset, OutputAssetsReference},
source_map::GenerateSourceMap,
};
static REGISTRATION: Registration = register!();
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn split_chunk() {
run_once(&REGISTRATION, || async {
let mut code = CodeBuilder::new(true, false);
code += "Hello world!\n";
code += "This is a test file.\n";
code.push_source(
&Rope::from("Hello world!\n123"),
Some(Rope::from(serde_json::to_string_pretty(&json! ({
"version": 3,
"mappings": "AAAA;AACA",
"sources": ["source1.js"],
"names": [],
"sourcesContent": ["console.log('Hello world!');"]
}))?)),
);
code += "This is the middle of the file.\n";
code.push_source(
&Rope::from("This is the middle of the file.\n"),
Some(Rope::from(serde_json::to_string_pretty(&json! ({
"version": 3,
"mappings": "AAAA",
"sources": ["source2.js"],
"names": [],
"sourcesContent": ["console.log('Middle of file');"]
}))?)),
);
code += "This is the end of the file.\n";
let code = code.build();
let asset = TestAsset {
code: code.resolved_cell(),
}
.resolved_cell();
#[turbo_tasks::function(operation)]
fn split_parts_operation(asset: ResolvedVc<TestAsset>) -> Vc<ChunkParts> {
split_output_asset_into_parts(Vc::upcast(*asset))
}
let parts_op = split_parts_operation(asset);
let parts = parts_op.read_strongly_consistent().await?;
assert_eq!(parts.len(), 2);
assert_eq!(parts[0].source, rcstr!("source1.js"));
assert_eq!(parts[0].real_size, 46);
assert_eq!(parts[0].unaccounted_size, 34);
assert_eq!(
parts[0].ranges,
vec![
ChunkPartRange {
line: 2,
start_column: 0,
end_column: 12
},
ChunkPartRange {
line: 3,
start_column: 0,
end_column: 34
},
]
);
assert_eq!(parts[1].source, rcstr!("source2.js"));
assert_eq!(parts[1].real_size, 31);
assert_eq!(parts[1].unaccounted_size, 30);
assert_eq!(
parts[1].ranges,
vec![ChunkPartRange {
line: 4,
start_column: 0,
end_column: 31
}]
);
#[turbo_tasks::function(operation)]
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);
anyhow::Ok(())
})
.await
.unwrap()
}
#[turbo_tasks::value]
struct TestAsset {
code: ResolvedVc<Code>,
}
#[turbo_tasks::value_impl]
impl OutputAssetsReference for TestAsset {}
#[turbo_tasks::value_impl]
impl OutputAsset for TestAsset {
#[turbo_tasks::function]
async fn path(&self) -> Result<Vc<FileSystemPath>> {
Ok(VirtualFileSystem::new()
.root()
.await?
.join("test.js")?
.cell())
}
}
#[turbo_tasks::value_impl]
impl Asset for TestAsset {
#[turbo_tasks::function]
async fn content(&self) -> Result<Vc<AssetContent>> {
Ok(AssetContent::file(
FileContent::Content(File::from(self.code.await?.source_code().clone())).cell(),
))
}
}
#[turbo_tasks::value_impl]
impl GenerateSourceMap for TestAsset {
#[turbo_tasks::function]
pub fn generate_source_map(&self) -> Vc<FileContent> {
self.code.generate_source_map()
}
}