Unverified Commit 723c0620 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

switch our test benchmark runs to release-with-assertions (#94538)

In ci when testing our benchmarks use our test profile
`release-with-assertions`

This avoids an expensive `lto` step and ensures that our tests run with
debug asserts.

I noticed that our workflow for 'test cargo benches' was very slow and a
lot of that time was the build presumably due to lto overheads across so
many benchmark binaries.


Compare:

* cargo benches for this pr:
https://github.com/vercel/next.js/runs/79974366863?pr=94538
   - build=4m42s
   - test=1m46s
* cargo benches before this pr:
https://github.com/vercel/next.js/actions/runs/27097792020/job/79973082715#logs
   - build=8m23s
   - test=6m56s

Of course doing this revealed a few things

* a birthday paradox panic in one of the persistence tests
* some 'top level read' errors to address in the benchmarks and in the
turbopack-cli server used for some benchmarks.

And finally, that the persistence tests are just extremely slow in test
mode due to their initialization overhead (populating >1GB dbs), so that
harness is rewritten to remove some variants and also to reduce max
sizes in test mode
parent d11f61b1
......@@ -57,21 +57,21 @@ jobs:
- name: Build benchmarks for tests
timeout-minutes: 120
run: |
cargo test --benches --workspace --release --no-fail-fast --exclude turbopack-bench --exclude next-napi-bindings --no-run
cargo test --benches --workspace --profile=release-with-assertions --no-fail-fast --exclude turbopack-bench --exclude next-napi-bindings --no-run
- name: Run cargo test on benchmarks
timeout-minutes: 120
run: |
cargo test --benches --workspace --release --no-fail-fast --exclude turbopack-bench --exclude next-napi-bindings
cargo test --benches --workspace --profile=release-with-assertions --no-fail-fast --exclude turbopack-bench --exclude next-napi-bindings
- name: Build benchmarks for tests for other bundlers
if: inputs.all
timeout-minutes: 120
run: |
cargo test --benches --release -p turbopack-bench --no-run
cargo test --benches --profile=release-with-assertions -p turbopack-bench --no-run
- name: Run cargo test on benchmarks for other bundlers
if: inputs.all
timeout-minutes: 120
run: |
cargo test --benches --release -p turbopack-bench
cargo test --benches --profile=release-with-assertions -p turbopack-bench
......@@ -10456,6 +10456,7 @@ name = "turbopack-cli-utils"
version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"crossterm 0.26.1",
"owo-colors",
"rustc-hash 2.1.1",
......
......@@ -24,11 +24,31 @@ static ALLOC: TurboMalloc = TurboMalloc;
// =============================================================================
const MB: u64 = 1024 * 1024;
/// Data amount for batch read benchmarks (1 GiB)
const BATCH_READ_DATA_AMOUNT: usize = 1024 * MB as usize;
/// Data amount for batch read benchmarks (128 MiB).
const BATCH_READ_DATA_AMOUNT: usize = 128 * MB as usize;
/// Maximum memory to use for storing keys during prefill (4 GiB)
const MAX_KEY_MEMORY: usize = 4 * 1024 * MB as usize;
/// Entry-count cap applied to prefill/setup work unless `LARGE_DB` is set, so the default
/// `cargo bench` / `cargo test --benches` run stays fast.
const SCALED_MAX_ENTRIES: usize = 100 * 1024;
/// True when the `LARGE_DB` env var is set, unlocking the full (large) benchmark sizes.
/// Defaults to false so both `cargo bench` and `cargo test --benches` run scaled-down; set
/// `LARGE_DB=1` for a real benchmarking run.
static LARGE_DB: LazyLock<bool> = LazyLock::new(|| std::env::var_os("LARGE_DB").is_some());
/// Cap an entry count to [`SCALED_MAX_ENTRIES`] unless `LARGE_DB` is set; otherwise return it
/// unchanged. Used only to bound prefill/setup work — benchmark `id` strings keep using the
/// configured (unscaled) sizes so real-run reports are unaffected.
fn scaled(full: usize) -> usize {
if *LARGE_DB {
full
} else {
full.min(SCALED_MAX_ENTRIES)
}
}
// =============================================================================
// Helper Types and Functions
// =============================================================================
......@@ -90,6 +110,21 @@ fn random_key(rng: &mut SmallRng, size: usize) -> Box<[u8]> {
)
}
/// Generate `count` distinct keys of `size` bytes each, in random order.
fn unique_keys(rng: &mut SmallRng, size: usize, count: usize) -> Vec<Box<[u8]>> {
let mut counters: Vec<u64> = (0..count as u64).collect();
counters.shuffle(rng);
let counter_len = size.min(size_of::<u64>());
counters
.into_iter()
.map(|counter| {
let mut data = random_key(rng, size);
data[..counter_len].copy_from_slice(&counter.to_le_bytes()[..counter_len]);
data
})
.collect()
}
/// Generate a random value of the specified size
fn random_value(rng: &mut SmallRng, size: usize) -> Box<[u8]> {
random_data(
......@@ -104,32 +139,32 @@ fn random_value(rng: &mut SmallRng, size: usize) -> Box<[u8]> {
fn prefill_database(path: &Path, config: &DbConfig) -> Result<Vec<Box<[u8]>>> {
let db = TurboPersistence::<SerialScheduler, 1>::open(path.to_path_buf())?;
let mut rng = SmallRng::seed_from_u64(42);
// Bound prefill work unless `LARGE_DB` is set; `LARGE_DB` runs use the full count.
let entry_count = scaled(config.entry_count);
let mut keys = Vec::with_capacity(
config
.entry_count
.min(MAX_KEY_MEMORY / (config.key_size + size_of::<Box<[u8]>>())),
entry_count.min(MAX_KEY_MEMORY / (config.key_size + size_of::<Box<[u8]>>())),
);
let all_keys = unique_keys(&mut rng, config.key_size, entry_count);
let entries_per_commit = config.entry_count / config.commit_count;
let entries_per_commit = entry_count / config.commit_count;
for commit_idx in 0..config.commit_count {
let batch = db.write_batch()?;
let start = commit_idx * entries_per_commit;
let end = if commit_idx == config.commit_count - 1 {
config.entry_count
entry_count
} else {
start + entries_per_commit
};
for _ in start..end {
let key = random_key(&mut rng, config.key_size);
for key in &all_keys[start..end] {
let value = random_value(&mut rng, config.value_size);
batch.put(0, key.clone(), value.into())?;
if keys.len() < keys.capacity() {
keys.push(key);
keys.push(key.clone());
} else {
let replace = rng.random_range(0..keys.len());
keys[replace] = key;
keys[replace] = key.clone();
}
}
db.commit_write_batch(batch)?;
......@@ -151,7 +186,8 @@ fn prefill_database(path: &Path, config: &DbConfig) -> Result<Vec<Box<[u8]>>> {
fn setup_prefilled_db(config: &DbConfig, id: &str) -> Result<(TempDir, Vec<Box<[u8]>>)> {
let tempdir = tempfile::tempdir()?;
let keys = prefill_database(tempdir.path(), config)?;
// Measure disk usage of the database and print it for informational purposes
// Measure disk usage of the database and print it for informational purposes.
let entry_count = scaled(config.entry_count);
let db_size = tempdir
.path()
.read_dir()?
......@@ -162,8 +198,8 @@ fn setup_prefilled_db(config: &DbConfig, id: &str) -> Result<(TempDir, Vec<Box<[
println!(
"\n{id} db size: {}B = {}B per item = {}% of original size",
format_number(db_size as usize),
format_number(db_size as usize / config.entry_count),
(db_size as usize * 100 / (config.entry_count * (config.key_size + config.value_size)))
format_number(db_size as usize / entry_count),
(db_size as usize * 100 / (entry_count * (config.key_size + config.value_size)))
);
Ok((tempdir, keys))
}
......@@ -245,13 +281,14 @@ fn bench_write(c: &mut Criterion) {
for &(key_size, value_size) in &entry_sizes {
for &database_size in &database_sizes {
let entry_count = database_size / (key_size + value_size);
let full_entry_count = database_size / (key_size + value_size);
let entry_count = scaled(full_entry_count);
let id = format!(
"key_{}/value_{}/entries_{}",
format_number(key_size),
format_number(value_size),
format_number(entry_count)
format_number(full_entry_count)
);
group.bench_function(&id, |b| {
b.iter_batched(
......@@ -259,8 +296,18 @@ fn bench_write(c: &mut Criterion) {
// Setup: create temp directory and RNG
let tempdir = tempfile::tempdir().unwrap();
let mut rng = SmallRng::seed_from_u64(42);
let mut random_data = vec![0u8; entry_count * (key_size + value_size)];
let entry_size = key_size + value_size;
let mut random_data = vec![0u8; entry_count * entry_size];
rng.fill(&mut random_data[..]);
// SingleValue families forbid duplicate keys, so overwrite each key region
// with a distinct, shuffled key (see `unique_keys`).
for (i, key) in unique_keys(&mut rng, key_size, entry_count)
.iter()
.enumerate()
{
let key_start = i * entry_size;
random_data[key_start..key_start + key_size].copy_from_slice(key);
}
(tempdir, random_data)
},
......@@ -319,14 +366,11 @@ fn bench_read_get(c: &mut Criterion) {
// Configuration parameters: (key_size, value_size)
let entry_sizes = [(8, 4), (4, 32 * 1024), (32 * 1024, 4)];
// Configuration parameters: (entry_count, commit_count, compacted)
// Configuration parameters: (database_size, commit_count, compacted)
let size_commits_compacted = [
(128 * 1024 * 1024, 1, true),
(128 * 1024 * 1024, 1, false),
(128 * 1024 * 1024, 20, false),
(1024 * 1024 * 1024, 1, true),
(1024 * 1024 * 1024, 1, false),
(1024 * 1024 * 1024, 20, false),
];
for &(key_size, value_size) in &entry_sizes {
......@@ -584,21 +628,21 @@ fn prefill_multi_value_database(
TurboPersistence::<SerialScheduler, 1>::open_with_config(path.to_path_buf(), db_config)?;
let mut rng = SmallRng::seed_from_u64(42);
// Generate all distinct keys up front
let max_stored_keys = config
.distinct_key_count
.min(MAX_KEY_MEMORY / (config.key_size + size_of::<Box<[u8]>>()));
let mut keys: Vec<Box<[u8]>> = (0..max_stored_keys)
.map(|_| random_key(&mut rng, config.key_size))
.collect();
let entry_count = scaled(config.entry_count);
let distinct_key_count = scaled(config.distinct_key_count);
// Generate all distinct keys up front.
let max_stored_keys =
distinct_key_count.min(MAX_KEY_MEMORY / (config.key_size + size_of::<Box<[u8]>>()));
let mut keys = unique_keys(&mut rng, config.key_size, max_stored_keys);
let entries_per_commit = config.entry_count / config.commit_count;
let entries_per_commit = entry_count / config.commit_count;
for commit_idx in 0..config.commit_count {
let batch = db.write_batch()?;
let start = commit_idx * entries_per_commit;
let end = if commit_idx == config.commit_count - 1 {
config.entry_count
entry_count
} else {
start + entries_per_commit
};
......@@ -630,6 +674,7 @@ fn setup_prefilled_multi_value_db(
) -> Result<(TempDir, Vec<Box<[u8]>>)> {
let tempdir = tempfile::tempdir()?;
let keys = prefill_multi_value_database(tempdir.path(), config)?;
let entry_count = scaled(config.entry_count);
let db_size = tempdir
.path()
.read_dir()?
......@@ -640,8 +685,8 @@ fn setup_prefilled_multi_value_db(
println!(
"\n{id} db size: {}B = {}B per item = {}% of original size",
format_number(db_size as usize),
format_number(db_size as usize / config.entry_count),
(db_size as usize * 100 / (config.entry_count * (config.key_size + config.value_size)))
format_number(db_size as usize / entry_count),
(db_size as usize * 100 / (entry_count * (config.key_size + config.value_size)))
);
Ok((tempdir, keys))
}
......@@ -890,14 +935,17 @@ fn bench_write_multi_value(c: &mut Criterion) {
for &(key_size, value_size) in &entry_sizes {
for &(database_size, values_per_key) in configs {
let entry_count = database_size / (key_size + value_size);
let distinct_key_count = entry_count / values_per_key;
// `id` uses the configured size so real-run reports are unaffected; the scaled
// counts bound the actual work unless `LARGE_DB` is set.
let full_entry_count = database_size / (key_size + value_size);
let entry_count = scaled(full_entry_count);
let distinct_key_count = (entry_count / values_per_key).max(1);
let id = format!(
"key_{}/value_{}/entries_{}/vpk_{}",
format_number(key_size),
format_number(value_size),
format_number(entry_count),
format_number(full_entry_count),
values_per_key,
);
group.bench_function(&id, |b| {
......@@ -905,10 +953,8 @@ fn bench_write_multi_value(c: &mut Criterion) {
|| {
let tempdir = tempfile::tempdir().unwrap();
let mut rng = SmallRng::seed_from_u64(42);
// Generate distinct keys
let keys: Vec<Box<[u8]>> = (0..distinct_key_count)
.map(|_| random_key(&mut rng, key_size))
.collect();
// Generate distinct (unique) keys to keep the true distinct count exact.
let keys = unique_keys(&mut rng, key_size, distinct_key_count);
let mut random_data = vec![0u8; entry_count * value_size];
rng.fill(&mut random_data[..]);
(tempdir, keys, random_data)
......
......@@ -16,6 +16,7 @@ workspace = true
[dependencies]
anyhow = { workspace = true }
async-trait = { workspace = true }
crossterm = "0.26.0"
owo-colors = { workspace = true }
rustc-hash = { workspace = true }
......
......@@ -8,15 +8,16 @@ use std::{
};
use anyhow::Result;
use async_trait::async_trait;
use crossterm::style::{StyledContent, Stylize};
use owo_colors::{OwoColorize as _, Style};
use rustc_hash::{FxHashMap, FxHashSet};
use turbo_rcstr::RcStr;
use turbo_tasks::{RawVc, TransientInstance, TransientValue, Vc};
use turbo_tasks::{RawVc, ReadRef, TransientInstance, Vc};
use turbo_tasks_fs::{FileLinesContent, source_context::get_source_context};
use turbopack_core::issue::{
CollectibleIssuesExt, IssueFilter, IssueReporter, IssueSeverity, PlainIssue, PlainIssueSource,
PlainTraceItem, StyledString,
IssueReporter, IssueSeverity, PlainIssue, PlainIssueSource, PlainIssues, PlainTraceItem,
StyledString,
};
use crate::source_context::format_source_context_lines;
......@@ -366,7 +367,7 @@ impl PartialEq for ConsoleUi {
#[turbo_tasks::value_impl]
impl ConsoleUi {
#[turbo_tasks::function]
#[turbo_tasks::function(root)]
pub fn new(options: TransientInstance<LogOptions>) -> Vc<Self> {
ConsoleUi {
options: (*options).clone(),
......@@ -376,15 +377,15 @@ impl ConsoleUi {
}
}
#[async_trait]
#[turbo_tasks::value_impl]
impl IssueReporter for ConsoleUi {
#[turbo_tasks::function]
async fn report_issues(
&self,
source: TransientValue<RawVc>,
issues: ReadRef<PlainIssues>,
source: RawVc,
min_failing_severity: IssueSeverity,
) -> Result<Vc<bool>> {
let issues = source.peek_issues();
) -> Result<bool> {
let LogOptions {
ref current_dir,
ref project_dir,
......@@ -395,7 +396,7 @@ impl IssueReporter for ConsoleUi {
} = self.options;
let mut grouped_issues: GroupedIssues = FxHashMap::default();
let plain_issues = issues.get_plain_issues(&IssueFilter::everything()).await?;
let plain_issues = &issues.0;
let issues = plain_issues
.iter()
.map(|plain_issue| {
......@@ -405,11 +406,7 @@ impl IssueReporter for ConsoleUi {
.collect::<Vec<_>>();
let issue_ids = issues.iter().map(|(_, id)| *id).collect::<FxHashSet<_>>();
let mut new_ids = self
.seen
.lock()
.unwrap()
.new_ids(source.into_value(), issue_ids);
let mut new_ids = self.seen.lock().unwrap().new_ids(source, issue_ids);
let mut has_fatal = false;
for (plain_issue, id) in issues {
......@@ -539,7 +536,7 @@ impl IssueReporter for ConsoleUi {
}
}
Ok(Vc::cell(has_fatal))
Ok(has_fatal)
}
}
......
......@@ -16,9 +16,9 @@ use serde::{Deserialize, Serialize};
use turbo_esregex::EsRegex;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
CollectiblesSource, NonLocalValue, OperationVc, RawVc, ReadRef, ResolvedVc, TransientValue,
TryFlatJoinIterExt, TryJoinIterExt, Upcast, ValueDefault, ValueToString, ValueToStringRef, Vc,
emit, trace::TraceRawVcs,
CollectiblesSource, NonLocalValue, OperationVc, RawVc, ReadRef, ResolvedVc, TryFlatJoinIterExt,
TryJoinIterExt, Upcast, ValueDefault, ValueToString, ValueToStringRef, Vc, emit,
trace::TraceRawVcs,
};
use turbo_tasks_fs::{
FileContent, FileLine, FileLinesContent, FileSystem, FileSystemPath, glob::Glob,
......@@ -904,6 +904,14 @@ pub struct PlainIssue {
pub import_traces: Vec<PlainTrace>,
}
/// A collection of [`PlainIssue`]s collected from a single source.
///
/// Returned by [`collect_issues`] so that the (plain) issues can be read strongly
/// consistently from a top-level task and handed to a non-turbo-task [`IssueReporter`].
#[turbo_tasks::value(serialization = "skip")]
#[derive(Debug)]
pub struct PlainIssues(pub Vec<ReadRef<PlainIssue>>);
#[turbo_tasks::value(serialization = "skip")]
#[derive(Clone, Debug, PartialOrd, Ord)]
pub struct PlainAdditionalIssueSource {
......@@ -1062,24 +1070,30 @@ impl PlainSource {
}
}
#[async_trait]
#[turbo_tasks::value_trait]
pub trait IssueReporter {
/// Reports issues to the user (e.g. to stdio). Returns whether fatal
/// Reports already-collected issues to the user (e.g. to stdio). Returns whether fatal
/// (program-ending) issues were present.
///
/// This is intentionally *not* a `#[turbo_tasks::function]`: it performs no turbo-tasks
/// reads of its own (the issues are collected ahead of time by [`collect_issues`]), so it
/// is safe to call from a top-level task.
///
/// # Arguments:
///
/// * `source` - The root [Vc] from which issues are traced. Can be used by implementers to
/// determine which issues are new. This must be derived from the OperationVc so issues can
/// be collected.
/// * `min_failing_severity` - The minimum Vc<[IssueSeverity]>
/// The minimum issue severity level considered to fatally end the program.
#[turbo_tasks::function]
fn report_issues(
self: Vc<Self>,
source: TransientValue<RawVc>,
/// * `issues` - The plain issues already collected from the source.
/// * `source` - The root [`RawVc`] from which the issues were traced. Can be used by
/// implementers as a dedup key to determine which issues are new. This must be derived from
/// the `OperationVc` the issues were collected from.
/// * `min_failing_severity` - The minimum issue severity level considered to fatally end the
/// program.
async fn report_issues(
&self,
issues: ReadRef<PlainIssues>,
source: RawVc,
min_failing_severity: IssueSeverity,
) -> Vc<bool>;
) -> Result<bool>;
}
pub trait CollectibleIssuesExt
......@@ -1117,6 +1131,21 @@ where
}
}
/// Collects all issues emitted by `source` as resolved [`PlainIssue`]s.
///
/// This is an `operation` function so its (plain) result can be read *strongly consistently* (via
/// [`OperationVc::read_strongly_consistent`]) from a top-level task without tripping the
/// eventually-consistent-read assertion. The per-issue `PlainIssue::from_issue` reads happen
/// *inside* this task, where eventually-consistent reads are legal.
#[turbo_tasks::function(operation, root)]
async fn collect_issues(source: OperationVc<()>) -> Result<Vc<PlainIssues>> {
let plain = source
.peek_issues()
.get_plain_issues(&IssueFilter::everything())
.await?;
Ok(PlainIssues(plain).cell())
}
/// A helper function to print out issues to the console.
///
/// Must be called in a turbo-task as this constructs a `cell`
......@@ -1129,13 +1158,31 @@ pub async fn handle_issues<T: Send>(
) -> Result<()> {
let source_vc = source_op.connect();
let _ = source_op.resolve().strongly_consistent().await?;
let source_raw = Vc::into_raw(source_vc);
// Collect the issues in a dedicated `operation` task and read its *plain* result strongly
// consistently. This is safe at the top level (unlike an eventually-consistent read), while
// the per-issue reads happen inside `collect_issues`. The source is type-erased to
// `OperationVc<()>` so a single non-generic task can collect issues for any source.
let erased_source = OperationVc::<()>::try_from(source_raw)?;
let issues = collect_issues(erased_source)
.read_strongly_consistent()
.await?;
let has_fatal = issue_reporter.report_issues(
TransientValue::new(Vc::into_raw(source_vc)),
min_failing_severity,
);
// `report_issues` is a plain async method; reach it via a `TraitRef`. Resolve the reporter
// strongly consistently first so that `into_trait_ref` is a plain cell read (rather than an
// eventually-consistent task-output read) at the top level.
let reporter = issue_reporter
.to_resolved()
.strongly_consistent()
.await?
.into_trait_ref()
.await?;
let has_fatal = reporter
.report_issues(issues, source_raw, min_failing_severity)
.await?;
if *has_fatal.await? {
if has_fatal {
let mut message = "Fatal issue(s) occurred".to_owned();
if let Some(path) = path.as_ref() {
message += &format!(" in {path}");
......
......@@ -30,8 +30,8 @@ use socket2::{Domain, Protocol, Socket, Type};
use tokio::task::JoinHandle;
use tracing::{Instrument, Level, Span, event, info_span};
use turbo_tasks::{
Effects, NonLocalValue, OperationVc, PrettyPrintError, TurboTasksApi, Vc,
read_strongly_consistent_and_apply_effects, run_once_with_reason, take_effects,
Completion, Effects, NonLocalValue, OperationVc, PrettyPrintError, ResolvedVc, TurboTasksApi,
Vc, read_strongly_consistent_and_apply_effects, run_once_with_reason, take_effects,
trace::TraceRawVcs, util::FormatDuration,
};
use turbopack_core::issue::{IssueReporter, IssueSeverity, handle_issues};
......@@ -71,6 +71,19 @@ async fn get_source_with_issues_operation(
Ok(ContentSourceWithIssues { source_op, effects }.cell())
}
/// Applies all collected [`ContentSourceSideEffect`]s. The individual `apply()` reads happen
/// *inside* this task (where eventually-consistent reads are legal); the caller reads the result
/// strongly consistently so the work is finished before the response is observed.
#[turbo_tasks::function(operation, root)]
async fn apply_side_effects_operation(
side_effects: Vec<ResolvedVc<Box<dyn ContentSourceSideEffect>>>,
) -> Result<Vc<Completion>> {
for side_effect in &side_effects {
side_effect.apply().await?;
}
Ok(Completion::new())
}
#[derive(TraceRawVcs, Debug, NonLocalValue)]
pub struct DevServerBuilder {
#[turbo_tasks(trace_ignore)]
......@@ -266,13 +279,17 @@ impl DevServerBuilder {
);
}
if !side_effects.is_empty() {
let side_effects: Vec<_> = side_effects.into_iter().collect();
let join_handle = tokio::spawn(run_once_with_reason(
tt.clone(),
side_effects_reason,
async move {
for side_effect in side_effects {
side_effect.apply().await?;
}
// Apply the side effects inside a dedicated `operation`
// task and read its result strongly consistently, so this
// top-level task performs no eventually-consistent read.
apply_side_effects_operation(side_effects)
.read_strongly_consistent()
.await?;
Ok(())
},
));
......
......@@ -111,6 +111,22 @@ fn versioned_content_update_operation(
content.update(*from)
}
/// Computes the initial [`Version`] for an update stream from a resolved source request. Runs as
/// an `operation` so [`UpdateStream::new`] can read it strongly consistently from its top-level
/// task without performing an eventually-consistent read.
#[turbo_tasks::function(operation, root)]
async fn initial_version_operation(
content: OperationVc<ResolveSourceRequestResult>,
) -> Result<Vc<Box<dyn Version>>> {
Ok(match *content.read_strongly_consistent().await? {
ResolveSourceRequestResult::Static(static_content, _) => {
static_content.await?.content.version()
}
ResolveSourceRequestResult::HttpProxy(proxy_result) => Vc::upcast(proxy_result.connect()),
_ => Vc::upcast(NotFoundVersion::new()),
})
}
#[turbo_tasks::function(operation, root)]
async fn get_update_stream_item_operation(
resource: RcStr,
......@@ -277,17 +293,13 @@ impl UpdateStream {
let content = get_content.call();
// We can ignore issues reported in content here since [compute_update_stream]
// will handle them
let version = match *content.connect().await? {
ResolveSourceRequestResult::Static(static_content, _) => {
static_content.await?.content.version()
}
ResolveSourceRequestResult::HttpProxy(proxy_result) => {
Vc::upcast(proxy_result.connect())
}
_ => Vc::upcast(NotFoundVersion::new()),
};
let version_state = VersionState::new(version.into_trait_ref().await?).await?;
// will handle them. This runs in a top-level task (`UpdateServer::run`'s
// `start_once_process`), so the initial version is computed in a dedicated `operation`
// task (where the per-content reads are legal) and read strongly consistently.
let version = initial_version_operation(content)
.read_trait_strongly_consistent()
.await?;
let version_state = VersionState::new(version).await?;
let _ = compute_update_stream(
resource,
......
......@@ -15,7 +15,9 @@ use swc_core::{
visit::VisitMutWith,
},
};
use turbo_tasks::{ResolvedVc, TurboTasks};
use turbo_tasks::{
ResolvedVc, TurboTasks, unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbopack_core::{
compile_time_info::CompileTimeInfo,
......@@ -142,6 +144,10 @@ fn bench_link(b: &mut Bencher, input: &BenchInput) {
let var_graph = var_graph.clone();
async move {
tt.run_once(async move {
// `link` performs eventually-consistent Vc reads. That trips the top-level-task
// assertion under debug-assertions, but for a benchmark (not real code) reading
// the not-yet-settled value is fine — we only care about throughput.
unmark_top_level_task_may_leak_eventually_consistent_state();
let compile_time_info = CompileTimeInfo::builder(
Environment::new(ExecutionEnvironment::NodeJsLambda(
NodeJsEnvironment {
......
......@@ -3,7 +3,9 @@ use std::{path::PathBuf, time::Duration};
use anyhow::Result;
use criterion::{BatchSize, Bencher, BenchmarkId, Criterion, criterion_group, criterion_main};
use turbo_rcstr::rcstr;
use turbo_tasks::{ResolvedVc, TurboTasks, Vc};
use turbo_tasks::{
ResolvedVc, TurboTasks, Vc, unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{DiskFileSystem, FileSystem};
use turbopack_core::{
......@@ -136,6 +138,9 @@ fn bench_full(b: &mut Bencher, input: &BenchInput) {
let module = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(tt.run_once(async move {
// See note below: benchmarks may read eventually-consistent state at the
// top level, which is fine here but trips the debug assertion otherwise.
unmark_top_level_task_may_leak_eventually_consistent_state();
let module = setup(root_dir, file, analyze_mode).await?;
Ok(module)
}))
......@@ -145,6 +150,10 @@ fn bench_full(b: &mut Bencher, input: &BenchInput) {
},
|(tt, module)| async move {
tt.run_once(async move {
// `analyze_ecmascript_module` performs eventually-consistent Vc reads. Reading
// not-yet-settled state at the top level is fine for a throughput benchmark, but
// trips the top-level-task assertion under debug-assertions otherwise.
unmark_top_level_task_may_leak_eventually_consistent_state();
analyze_ecmascript_module(*module, None).await?;
Ok(())
})
......
......@@ -4,7 +4,9 @@ use criterion::{Bencher, BenchmarkId, Criterion};
use regex::Regex;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
Effects, OperationVc, TurboTasks, Vc, read_strongly_consistent_and_apply_effects, take_effects,
Effects, OperationVc, TurboTasks, Vc, mark_top_level_task,
read_strongly_consistent_and_apply_effects, take_effects,
unmark_top_level_task_may_leak_eventually_consistent_state,
};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_fs::{DiskFileSystem, FileSystem, NullFileSystem};
......@@ -85,6 +87,11 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) {
let input: RcStr = bench_input.input.clone().into();
async move {
tt.run_once(async move {
// This benchmark performs eventually-consistent Vc reads at the top level, which
// is fine for a throughput benchmark but trips the top-level-task assertion under
// debug-assertions otherwise. Unmark the top-level task for the reads, then re-mark
// it before `Effects::apply`, which *requires* a top-level task.
unmark_top_level_task_may_leak_eventually_consistent_state();
let input_fs = DiskFileSystem::new(rcstr!("tests"), Vc::cell(tests_root.clone()));
let input = input_fs.root().await?.join(&input)?;
......@@ -131,13 +138,17 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) {
.to_resolved()
.await?;
// `read_strongly_consistent_and_apply_effects` applies effects, which *requires* a
// top-level task. Restore the mark we cleared above for the eventually-consistent
// reads.
mark_top_level_task();
read_strongly_consistent_and_apply_effects(
extract_effects_operation(emit_assets_into_dir_operation(assets, output_dir)),
|e| e,
)
.await?;
Ok(())
anyhow::Ok(())
})
.await
.unwrap();
......
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