Unverified Commit ba0939fc authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

turbo-tasks-backend: track early aggregation removals as follower debt

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 00161ce1
//! Benchmarks adding and removing edges of the aggregation graph.
//!
//! - `ordered`: one parent alternates between connecting all of its children and none of them.
//! Every removal is processed after the corresponding addition.
//! - `concurrent`: many roots and parents share children and change which children they connect on
//! every iteration, so additions and removals of the same edges run concurrently and removals can
//! overtake additions.
//!
//! The graph is built once per configuration. Each iteration sets the state and reads all roots
//! strongly consistently.
//!
//! ```bash
//! cargo bench -p turbo-tasks-backend --bench mod -- aggregation_churn
//! ```
use std::time::{Duration, Instant};
use anyhow::Result;
use criterion::{BenchmarkId, Criterion, Throughput};
use turbo_tasks::{OperationVc, ResolvedVc, State, TryJoinIterExt, TurboTasks, Vc};
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
/// Length of the chain below each child. Chains increase the aggregation numbers of the tasks.
const CHAIN: u32 = 4;
#[turbo_tasks::value(transparent)]
struct Generation(State<u32>);
#[turbo_tasks::function(operation, root)]
fn create_generation() -> Vc<Generation> {
Generation(State::new(0)).cell()
}
/// Deterministically decides if `from` connects to `to` in `generation`.
fn connected(generation: u32, salt: u32, from: u32, to: u32) -> bool {
let mut x = generation
.wrapping_mul(0x9e37_79b9)
.wrapping_add(salt.wrapping_mul(0x85eb_ca6b))
.wrapping_add(from.wrapping_mul(0xc2b2_ae35))
.wrapping_add(to.wrapping_mul(0x27d4_eb2f));
x ^= x >> 15;
x = x.wrapping_mul(0x2c1b_3c6d);
x ^= x >> 12;
x.is_multiple_of(3)
}
#[turbo_tasks::task_input]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, bincode::Encode, bincode::Decode)]
struct Shape {
parents: u32,
children: u32,
/// When `false`, every parent connects all children in even and none in odd generations.
concurrent: bool,
}
#[turbo_tasks::function(operation, root)]
async fn root_operation(
generation: ResolvedVc<Generation>,
shape: Shape,
root: u32,
) -> Result<Vc<()>> {
let current = *generation.await?.get();
(0..shape.parents)
.filter(|&parent_index| !shape.concurrent || connected(current, 0, root, parent_index))
.map(|parent_index| parent(*generation, shape, parent_index))
.map(|parent| async move { parent.await })
.try_join()
.await?;
Ok(Vc::cell(()))
}
#[turbo_tasks::function]
async fn parent(generation: Vc<Generation>, shape: Shape, index: u32) -> Result<Vc<()>> {
let current = *generation.await?.get();
(0..shape.children)
.filter(|&child_index| {
if shape.concurrent {
connected(current, 1, index, child_index)
} else {
current.is_multiple_of(2)
}
})
.map(|child_index| child(child_index, CHAIN))
.map(|child| async move { child.await })
.try_join()
.await?;
Ok(Vc::cell(()))
}
#[turbo_tasks::function]
async fn child(index: u32, depth: u32) -> Result<Vc<()>> {
if depth > 0 {
child(index, depth - 1).await?;
}
Ok(Vc::cell(()))
}
async fn set_and_read(
generation_op: OperationVc<Generation>,
shape: Shape,
roots: u32,
value: u32,
) -> Result<Duration> {
let generation = generation_op.resolve().strongly_consistent().await?;
let state = generation_op.read_strongly_consistent().await?;
let start = Instant::now();
state.set(value);
(0..roots)
.map(|root| async move {
root_operation(generation, shape, root)
.read_strongly_consistent()
.await
})
.try_join()
.await?;
Ok(start.elapsed())
}
pub fn aggregation_churn(c: &mut Criterion) {
let mut group = c.benchmark_group("turbo_tasks_backend_aggregation_churn");
group.sample_size(20);
group.measurement_time(Duration::from_secs(10));
let configs = [
(
"ordered",
1,
Shape {
parents: 1,
children: 1_000,
concurrent: false,
},
),
(
"concurrent",
8,
Shape {
parents: 64,
children: 256,
concurrent: true,
},
),
];
for (name, roots, shape) in configs {
group.throughput(Throughput::Elements(shape.children as u64));
group.bench_with_input(
BenchmarkId::new(name, format_args!("{} x {}", shape.parents, shape.children)),
&shape,
|b, &shape| {
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
// `TurboTasks::new` needs the runtime context.
let tt = rt.block_on(async {
TurboTasks::new(TurboTasksBackend::new(
BackendOptions {
storage_mode: None,
..Default::default()
},
noop_backing_storage(),
))
});
// Build the graph once (not timed).
let generation_op = rt
.block_on(tt.run_once(async move {
let generation_op = create_generation();
set_and_read(generation_op, shape, roots, 0).await?;
Ok(generation_op)
}))
.unwrap();
let mut next_value = 1u32;
b.iter_custom(|iters| {
let mut total = Duration::ZERO;
for _ in 0..iters {
let value = next_value;
next_value = next_value.wrapping_add(1);
total += rt
.block_on(tt.run_once(async move {
set_and_read(generation_op, shape, roots, value).await
}))
.unwrap();
}
total
});
rt.block_on(async { tt.stop_and_wait().await });
},
);
}
group.finish();
}
......@@ -3,6 +3,7 @@
use criterion::{Criterion, criterion_group, criterion_main};
pub(crate) mod aggregation_churn;
pub(crate) mod batch_lookup;
pub(crate) mod cell_fan_out;
pub(crate) mod collectibles;
......@@ -17,6 +18,6 @@ criterion_group!(
config = Criterion::default();
targets = stress::fibonacci, scope_stress::scope_stress, overhead::overhead, gc::gc,
cell_fan_out::cell_fan_out, state_fan_out::state_fan_out, collectibles::collectibles,
batch_lookup::batch_lookup
batch_lookup::batch_lookup, aggregation_churn::aggregation_churn
);
criterion_main!(turbo_tasks_backend_stress);
......@@ -16,7 +16,8 @@ libfuzzer-sys = "0.4.9"
serde = { workspace = true }
tokio = { workspace = true, features = ["full"] }
turbo-tasks = { workspace = true, features = ["non_operation_vc_strongly_consistent"] }
turbo-tasks-backend = { workspace = true }
# Verify the aggregation graph and its edges (e.g. that no follower debt is left) on stop.
turbo-tasks-backend = { workspace = true, features = ["verify_aggregation_graph"] }
turbo-tasks-malloc = { workspace = true , features = ["custom_allocator"]}
[[bin]]
......
......@@ -3,7 +3,7 @@ use std::sync::{Arc, LazyLock};
use anyhow::Result;
use arbitrary::Arbitrary;
use bincode::{Decode, Encode};
use turbo_tasks::{self, State, TurboTasks, Vc};
use turbo_tasks::{self, State, TryJoinIterExt, TurboTasks, Vc};
use turbo_tasks_malloc::TurboMalloc;
#[turbo_tasks::task_input]
......@@ -58,6 +58,9 @@ impl<'a> Iterator for Iter<'a> {
}
}
/// The first tasks of the spec are run as concurrent roots.
const MAX_CONCURRENT_ROOTS: usize = 3;
static RUNTIME: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
......@@ -124,16 +127,31 @@ fn actual_operation(spec: Arc<Vec<TaskSpec>>, iterations: usize) {
},
turbo_tasks_backend::noop_backing_storage(),
));
let roots = spec.len().min(MAX_CONCURRENT_ROOTS) as u16;
for i in 0..iterations {
let spec = spec.clone();
tt.run(async move {
let it = *create_state().to_resolved().await?;
it.await?.set(i);
let task = run_task(spec.clone(), it, 0);
task.strongly_consistent().await?;
Ok(())
})
.await?;
// Run multiple roots concurrently. They share subgraphs, so edges of the
// aggregation graph are added and removed concurrently.
(0..roots)
.map(|root| {
let spec = spec.clone();
let tt = &tt;
async move {
anyhow::Ok(
tt.run(async move {
// Top-level tasks must only use strongly consistent reads.
let it_op = create_state();
let it = it_op.resolve().strongly_consistent().await?;
it_op.read_strongly_consistent().await?.set(i);
let task = run_task(spec.clone(), *it, root);
task.strongly_consistent().await?;
Ok(())
})
.await?,
)
}
})
.try_join()
.await?;
}
tt.stop_and_wait().await;
drop(tt);
......@@ -142,7 +160,7 @@ fn actual_operation(spec: Arc<Vec<TaskSpec>>, iterations: usize) {
.unwrap();
}
#[turbo_tasks::function]
#[turbo_tasks::function(operation, root)]
fn create_state() -> Vc<Iteration> {
Vc::cell(State::new(0))
}
......
......@@ -1684,6 +1684,8 @@ impl TurboTasksBackend {
{
self.is_idle.store(false, Ordering::Release);
self.verify_aggregation_graph(turbo_tasks, false);
// Storage is still alive here and no new aggregation updates can start.
self.verify_aggregation_edges();
}
// eagerly drop the task cache before persisting
self.storage.drop_task_cache();
......@@ -3598,6 +3600,30 @@ impl TurboTasksBackend {
}
}
/// Verifies the aggregation edges of all resident tasks (see
/// [`operation::verify_aggregation_edges`]). Must only be called when no aggregation updates
/// run.
#[cfg(any(test, feature = "verify_aggregation_graph"))]
pub(crate) fn verify_aggregation_edges(&self) {
if std::env::var("TURBO_ENGINE_VERIFY_GRAPH").ok().as_deref() == Some("0") {
return;
}
let violations =
operation::verify_aggregation_edges(&self.storage.aggregation_edges_for_verification());
if !violations.is_empty() {
panic!(
"The aggregation edges are inconsistent ({} violations):\n{}",
violations.len(),
violations
.iter()
.take(20)
.map(String::as_str)
.collect::<Vec<_>>()
.join("\n")
);
}
}
#[cfg(feature = "verify_aggregation_graph")]
fn verify_aggregation_graph(&self, turbo_tasks: &TurboTasks<TurboTasksBackend>, idle: bool) {
if env::var("TURBO_ENGINE_VERIFY_GRAPH").ok().as_deref() == Some("0") {
......
//! Pure helpers for the edge counts of the aggregation graph.
//!
//! An aggregation edge between an upper task `U` and a task `F` is stored either as an inner edge
//! (`F.upper[U]`, an unsigned count) or as a follower edge (`U.followers[F]`, a signed count). A
//! negative follower count is *debt*: removals of the edge that overtook the corresponding
//! additions. Only counts `> 0` are real edges. See the module docs of
//! [`super::aggregation_update`] for how debt is created and paid.
//!
//! These helpers contain no locking and no side effects, so the arithmetic and placement rules can
//! be reviewed and tested in isolation.
use turbo_tasks::TaskId;
use crate::backend::operation::aggregation_update::is_root_node;
/// Which side of the edge between `U` and `F` stores the edge count.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EdgeSide {
/// Stored as `F.upper[U]`: `U` aggregates the data of `F`.
Inner,
/// Stored as `U.followers[F]`: `F` is a follower of `U`.
Follower,
}
/// Where a writer (an edge addition) places the edge.
///
/// A root upper always aggregates its inner tasks (also when the follower is a root too). Equal
/// aggregation numbers of a non-root upper are placed on the follower side; [`edge_balance_side`]
/// treats that case as a conflict that is resolved later.
///
/// The writers only lock one task at a time, so they call this with the exact number of the locked
/// task and a lower bound for the other one. The decision loops in `aggregation_update` explain why
/// that is enough.
pub fn edge_write_side(
upper_aggregation_number: u32,
follower_aggregation_number: u32,
) -> EdgeSide {
if is_root_node(upper_aggregation_number)
|| follower_aggregation_number < upper_aggregation_number
{
EdgeSide::Inner
} else {
EdgeSide::Follower
}
}
/// Where `balance_edge` (which holds both locks) wants the edge.
///
/// Returns `None` for equal aggregation numbers of a non-root upper. That is a conflict which is
/// resolved by increasing the aggregation number of the follower.
pub fn edge_balance_side(
upper_aggregation_number: u32,
follower_aggregation_number: u32,
) -> Option<EdgeSide> {
if is_root_node(upper_aggregation_number)
|| follower_aggregation_number < upper_aggregation_number
{
Some(EdgeSide::Inner)
} else if follower_aggregation_number > upper_aggregation_number {
Some(EdgeSide::Follower)
} else {
None
}
}
/// Whether a write changed the existence of a real edge.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EdgeTransition {
/// The count went from `<= 0` to `> 0`.
Appeared,
/// The count went from `> 0` to `<= 0`.
Disappeared,
/// The count stayed `> 0` or stayed `<= 0`.
Unchanged,
}
/// The result of applying a delta to a follower count.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FollowerCountChange {
pub old: i32,
pub new: i32,
}
impl FollowerCountChange {
pub fn transition(&self) -> EdgeTransition {
match (self.old > 0, self.new > 0) {
(false, true) => EdgeTransition::Appeared,
(true, false) => EdgeTransition::Disappeared,
_ => EdgeTransition::Unchanged,
}
}
/// The follower count is negative after the write, i.e. there are removals that wait for
/// their additions.
pub fn is_debt(&self) -> bool {
self.new < 0
}
}
/// Applies `delta` to a follower count. `None` means the counter overflowed, which is a logic
/// error the caller reports with the involved task ids.
pub fn apply_follower_delta(old: i32, delta: i32) -> Option<FollowerCountChange> {
let new = old.checked_add(delta)?;
Some(FollowerCountChange { old, new })
}
/// Converts the unsigned count of an addition of the edge between `upper_id` and `follower_id`
/// into a signed follower delta.
///
/// # Panics
///
/// When the count doesn't fit into an `i32`. Counts this large would be a logic error.
pub fn follower_delta(upper_id: TaskId, follower_id: TaskId, count: u32) -> i32 {
i32::try_from(count).unwrap_or_else(|_| {
panic!("aggregation edge count {count} from {upper_id} to {follower_id} overflows i32")
})
}
/// Nets follower debt against an inner count of the same edge. Returns the new
/// `(inner, follower)` counts.
///
/// Debt and an inner edge can coexist when an addition placed the edge on the inner side while the
/// removal recorded debt on the follower side. The net count of the edge is `inner + follower`;
/// this cancels as much as possible so that at most one of both remains non-zero.
pub fn net_debt(inner: u32, follower: i32) -> (u32, i32) {
if follower >= 0 || inner == 0 {
return (inner, follower);
}
let debt = follower.unsigned_abs();
let cancelled = inner.min(debt);
// `follower + cancelled` is in `follower..=0`, so it always fits into an `i32`.
let new_follower = i32::try_from(i64::from(follower) + i64::from(cancelled))
.expect("netted follower count is between the old count and 0");
(inner - cancelled, new_follower)
}
/// The aggregation edges stored on one task, captured for verification.
#[cfg(any(test, feature = "verify_aggregation_graph"))]
#[derive(Clone, Debug)]
pub struct TaskAggregationEdges {
pub task_id: TaskId,
pub aggregation_number: u32,
/// `self.upper`: inner edges to upper tasks.
pub upper: Vec<(TaskId, u32)>,
/// `self.followers`: follower edges (or debt) to follower tasks.
pub followers: Vec<(TaskId, i32)>,
}
/// Checks the invariants of the aggregation edges that hold once all aggregation updates are
/// processed, and returns a description of every violation:
/// - There is no follower debt left (every removal found its addition).
/// - No edge is stored on both sides.
/// - Every edge is stored on a side that is valid for the aggregation numbers. Equal aggregation
/// numbers of a non-root upper are a conflict that is resolved lazily, so both sides are
/// accepted.
///
/// Must only be called when no aggregation updates run, e.g. when the backend stops.
#[cfg(any(test, feature = "verify_aggregation_graph"))]
pub fn verify_aggregation_edges(tasks: &[TaskAggregationEdges]) -> Vec<String> {
use rustc_hash::FxHashMap;
let aggregation_numbers: FxHashMap<TaskId, u32> = tasks
.iter()
.map(|t| (t.task_id, t.aggregation_number))
.collect();
let follower_counts: FxHashMap<(TaskId, TaskId), i32> = tasks
.iter()
.flat_map(|t| t.followers.iter().map(|&(f, c)| ((t.task_id, f), c)))
.collect();
let mut violations = Vec::new();
for task in tasks {
let upper_id = task.task_id;
for &(follower_id, count) in &task.followers {
if count < 0 {
violations.push(format!(
"follower debt {count} in {upper_id} for follower {follower_id}"
));
continue;
}
if let Some(&follower_number) = aggregation_numbers.get(&follower_id)
&& edge_balance_side(task.aggregation_number, follower_number)
== Some(EdgeSide::Inner)
{
violations.push(format!(
"follower edge {upper_id} -> {follower_id} should be an inner edge \
(aggregation numbers {} and {follower_number})",
task.aggregation_number
));
}
}
let follower_id = task.task_id;
for &(upper_id, _) in &task.upper {
if let Some(&follower_count) = follower_counts.get(&(upper_id, follower_id)) {
violations.push(format!(
"edge {upper_id} -> {follower_id} is stored on both sides (follower count \
{follower_count})"
));
}
if let Some(&upper_number) = aggregation_numbers.get(&upper_id)
&& edge_balance_side(upper_number, task.aggregation_number)
== Some(EdgeSide::Follower)
{
violations.push(format!(
"inner edge {upper_id} -> {follower_id} should be a follower edge \
(aggregation numbers {upper_number} and {})",
task.aggregation_number
));
}
}
}
violations
}
#[cfg(test)]
mod tests {
use super::*;
const ROOT: u32 = u32::MAX;
#[test]
fn write_side() {
// A root upper always aggregates, even a root follower.
assert_eq!(edge_write_side(ROOT, ROOT), EdgeSide::Inner);
assert_eq!(edge_write_side(ROOT, 0), EdgeSide::Inner);
assert_eq!(edge_write_side(20, 10), EdgeSide::Inner);
// Equal numbers of a non-root upper are written as follower edges.
assert_eq!(edge_write_side(20, 20), EdgeSide::Follower);
assert_eq!(edge_write_side(20, 30), EdgeSide::Follower);
assert_eq!(edge_write_side(20, ROOT), EdgeSide::Follower);
}
#[test]
fn balance_side() {
assert_eq!(edge_balance_side(ROOT, ROOT), Some(EdgeSide::Inner));
assert_eq!(edge_balance_side(ROOT, 0), Some(EdgeSide::Inner));
assert_eq!(edge_balance_side(20, 10), Some(EdgeSide::Inner));
assert_eq!(edge_balance_side(20, 20), None);
assert_eq!(edge_balance_side(20, 30), Some(EdgeSide::Follower));
assert_eq!(edge_balance_side(20, ROOT), Some(EdgeSide::Follower));
}
#[test]
fn write_and_balance_side_agree_outside_of_conflicts() {
for upper in [0, 1, 15, 16, 17, 100, ROOT - 1, ROOT] {
for follower in [0, 1, 15, 16, 17, 100, ROOT - 1, ROOT] {
match edge_balance_side(upper, follower) {
Some(side) => assert_eq!(edge_write_side(upper, follower), side),
None => {
assert_eq!(upper, follower);
assert_eq!(edge_write_side(upper, follower), EdgeSide::Follower);
}
}
}
}
}
fn transition(old: i32, delta: i32) -> (i32, EdgeTransition, bool) {
let change = apply_follower_delta(old, delta).unwrap();
(change.new, change.transition(), change.is_debt())
}
#[test]
fn follower_delta_transitions() {
use EdgeTransition::*;
// Plain additions and removals.
assert_eq!(transition(0, 1), (1, Appeared, false));
assert_eq!(transition(1, 1), (2, Unchanged, false));
assert_eq!(transition(2, -1), (1, Unchanged, false));
assert_eq!(transition(1, -1), (0, Disappeared, false));
// A removal that overtakes its addition creates debt, without an edge transition.
assert_eq!(transition(0, -1), (-1, Unchanged, true));
assert_eq!(transition(-1, -1), (-2, Unchanged, true));
// Paying debt is not an edge transition either ...
assert_eq!(transition(-1, 1), (0, Unchanged, false));
assert_eq!(transition(-2, 1), (-1, Unchanged, true));
// ... until the count gets positive.
assert_eq!(transition(-1, 2), (1, Appeared, false));
// Batched removals can skip zero.
assert_eq!(transition(1, -2), (-1, Disappeared, true));
}
#[test]
fn follower_delta_overflow() {
assert_eq!(apply_follower_delta(i32::MAX, 1), None);
assert_eq!(apply_follower_delta(i32::MIN, -1), None);
assert!(apply_follower_delta(i32::MAX, -1).is_some());
assert!(apply_follower_delta(i32::MIN, 1).is_some());
}
#[test]
fn follower_delta_conversion() {
assert_eq!(follower_delta(id(1), id(2), 0), 0);
assert_eq!(follower_delta(id(1), id(2), 7), 7);
assert_eq!(follower_delta(id(1), id(2), i32::MAX as u32), i32::MAX);
}
#[test]
fn follower_delta_conversion_overflow_names_edge() {
let error = std::panic::catch_unwind(|| {
follower_delta(id(11), id(12), i32::MAX as u32 + 1);
})
.expect_err("conversion must overflow");
let message = error
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| error.downcast_ref::<&str>().copied())
.unwrap_or_default();
assert!(message.contains("overflows i32"), "{message}");
assert!(message.contains(&id(11).to_string()), "{message}");
assert!(message.contains(&id(12).to_string()), "{message}");
}
#[test]
fn net_debt_cases() {
// Nothing to net.
assert_eq!(net_debt(0, 0), (0, 0));
assert_eq!(net_debt(0, -3), (0, -3));
assert_eq!(net_debt(2, 0), (2, 0));
assert_eq!(net_debt(2, 5), (2, 5));
// Debt and inner count cancel each other.
assert_eq!(net_debt(1, -1), (0, 0));
assert_eq!(net_debt(1, -3), (0, -2));
assert_eq!(net_debt(3, -1), (2, 0));
// Extremes don't overflow.
assert_eq!(net_debt(u32::MAX, i32::MIN), (u32::MAX - (1 << 31), 0));
assert_eq!(net_debt(1, i32::MIN), (0, i32::MIN + 1));
}
fn task(id: u32, aggregation_number: u32) -> TaskAggregationEdges {
TaskAggregationEdges {
task_id: TaskId::new(id).unwrap(),
aggregation_number,
upper: Vec::new(),
followers: Vec::new(),
}
}
fn id(id: u32) -> TaskId {
TaskId::new(id).unwrap()
}
#[test]
fn verify_accepts_valid_edges() {
let mut upper = task(1, 100);
let mut inner = task(2, 10);
let follower = task(3, 200);
let mut conflict = task(4, 100);
inner.upper.push((id(1), 1));
upper.followers.push((id(3), 2));
// equal aggregation numbers are accepted on both sides
conflict.upper.push((id(1), 1));
assert_eq!(
verify_aggregation_edges(&[upper, inner, follower, conflict]),
Vec::<String>::new()
);
}
#[test]
fn verify_reports_debt_and_split_edges() {
let mut upper = task(1, 100);
let mut inner = task(2, 10);
upper.followers.push((id(2), -1));
inner.upper.push((id(1), 1));
let violations = verify_aggregation_edges(&[upper, inner]);
assert_eq!(violations.len(), 2, "{violations:#?}");
assert!(violations[0].contains("debt"));
assert!(violations[1].contains("both sides"));
}
#[test]
fn verify_reports_misplaced_edges() {
let mut upper = task(1, 100);
let mut root = task(5, ROOT);
let mut inner = task(2, 10);
let mut follower = task(3, 200);
// should be inner
upper.followers.push((id(2), 1));
// should be follower
follower.upper.push((id(1), 1));
// a root upper must not have followers, even a root follower
root.followers.push((id(6), 1));
let other_root = task(6, ROOT);
inner.upper.clear();
let violations = verify_aggregation_edges(&[upper, root, inner, follower, other_root]);
assert_eq!(violations.len(), 3, "{violations:#?}");
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -202,7 +202,6 @@ fn cleanup_old_edges_inner(
queue.push(AggregationUpdateJob::InnerOfUpperLostFollowers {
upper_id: task_id,
lost_follower_ids: children,
retry: 0,
});
} else {
let upper_ids = get_uppers(&task);
......
mod aggregation_edge;
mod aggregation_update;
mod cleanup_old_edges;
mod connect_child;
......@@ -24,6 +25,8 @@ use turbo_tasks::{
macro_helpers::NativeFunction,
};
#[cfg(any(test, feature = "verify_aggregation_graph"))]
pub use self::aggregation_edge::{TaskAggregationEdges, verify_aggregation_edges};
pub use self::aggregation_update::{AggregationUpdateQueue, ComputeDirtyAndCleanUpdate};
use crate::{
backend::{
......@@ -160,6 +163,20 @@ impl<'e> ExecuteContext<'e> {
}
}
/// Like [`ExecuteContext::new`], but reports tasks that may have become collectible to
/// `gc_collectible`, like the context of the garbage collector does.
#[cfg(test)]
pub(super) fn new_with_gc_collectible_for_testing(
backend: &'e TurboTasksBackend,
turbo_tasks: &'e TurboTasks<TurboTasksBackend>,
gc_collectible: &'e dyn Fn(TaskId),
) -> Self {
Self {
gc_collectible: Some(gc_collectible),
..Self::new(backend, turbo_tasks)
}
}
/// Constructs a context that does NOT take an operation guard, for use by the garbage
/// collector while it holds the coordinator's exclusion phase.
///
......
......@@ -662,6 +662,22 @@ impl Storage {
per_shard.into_iter().flatten()
}
/// Captures the aggregation edges of all resident tasks, for verification of the aggregation
/// graph. Only meaningful when no aggregation updates run concurrently.
#[cfg(any(test, feature = "verify_aggregation_graph"))]
pub fn aggregation_edges_for_verification(
&self,
) -> Vec<crate::backend::operation::TaskAggregationEdges> {
let mut result = Vec::new();
for shard in self.map.shards() {
let shard = shard.read();
for (task_id, task) in shard.iter() {
result.extend(task.aggregation_edges_for_verification(*task_id));
}
}
result
}
pub fn access_pair_mut(
&self,
key1: TaskId,
......
......@@ -252,8 +252,12 @@ struct TaskStorageSchema {
children: AutoSet<TaskId, 6>,
/// Follower nodes in the aggregation tree (reference counted).
///
/// Signed: a negative count is "debt", recorded when the removal of a follower edge overtakes
/// its addition. Only counts `> 0` are real edges. See the module docs of
/// `operation::aggregation_update` for details.
#[field(storage = "counter_map", category = "meta", filter_transient)]
followers: CounterMap<TaskId, u32, 3>,
followers: CounterMap<TaskId, i32, 3>,
// =========================================================================
// DEPENDENCIES (data)
......@@ -812,6 +816,30 @@ impl TaskStorage {
});
}
/// Captures the aggregation edges of this task for verification of the aggregation graph.
/// Returns `None` when the task has no aggregation edges.
#[cfg(any(test, feature = "verify_aggregation_graph"))]
pub fn aggregation_edges_for_verification(
&self,
task_id: TaskId,
) -> Option<crate::backend::operation::TaskAggregationEdges> {
let upper: Vec<_> = self.upper().iter().map(|(&id, &c)| (id, c)).collect();
let followers: Vec<_> = self
.followers()
.into_iter()
.flat_map(|f| f.iter().map(|(&id, &c)| (id, c)))
.collect();
if upper.is_empty() && followers.is_empty() {
return None;
}
Some(crate::backend::operation::TaskAggregationEdges {
task_id,
aggregation_number: self.get_aggregation_number().map_or(0, |a| a.effective),
upper,
followers,
})
}
/// Returns counts for aggregation tree and collectibles fields.
/// Used for cache size statistics.
#[cfg(feature = "print_cache_item_size")]
......
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
//! Stress test for the aggregation graph: many tasks concurrently add and remove edges to shared
//! children on every change of a state, so removals of edges race with their additions.
//!
//! Run it with `--features verify_aggregation_graph` to verify the aggregation graph when the
//! backend stops: aggregated dirty containers and collectibles, and that the aggregation edges are
//! consistent (e.g. no follower debt is left over).
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, State, TryJoinIterExt, ValueToString, Vc, emit};
use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!();
/// Number of root operations.
const ROOTS: u32 = 4;
/// Number of parents shared by the roots.
const PARENTS: u32 = 16;
/// Number of children shared by the parents.
const CHILDREN: u32 = 24;
/// Length of the chain below each child. Chains increase the aggregation numbers of the tasks.
const CHAIN: u32 = 4;
fn rounds() -> u32 {
std::env::var("TURBOPACK_TEST_AGGREGATION_CHURN_ROUNDS")
.map(|rounds| rounds.parse().unwrap())
.unwrap_or(20)
}
/// Deterministically decides if `from` connects to `to` in `generation`.
fn connected(generation: u32, salt: u32, from: u32, to: u32) -> bool {
let mut x = generation
.wrapping_mul(0x9e37_79b9)
.wrapping_add(salt.wrapping_mul(0x85eb_ca6b))
.wrapping_add(from.wrapping_mul(0xc2b2_ae35))
.wrapping_add(to.wrapping_mul(0x27d4_eb2f));
x ^= x >> 15;
x = x.wrapping_mul(0x2c1b_3c6d);
x ^= x >> 12;
x.is_multiple_of(3)
}
/// The number of children all parents of `root` connect in `generation`.
fn expected_connected_children(generation: u32, root: u32) -> u32 {
(0..PARENTS)
.filter(|&parent| connected(generation, 0, root, parent))
.map(|parent| {
(0..CHILDREN)
.filter(|&child| connected(generation, 1, parent, child))
.count() as u32
})
.sum()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn aggregation_churn() {
run_once(&REGISTRATION, async || {
let generation_op = make_generation_operation();
let generation_vc = generation_op.resolve().strongly_consistent().await?;
let generation = generation_op.read_strongly_consistent().await?;
for round in 0..rounds() {
generation.state.set(round);
(0..ROOTS)
.map(|root| async move {
let connected_children = *root_operation(generation_vc, root)
.read_strongly_consistent()
.await?;
assert_eq!(
connected_children,
expected_connected_children(round, root),
"connected children of root {root} in round {round}"
);
anyhow::Ok(())
})
.try_join()
.await?;
}
anyhow::Ok(())
})
.await
.unwrap()
}
#[turbo_tasks::value]
struct Generation {
state: State<u32>,
}
#[turbo_tasks::function(operation, root)]
fn make_generation_operation() -> Vc<Generation> {
Generation {
state: State::new(0),
}
.cell()
}
#[turbo_tasks::value(transparent)]
struct Count(u32);
/// Returns the number of children connected by the parents of `root`.
#[turbo_tasks::function(operation, root)]
async fn root_operation(generation: ResolvedVc<Generation>, root: u32) -> Result<Vc<Count>> {
let current = *generation.await?.state.get();
let counts = (0..PARENTS)
.filter(|&parent_index| connected(current, 0, root, parent_index))
.map(|parent_index| parent(*generation, parent_index))
.map(|parent| async move { parent.await })
.try_join()
.await?;
Ok(Vc::cell(counts.iter().map(|count| **count).sum()))
}
/// Connects a subset of the children, depending on the generation. Returns their number.
#[turbo_tasks::function]
async fn parent(generation: Vc<Generation>, index: u32) -> Result<Vc<Count>> {
let current = *generation.await?.state.get();
let children = (0..CHILDREN)
.filter(|&child_index| connected(current, 1, index, child_index))
.map(|child_index| child(child_index, CHAIN))
.map(|child| async move { child.await })
.try_join()
.await?;
Ok(Vc::cell(children.len() as u32))
}
#[turbo_tasks::function]
async fn child(index: u32, depth: u32) -> Result<Vc<()>> {
if depth > 0 {
child(index, depth - 1).await?;
} else {
emit(ResolvedVc::upcast::<Box<dyn ValueToString>>(Thing::new(
index,
)));
}
Ok(Vc::cell(()))
}
#[turbo_tasks::value(shared)]
struct Thing(u32);
impl Thing {
fn new(v: u32) -> ResolvedVc<Self> {
Self::resolved_cell(Thing(v))
}
}
#[turbo_tasks::value_impl]
impl ValueToString for Thing {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell(self.0.to_string().into())
}
}
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