Unverified Commit eaa2f075 authored by Jimmy Miller's avatar Jimmy Miller Committed by GitHub

Remove suspend during operations (#99383)

## What

Remove the ability to suspend in flight operations to allow for
snapshotting and GC

## Why

Exstensive testing with GC has revealed a number of bugs latent in this
system

* transient task ids are getting serialized as part of operations, this
confuses our new stricter task access semantics in fresh sessions
* child execution contexts don't properly participate, they both need to
suspend when requested to avoid exceeding retries since the task they
are waiting for has already suspended, and cannot suspend because that
could deadlock the scope_bounded call

Instead we just don't suspend. This simplifies a lot, should be a small
perf win (purely from not touching the atomics as often)

The major risk is that waiting for everything to settle adds latency. To
mitigate that:

* idle snapshots don't wait for operations to settle, they just bail out
instead
* other snapshots do wait but log warnings if it takes more than 10s,
this should never happen but if it does we will have a smoking gun

---------
Co-authored-by: 's avatarLuke Sandberg <lukesandberg@users.noreply.github.com>
parent c62c51e3
......@@ -9051,7 +9051,6 @@ dependencies = [
"either",
"indexmap 2.14.0",
"mime",
"ringmap",
"serde",
"smallvec",
"turbo-tasks-hash",
......
......@@ -15,7 +15,6 @@ bincode = { workspace = true }
either = { workspace = true }
indexmap = { workspace = true }
mime = { workspace = true }
ringmap = { workspace = true }
serde = { workspace = true }
smallvec = { workspace = true }
turbo-tasks-hash = { workspace = true }
......
......@@ -375,83 +375,6 @@ pub mod indexset {
}
}
pub mod ringset {
use std::hash::{BuildHasher, Hash};
use ::ringmap::RingSet;
use super::*;
pub fn encode<E, T, S>(set: &RingSet<T, S>, encoder: &mut E) -> Result<(), EncodeError>
where
E: Encoder,
T: Encode,
{
usize::encode(&set.len(), encoder)?;
for item in set {
T::encode(item, encoder)?;
}
Ok(())
}
pub fn decode<Context, D, T, S>(decoder: &mut D) -> Result<RingSet<T, S>, DecodeError>
where
D: Decoder<Context = Context>,
T: Decode<Context> + Eq + Hash,
S: BuildHasher + Default,
{
let len = usize::decode(decoder)?;
let mut set = RingSet::with_capacity_and_hasher(len, Default::default());
for _i in 0..len {
set.insert(T::decode(decoder)?);
}
Ok(set)
}
pub fn borrow_decode<'de, Context, D, T, S>(
decoder: &mut D,
) -> Result<RingSet<T, S>, DecodeError>
where
D: BorrowDecoder<'de, Context = Context>,
T: BorrowDecode<'de, Context> + Eq + Hash,
S: BuildHasher + Default,
{
let len = usize::decode(decoder)?;
let mut set = RingSet::with_capacity_and_hasher(len, Default::default());
for _i in 0..len {
set.insert(T::borrow_decode(decoder)?);
}
Ok(set)
}
#[cfg(test)]
mod tests {
use bincode::{decode_from_slice, encode_to_vec};
use super::*;
#[test]
fn test_roundtrip() {
let cfg = bincode::config::standard();
#[derive(Encode, Decode)]
struct Wrapper(#[bincode(with = "crate::ringset")] RingSet<String>);
let set1 = Wrapper(RingSet::from([
"value1".to_string(),
"value2".to_string(),
"value3".to_string(),
]));
let set2: Wrapper = decode_from_slice(&encode_to_vec(&set1, cfg).unwrap(), cfg)
.unwrap()
.0;
assert_eq!(set1.0, set2.0);
}
}
}
pub mod mime_option {
use std::str::FromStr;
......
......@@ -29,10 +29,10 @@ use turbo_tasks::{TaskId, TurboTasks, scope_unbounded::scope_unbounded_with};
use crate::{
backend::{
AnyOperation, TurboTasksBackend,
TurboTasksBackend,
operation::{
AggregationUpdateJob, AggregationUpdateQueue, CleanupOldEdgesOperation, ExecuteContext,
ExecuteContextImpl, TaskGuard, capture_all_edges,
AggregationUpdateJob, AggregationUpdateQueue, ExecuteContext, ExecuteContextImpl,
TaskGuard, capture_all_edges, cleanup_old_edges_deletions_only,
},
snapshot_coordinator::SnapshotPhase,
storage::{SpecificTaskDataCategory, TaskDataCategory},
......@@ -73,7 +73,7 @@ enum GcJob {
/// Decides when a GC pass should stop early because it is delaying real work.
struct GcBudget<'a> {
phase: &'a SnapshotPhase<'a, AnyOperation>,
phase: &'a SnapshotPhase<'a>,
started: Instant,
/// The minimum quantum of work this pass does before any interrupt is honoured.
min_progress: Duration,
......@@ -208,7 +208,7 @@ impl TurboTasksBackend {
pub(crate) fn gc_collect(
&self,
turbo_tasks: &TurboTasks<TurboTasksBackend>,
phase: &SnapshotPhase<'_, AnyOperation>,
phase: &SnapshotPhase<'_>,
interruptible: bool,
) -> (GcStats, GcPassResult, Option<Vec<(TaskId, TtlCounter)>>) {
// Record the time at the beginning of the loop to have a consistent timestamp for the roots
......@@ -288,7 +288,7 @@ impl TurboTasksBackend {
// It is almost certainly already marked modified, so this is mostly a no-op.
let _ = task.track_modification(SpecificTaskDataCategory::Meta, "gc_deleted");
}
drop(task); // drop the lock so CleanupOldEdgesOperation can run
drop(task); // drop the lock so edge cleanup can run
stats.collected += 1;
stats.edges_deleted += old_edges.len();
// If we happened to delete a known root at this point record it so we can reconcile
......@@ -299,8 +299,7 @@ impl TurboTasksBackend {
// Delete outgoing edges but don't update the aggregation graph yet.
// To avoid accidentally rebalancing on deleted tasks due to racing deletions,
// we defer all rebalancing to the end
let deferred =
CleanupOldEdgesOperation::run_edge_deletions_only(task_id, old_edges, &mut ctx);
let deferred = cleanup_old_edges_deletions_only(task_id, old_edges, &mut ctx);
result.deferred_balance_edges.extend(deferred.balance_edges);
result
.deferred_dirty_dependents
......@@ -451,18 +450,18 @@ impl TurboTasksBackend {
"gc_for_testing requires a GC-enabled backend: set `BackendOptions::gc = Some(true)`"
);
let _serialize = self.snapshot_in_progress.lock();
let phase = self.snapshot_coord.begin_snapshot();
let phase = self
.snapshot_coord
.begin_snapshot(|slow| Self::report_slow_settle_for_snapshot(turbo_tasks, slow));
let (stats, _result, roots) =
self.gc_collect(turbo_tasks, &phase, /* interruptible= */ false);
// Persist the roots map this pass produced. Some tests query the roots set and GC itself
// does as well, this ensures it is available to the next cycle.
if let Some(roots) = roots
&& let Err(err) = self.backing_storage.save_snapshot(
Vec::new(),
Some(roots),
Vec::<Vec<SnapshotItem>>::new(),
)
&& let Err(err) = self
.backing_storage
.save_snapshot(Some(roots), Vec::<Vec<SnapshotItem>>::new())
{
panic!("gc_for_testing: failed to persist GC roots: {err:?}");
}
......
......@@ -46,7 +46,7 @@ use turbo_tasks::{
},
event::{Event, EventDescription, EventListener},
macro_helpers::NativeFunction,
message_queue::{TimingEvent, TraceEvent},
message_queue::{DiagnosticEvent, Severity, TimingEvent, TraceEvent},
registry::get_value_type,
scope_bounded::scope_bounded,
task_statistics::TaskStatisticsApi,
......@@ -59,19 +59,18 @@ use turbo_tasks_malloc::TurboMalloc;
use self::eviction::EvictionControl;
pub use self::{
eviction::EvictionMode,
operation::AnyOperation,
storage::{EvictionCounts, SpecificTaskDataCategory, TaskDataCategory},
};
use crate::{
backend::{
operation::{
AggregationUpdateJob, AggregationUpdateQueue, ChildExecuteContext,
CleanupOldEdgesOperation, ConnectChildOperation, ExecuteContext, ExecuteContextImpl,
LeafDistanceUpdateQueue, Operation, OutdatedEdge, TaskGuard, TaskType, TaskTypeRef,
capture_all_edges, connect_children, get_aggregation_number, get_uppers,
make_task_dirty_internal, prepare_new_children,
AggregationUpdateJob, AggregationUpdateQueue, ChildExecuteContext, ExecuteContext,
ExecuteContextImpl, LeafDistanceUpdateQueue, OutdatedEdge, TaskGuard, TaskType,
TaskTypeRef, capture_all_edges, cleanup_old_edges, connect_child, connect_children,
get_aggregation_number, get_uppers, invalidate, make_task_dirty_internal,
prepare_new_children, update_cell,
},
snapshot_coordinator::{OperationGuard, SnapshotCoordinator},
snapshot_coordinator::{OperationGuard, SlowSettle, SnapshotCoordinator},
storage::Storage,
storage_schema::{TaskStorage, TaskStorageAccessors},
},
......@@ -210,6 +209,14 @@ impl SnapshotReason {
}
}
/// Whether this snapshot waits for in-flight operations to settle. Otherwise it is skipped
/// if any operation is active when it starts.
fn waits_for_operations(self) -> bool {
// Idle snapshots are opportunistic: an active operation means we are no longer idle, so
// skip and let the background loop try again rather than pausing the work that woke us.
!matches!(self, SnapshotReason::IdleTimeout)
}
/// Whether a GC pass run for this reason may wind down early when an operation is waiting.
fn gc_is_interruptible(self) -> bool {
matches!(self, SnapshotReason::IdleTimeout | SnapshotReason::Test)
......@@ -390,7 +397,7 @@ impl TurboTasksBackend {
))
}
pub(crate) fn start_operation(&self) -> Option<OperationGuard<'_, AnyOperation>> {
pub(crate) fn start_operation(&self) -> Option<OperationGuard<'_>> {
if !self.should_persist() {
return None;
}
......@@ -419,7 +426,8 @@ impl TurboTasksBackend {
);
let snapshot_result = self.snapshot_and_persist(None, SnapshotReason::Test, turbo_tasks);
let (had_new_data, gc_outcome) = match snapshot_result {
Ok((_, new_data, gc_outcome)) => (new_data, gc_outcome),
Ok(Some((_, new_data, gc_outcome))) => (new_data, gc_outcome),
Ok(None) => unreachable!("test snapshots wait for operations to settle"),
Err(_) => {
// Snapshot/persist failed — skip eviction since the data may not
// be on disk yet. Evicting now could lose in-memory state that
......@@ -1128,7 +1136,9 @@ impl TurboTasksBackend {
/// Runs a persistence cycle
///
/// Returns `(snapshot_start, had_new_data, gc_outcome)`. `gc_outcome` is `None` when GC is
/// Returns `None` if the cycle was skipped because operations were active and the reason
/// doesn't [wait for them](SnapshotReason::waits_for_operations). Otherwise returns
/// `(snapshot_start, had_new_data, gc_outcome)`. `gc_outcome` is `None` when GC is
/// disabled; it is returned rather than stashed on `self` so a test can inspect the pass it
/// just triggered without the backend carrying test-only state. Production reads the same
/// numbers off the `gc` span.
......@@ -1138,13 +1148,11 @@ impl TurboTasksBackend {
parent_span: Option<tracing::Id>,
reason: SnapshotReason,
turbo_tasks: &TurboTasks<TurboTasksBackend>,
) -> Result<(Instant, bool, Option<(GcStats, GcPassResult)>)> {
) -> Result<Option<(Instant, bool, Option<(GcStats, GcPassResult)>)>> {
let snapshot_span =
tracing::trace_span!(parent: parent_span.clone(), "snapshot", reason = reason.as_str())
.entered();
// Serialize snapshots. The internal protocol (snapshot_mode, snapshot
// request bit, suspended_operations) assumes only one snapshot runs at
// a time. Held for the entire snapshot lifecycle.
// Serialize snapshots and GC for the entire persistence cycle.
let _snapshot_in_progress = self.snapshot_in_progress.lock();
// One exclusion covers the GC pass and the snapshot that follows it, so the collected
......@@ -1155,7 +1163,15 @@ impl TurboTasksBackend {
// since epoch). Instant is monotonic but has no defined epoch, so it
// can't be used for cross-process trace correlation.
let wall_start = SystemTime::now();
let mut snapshot_phase = self.snapshot_coord.begin_snapshot();
let snapshot_phase = if reason.waits_for_operations() {
self.snapshot_coord
.begin_snapshot(|slow| Self::report_slow_settle_for_snapshot(turbo_tasks, slow))
} else {
match self.snapshot_coord.try_begin_snapshot() {
Some(phase) => phase,
None => return Ok(None),
}
};
let (gc_elapsed, gc_roots_to_persist, gc_outcome) = if self.gc_enabled {
let gc_span = tracing::info_span!(
"gc",
......@@ -1172,7 +1188,7 @@ impl TurboTasksBackend {
// This ensures that we don't persist roots that were not completely validated.
drop(snapshot_phase);
drop(gc_span);
return Ok((start, false, Some((stats, result))));
return Ok(Some((start, false, Some((stats, result)))));
}
(Some(start.elapsed()), roots, Some((stats, result)))
} else {
......@@ -1181,11 +1197,9 @@ impl TurboTasksBackend {
debug_assert!(self.should_persist());
// Checking after start_snapshot ensures no concurrent increments can race.
// Checking after the exclusion begins ensures no concurrent increments can race.
let (snapshot_guard, has_modifications) = self.storage.start_snapshot();
let suspended_operations = snapshot_phase.take_suspended_operations();
let snapshot_time = Instant::now();
drop(snapshot_phase);
......@@ -1193,7 +1207,7 @@ impl TurboTasksBackend {
// No tasks modified since the last snapshot — drop the guard (which
// calls end_snapshot) and skip the expensive O(N) scan.
drop(snapshot_guard);
return Ok((start, false, gc_outcome));
return Ok(Some((start, false, gc_outcome)));
}
#[cfg(feature = "print_cache_item_size")]
......@@ -1455,8 +1469,8 @@ impl TurboTasksBackend {
creation for persistent tasks uses a single ExecutionContextImpl for \
creating the task (which sets new_task) and connect_child (which sets \
persistent_task_type) and take_snapshot waits for all operations to complete \
or suspend before we start snapshotting. So task creation will always set \
the task_type.",
before we start snapshotting. So task creation will always set the \
task_type.",
);
Some(compute_task_type_hash(task_type))
} else {
......@@ -1484,7 +1498,7 @@ impl TurboTasksBackend {
// was present, and every modification that increments the count also failed
// during encoding.
std::hint::cold_path();
return Ok((snapshot_time, false, gc_outcome));
return Ok(Some((snapshot_time, false, gc_outcome)));
}
let persist_start = Instant::now();
......@@ -1498,11 +1512,9 @@ impl TurboTasksBackend {
// Tasks were already consumed by take_snapshot, so a future snapshot
// would not re-persist them — returning an error signals to the caller
// that further persist attempts would corrupt the task graph in storage.
let snapshot_meta = self.backing_storage.save_snapshot(
suspended_operations,
gc_roots_to_persist,
task_snapshots,
)?;
let snapshot_meta = self
.backing_storage
.save_snapshot(gc_roots_to_persist, task_snapshots)?;
span.record("snapshot_meta", display(snapshot_meta));
#[cfg(feature = "print_cache_item_size")]
......@@ -1620,26 +1632,10 @@ impl TurboTasksBackend {
]),
)));
Ok((snapshot_time, true, gc_outcome))
Ok(Some((snapshot_time, true, gc_outcome)))
}
fn startup(&self, turbo_tasks: &TurboTasks<TurboTasksBackend>) {
if self.should_restore() {
// Continue all uncompleted operations
// They can't be interrupted by a snapshot since the snapshotting job has not been
// scheduled yet.
let uncompleted_operations = self
.backing_storage
.uncompleted_operations()
.expect("Failed to get uncompleted operations");
if !uncompleted_operations.is_empty() {
let mut ctx = self.execute_context(turbo_tasks);
for op in uncompleted_operations {
op.execute(&mut ctx);
}
}
}
// Only when it should write regularly to the storage, we schedule the initial snapshot
// job.
if matches!(self.options.storage_mode, Some(StorageMode::ReadWrite)) {
......@@ -1764,7 +1760,7 @@ impl TurboTasksBackend {
get_in_shard(shard, hash, |k| k.eq_components(native_fn, this, arg_ref))
{
self.track_cache_hit_by_fn(native_fn);
operation::ConnectChildOperation::run(
connect_child(
parent_task,
task_id,
/* release_construction_ref */ false,
......@@ -1870,7 +1866,7 @@ impl TurboTasksBackend {
// New tasks carry a transient ref so they survive construction. Release it while
// connecting the task to the graph.
operation::ConnectChildOperation::run(parent_task, task_id, created_new, ctx);
connect_child(parent_task, task_id, created_new, ctx);
task_id
}
......@@ -1879,7 +1875,7 @@ impl TurboTasksBackend {
if !self.should_track_dependencies() {
panic!("Dependency tracking is disabled so invalidation is not allowed");
}
operation::InvalidateOperation::run(
invalidate(
smallvec![task_id],
#[cfg(feature = "task_dirty_cause")]
TaskDirtyCause::Invalidator,
......@@ -1891,7 +1887,7 @@ impl TurboTasksBackend {
if !self.should_track_dependencies() {
panic!("Dependency tracking is disabled so invalidation is not allowed");
}
operation::InvalidateOperation::run(
invalidate(
tasks.iter().copied().collect(),
#[cfg(feature = "task_dirty_cause")]
TaskDirtyCause::Unknown,
......@@ -1907,7 +1903,7 @@ impl TurboTasksBackend {
if !self.should_track_dependencies() {
panic!("Dependency tracking is disabled so invalidation is not allowed");
}
operation::InvalidateOperation::run(
invalidate(
tasks.iter().copied().collect(),
#[cfg(feature = "task_dirty_cause")]
TaskDirtyCause::Unknown,
......@@ -2173,9 +2169,8 @@ impl TurboTasksBackend {
// 3. Remove dirty flag (and propagate that to uppers) and remove the in-progress state.
// 4. Shrink the task memory to reduce footprint of the task.
// Due to persistence it is possible that the process is cancelled after any step. This is
// ok, since the dirty flag won't be removed until step 3 and step 4 is only affecting the
// in-memory representation.
// The snapshot waits for this entire completion path, including its scoped child work,
// before it observes the graph.
// The task might be invalidated during this process, so we need to check the stale flag
// at the start of every step.
......@@ -2243,10 +2238,6 @@ impl TurboTasksBackend {
#[cfg(feature = "trace_task_details")]
span.record("output_dependents", output_dependent_tasks.len());
// When restoring from filesystem cache the following might not be executed (since we can
// suspend in `CleanupOldEdgesOperation`), but that's ok as the task is still dirty and
// would be executed again.
if !output_dependent_tasks.is_empty() {
self.task_execution_completed_invalidate_output_dependent(
&mut ctx,
......@@ -2571,19 +2562,21 @@ impl TurboTasksBackend {
feature = "trace_task_completion",
feature = "trace_aggregation_update_stats"
))]
let _span =
tracing::trace_span!("remove old edges and prepare new children", stats = Empty)
.entered();
let _span = tracing::trace_span!(
"remove old edges and prepare new children",
stats = tracing::field::Empty
)
.entered();
// Remove outdated edges first, before removing in_progress+dirty flag.
// We need to make sure all outdated edges are removed before the task can potentially
// be scheduled and executed again
#[cfg(feature = "trace_aggregation_update_stats")]
{
let stats = CleanupOldEdgesOperation::run(task_id, old_edges, queue, ctx);
let stats = cleanup_old_edges(task_id, old_edges, queue, ctx);
_span.record("stats", tracing::field::debug(stats));
}
#[cfg(not(feature = "trace_aggregation_update_stats"))]
CleanupOldEdgesOperation::run(task_id, old_edges, queue, ctx);
cleanup_old_edges(task_id, old_edges, queue, ctx);
}
Ok(TaskExecutionCompletePrepareResult {
......@@ -2958,6 +2951,27 @@ impl TurboTasksBackend {
removed_cell_data
}
/// Warns through the compilation event queue (so Next.js logs it) that a snapshot is still
/// waiting for active operations to finish.
fn report_slow_settle_for_snapshot(
turbo_tasks: &TurboTasks<TurboTasksBackend>,
slow: SlowSettle,
) {
let SlowSettle {
waited,
active_at_start,
active_now,
} = slow;
turbo_tasks.send_compilation_event(Arc::new(DiagnosticEvent::new(
Severity::Warning,
format!(
"Writing to the filesystem cache has been waiting {}s for active operations to \
finish ({active_at_start} active when it started, {active_now} active now)",
waited.as_secs(),
),
)));
}
/// Prints the standard message emitted when the background persisting process stops due to an
/// unrecoverable write error. The caller is responsible for returning from the background job.
fn log_unrecoverable_persist_error() {
......@@ -3106,7 +3120,15 @@ impl TurboTasksBackend {
Self::log_unrecoverable_persist_error();
return;
}
Ok((snapshot_start, new_data, _gc_outcome)) => {
Ok(None) => {
// An idle snapshot found operations in flight. Nothing was
// persisted, so keep the accumulated active time and scheduling
// state. Re-arm the idle timeout so we retry if we are still
// idle; otherwise the next idle period or interval picks it up.
fresh_idle = true;
continue 'outer;
}
Ok(Some((snapshot_start, new_data, _gc_outcome))) => {
// if we see 'new_data' then the next idle transition is 'fresh'
fresh_idle = new_data;
is_first = false;
......@@ -3365,7 +3387,7 @@ impl TurboTasksBackend {
verification_mode: VerificationMode,
turbo_tasks: &TurboTasks<TurboTasksBackend>,
) {
operation::UpdateCellOperation::run(
update_cell(
task_id,
cell,
content,
......@@ -3399,7 +3421,7 @@ impl TurboTasksBackend {
turbo_tasks: &TurboTasks<TurboTasksBackend>,
) {
self.assert_not_persistent_calling_transient(parent_task, task);
ConnectChildOperation::run(
connect_child(
parent_task,
task,
/* release_construction_ref */ false,
......@@ -3450,12 +3472,7 @@ impl TurboTasksBackend {
drop(task);
if !old_edges.is_empty() {
CleanupOldEdgesOperation::run(
task_id,
old_edges,
AggregationUpdateQueue::new(),
&mut ctx,
);
cleanup_old_edges(task_id, old_edges, AggregationUpdateQueue::new(), &mut ctx);
}
}
}
......
......@@ -4,7 +4,7 @@
//!
//! [`crate::backend::gc`] soft-deletes a task (`deleted` flag) and then removes all its outgoing
//! edges. For this to be correct all 'incoming edges' must be gone. However GC is a highly
//! concurrent process and an AggregationUpdateQueue may 'suspend' while GC is running. To assist
//! concurrent process. The snapshot waits for graph updates to finish before running GC. To assist
//! with GC aggregation updates need to be defensive about running on deleted tasks and also assist
//! GC by telling the context whenever an aggregation update queue operation may make a task
//! collectible (via [`ExecuteContext::note_maybe_collectible`] on `1->0` transitions), and also
......@@ -16,13 +16,12 @@ use std::{
hash::Hash,
mem::take,
num::NonZeroU32,
ops::{ControlFlow, Deref},
ops::ControlFlow,
thread::yield_now,
time::{Duration, Instant},
};
use anyhow::Result;
use bincode::{Decode, Encode};
use indexmap::map::Entry;
use ringmap::RingSet;
use rustc_hash::{FxBuildHasher, FxHashMap};
......@@ -42,7 +41,7 @@ use crate::{
backend::{
TaskDataCategory,
operation::{
ExecuteContext, Operation, TaskGuard,
ExecuteContext, TaskGuard,
connect_child::resurrect_deleted,
invalidate::{make_task_dirty, try_make_task_dirty},
},
......@@ -199,11 +198,9 @@ impl ComputeDirtyAndCleanUpdateResult {
}
}
#[derive(Encode, Decode, Clone, Debug)]
#[derive(Clone, Debug)]
pub struct InnerOfUppersHasNewFollowersJob {
#[bincode(with = "turbo_bincode::smallvec")]
pub upper_ids: TaskIdVec,
#[bincode(with = "turbo_bincode::smallvec")]
pub new_follower_ids: TaskIdVec,
}
......@@ -213,11 +210,9 @@ impl From<InnerOfUppersHasNewFollowersJob> for AggregationUpdateJob {
}
}
#[derive(Encode, Decode, Clone, Debug)]
#[derive(Clone, Debug)]
pub struct InnerOfUppersLostFollowersJob {
#[bincode(with = "turbo_bincode::smallvec")]
pub upper_ids: TaskIdVec,
#[bincode(with = "turbo_bincode::smallvec")]
pub lost_follower_ids: TaskIdVec,
}
......@@ -227,7 +222,7 @@ impl From<InnerOfUppersLostFollowersJob> for AggregationUpdateJob {
}
}
#[derive(Encode, Decode, Clone, Debug)]
#[derive(Clone, Debug)]
pub struct AggregatedDataUpdateJob {
pub upper_ids: TaskIdVec,
pub update: AggregatedDataUpdate,
......@@ -240,7 +235,7 @@ impl From<AggregatedDataUpdateJob> for AggregationUpdateJob {
}
/// A job in the job queue for updating something in the aggregated graph.
#[derive(Encode, Decode, Clone, Debug)]
#[derive(Clone, Debug)]
pub enum AggregationUpdateJob {
/// Update the aggregation number of a task. This might result in balancing needed to update
/// "upper" and "follower" edges.
......@@ -249,11 +244,6 @@ pub enum AggregationUpdateJob {
base_aggregation_number: u32,
distance: Option<NonZeroU32>,
},
/// Notifies an upper task that one of its inner tasks has a new follower.
InnerOfUpperHasNewFollower {
upper_id: TaskId,
new_follower_id: TaskId,
},
/// Notifies multiple upper tasks that one of its inner tasks has a new follower.
InnerOfUppersHasNewFollower {
upper_ids: TaskIdVec,
......@@ -299,12 +289,7 @@ pub enum AggregationUpdateJob {
/// Adjust the persistent `parent_count` of each task in `task_ids` by `delta`
AdjustParentCount { task_ids: TaskIdVec, delta: i32 },
/// Adjust the session-only `transient_ref_count` of each task in `task_ids` by `delta`
AdjustTransientRefCount {
#[bincode(skip, default = "unreachable_decode")]
task_ids: TaskIdVec,
#[bincode(skip, default = "unreachable_decode")]
delta: i32,
},
AdjustTransientRefCount { task_ids: TaskIdVec, delta: i32 },
/// Notifies an upper task about changed data from an inner task.
AggregatedDataUpdate(Box<AggregatedDataUpdateJob>),
/// Mark these tasks dirty because they have a dependency on a task being deleted by GC.
......@@ -320,37 +305,19 @@ pub enum AggregationUpdateJob {
},
/// Increases the active counter of the task
IncreaseActiveCount {
// TODO: bgw: Add a way to skip the entire enum variant in bincode (generating an error
// upon attempted serialization) similar to #[serde(skip)] on variants
#[bincode(skip, default = "unreachable_decode")]
task: TaskId,
release_construction_ref: bool,
},
/// Increases the active counters of the tasks
IncreaseActiveCounts {
#[bincode(skip, default = "unreachable_decode")]
task_ids: TaskIdVec,
},
IncreaseActiveCounts { task_ids: TaskIdVec },
/// Decreases the active counter of the task
DecreaseActiveCount {
#[bincode(skip, default = "unreachable_decode")]
task: TaskId,
},
DecreaseActiveCount { task: TaskId },
/// Decreases the active counters of the tasks
DecreaseActiveCounts {
#[bincode(skip, default = "unreachable_decode")]
task_ids: TaskIdVec,
},
DecreaseActiveCounts { task_ids: TaskIdVec },
/// Balances the edges of the graph. This checks if the graph invariant is still met for this
/// edge and coverts a upper edge to a follower edge or vice versa. Balancing might triggers
/// more changes to the structure.
BalanceEdge { upper_id: TaskId, task_id: TaskId },
/// Does nothing. This is used to filter out transient jobs during serialization.
Noop,
}
fn unreachable_decode<T>() -> T {
unreachable!("AggregatedDataUpdateJob variant should not have been encoded, cannot decode")
}
impl AggregationUpdateJob {
......@@ -373,34 +340,18 @@ impl AggregationUpdateJob {
}
}
#[derive(Default, Encode, Decode, Clone, Copy, Debug)]
#[bincode(decode_bounds = "T: Default", borrow_decode_bounds = "T: Default")]
pub struct SessionDependent<T> {
#[bincode(skip)]
pub value: T,
}
impl<T> SessionDependent<T> {
pub fn new(value: T) -> Self {
Self { value }
}
}
impl<T> Deref for SessionDependent<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
#[derive(Clone, Copy, Debug)]
struct DirtyContainerUpdate {
task_id: TaskId,
dirty_count: i32,
current_session_clean_count: i32,
}
/// Aggregated data update.
#[derive(Default, Encode, Decode, Clone, Debug)]
#[derive(Default, Clone, Debug)]
pub struct AggregatedDataUpdate {
/// One of the inner tasks has changed its dirty state or aggregated dirty state.
/// (task id, dirty update, current session clean update)
// TODO Serialize the current session clean update as 0
dirty_container_update: Option<(TaskId, i32, SessionDependent<i32>)>,
dirty_container_update: Option<DirtyContainerUpdate>,
/// One of the inner tasks has changed its collectibles count or aggregated collectibles count.
collectibles_update: Vec<(CollectibleRef, i32)>,
}
......@@ -458,9 +409,9 @@ impl AggregatedDataUpdate {
dirty_container_update,
collectibles_update,
} = &mut self;
if let Some((_, value, current_session_clean_update)) = dirty_container_update.as_mut() {
*value = -*value;
current_session_clean_update.value = -current_session_clean_update.value;
if let Some(update) = dirty_container_update.as_mut() {
update.dirty_count = -update.dirty_count;
update.current_session_clean_count = -update.current_session_clean_count;
}
for (_, value) in collectibles_update.iter_mut() {
*value = -*value;
......@@ -490,13 +441,16 @@ impl AggregatedDataUpdate {
collectibles_update,
} = self;
let mut result = Self::default();
if let &Some((dirty_container_id, count, current_session_clean_update)) =
dirty_container_update
if let &Some(DirtyContainerUpdate {
task_id: dirty_container_id,
dirty_count: count,
current_session_clean_count: current_session_clean_update,
}) = dirty_container_update
{
if should_track_activeness {
// When a dirty container count is increased and the task is considered as active
// we need to schedule the dirty tasks in the new dirty container
let current_session_update = count - *current_session_clean_update;
let current_session_update = count - current_session_clean_update;
if current_session_update > 0 && task.has_activeness() {
queue.push_find_and_schedule_dirty(dirty_container_id)
}
......@@ -525,15 +479,14 @@ impl AggregatedDataUpdate {
// Update AggregatedSessionDependentCleanContainer
let old_single_container_current_session_clean_count;
let new_single_container_current_session_clean_count;
if *current_session_clean_update != 0 {
if current_session_clean_update != 0 {
new_single_container_current_session_clean_count = task
.update_and_get_aggregated_current_session_clean_containers(
dirty_container_id,
*current_session_clean_update,
current_session_clean_update,
);
old_single_container_current_session_clean_count =
new_single_container_current_session_clean_count
- *current_session_clean_update;
new_single_container_current_session_clean_count - current_session_clean_update;
} else {
new_single_container_current_session_clean_count = task
.get_aggregated_current_session_clean_containers(&dirty_container_id)
......@@ -610,8 +563,8 @@ impl AggregatedDataUpdate {
if let Some(aggregated_update) = compute_result.aggregated_update(task_id) {
result = aggregated_update;
if let Some((_, count, current_session_clean)) = result.dirty_container_update
&& count - *current_session_clean < 0
if let Some(update) = result.dirty_container_update
&& update.dirty_count - update.current_session_clean_count < 0
{
// When the current task is no longer dirty, we need to fire the
// aggregate root events and do some cleanup
......@@ -686,11 +639,11 @@ impl AggregatedDataUpdate {
count: i32,
current_session_clean_update: i32,
) -> Self {
self.dirty_container_update = Some((
self.dirty_container_update = Some(DirtyContainerUpdate {
task_id,
count,
SessionDependent::new(current_session_clean_update),
));
dirty_count: count,
current_session_clean_count: current_session_clean_update,
});
self
}
......@@ -702,21 +655,19 @@ impl AggregatedDataUpdate {
}
/// An aggregation number update job that is enqueued.
#[derive(Encode, Decode, Clone)]
#[derive(Clone)]
struct AggregationNumberUpdate {
base_aggregation_number: u32,
distance: Option<NonZeroU32>,
#[cfg(feature = "trace_aggregation_update_queue")]
#[bincode(skip)]
span: Option<Span>,
}
/// An aggregated data update job that is enqueued. See `AggregatedDataUpdate`.
#[derive(Encode, Decode, Clone)]
#[derive(Clone)]
struct AggregationUpdateJobItem {
job: AggregationUpdateJob,
#[cfg(feature = "trace_aggregation_update_queue")]
#[bincode(skip)]
span: Option<Span>,
}
......@@ -745,12 +696,11 @@ struct AggregationUpdateJobGuard {
}
/// A balancing job that is enqueued. See `balance_edge`.
#[derive(Encode, Decode, Clone)]
#[derive(Clone)]
struct BalanceJob {
upper_id: TaskId,
task_id: TaskId,
#[cfg(feature = "trace_aggregation_update_queue")]
#[bincode(skip)]
span: Option<Span>,
}
......@@ -781,7 +731,7 @@ impl PartialEq for BalanceJob {
impl Eq for BalanceJob {}
/// An optimization job that is enqueued. See `optimize_task`.
#[derive(Encode, Decode, Clone)]
#[derive(Clone)]
struct OptimizeJob {
task_id: TaskId,
/// Whether the `optimization_pending` flag was known to already be set on the task at
......@@ -805,7 +755,6 @@ struct OptimizeJob {
/// performed. Skipping the flag set is exactly what we want.
optimization_pending_flag_already_set: bool,
#[cfg(feature = "trace_aggregation_update_queue")]
#[bincode(skip)]
span: Option<Span>,
}
......@@ -835,11 +784,10 @@ impl PartialEq for OptimizeJob {
impl Eq for OptimizeJob {}
/// A job to find and schedule dirty tasks that is enqueued. See `find_and_schedule_dirty`.
#[derive(Encode, Decode, Clone)]
#[derive(Clone)]
struct FindAndScheduleJob {
task_id: TaskId,
#[cfg(feature = "trace_find_and_schedule")]
#[bincode(skip)]
span: Option<Span>,
}
......@@ -868,7 +816,7 @@ impl PartialEq for FindAndScheduleJob {
impl Eq for FindAndScheduleJob {}
#[cfg(feature = "trace_aggregation_update_stats")]
#[derive(Default, Encode, Decode, Clone, Debug)]
#[derive(Default, Debug)]
pub struct AggregationUpdateQueueStats {
new_followers: usize,
inner_of_upper_has_new_follower: usize,
......@@ -878,8 +826,6 @@ pub struct AggregationUpdateQueueStats {
inner_of_upper_lost_follower: usize,
inner_of_upper_lost_followers: usize,
inner_of_uppers_lost_follower: usize,
increase_active_count: usize,
decrease_active_count: usize,
balance_edge: usize,
balance_edge_batches: usize,
update_aggregation_number: usize,
......@@ -891,82 +837,18 @@ pub struct AggregationUpdateQueueStats {
schedule_task: usize,
}
/// Encodes the jobs in the queue. This is used to filter out transient jobs during encoding.
mod encode_jobs {
use bincode::{
de::{BorrowDecoder, Decoder},
enc::Encoder,
error::{DecodeError, EncodeError},
};
use super::*;
pub fn encode<E: Encoder>(
jobs: &VecDeque<AggregationUpdateJobItem>,
encoder: &mut E,
) -> Result<(), EncodeError> {
usize::encode(&jobs.len(), encoder)?;
for job in jobs {
match job.job {
AggregationUpdateJob::IncreaseActiveCount { .. }
| AggregationUpdateJob::IncreaseActiveCounts { .. }
| AggregationUpdateJob::DecreaseActiveCount { .. }
| AggregationUpdateJob::DecreaseActiveCounts { .. }
| AggregationUpdateJob::AdjustTransientRefCount { .. } => {
AggregationUpdateJobItem {
job: AggregationUpdateJob::Noop,
#[cfg(feature = "trace_aggregation_update_queue")]
span: None,
}
.encode(encoder)?;
}
_ => {
job.encode(encoder)?;
}
}
}
Ok(())
}
pub fn decode<Context, D: Decoder<Context = Context>>(
decoder: &mut D,
) -> Result<VecDeque<AggregationUpdateJobItem>, DecodeError> {
let len = usize::decode(decoder)?;
let mut jobs = VecDeque::with_capacity(len);
for _ in 0..len {
jobs.push_back(Decode::decode(decoder)?);
}
Ok(jobs)
}
pub fn borrow_decode<'de, Context, D: BorrowDecoder<'de, Context = Context>>(
decoder: &mut D,
) -> Result<VecDeque<AggregationUpdateJobItem>, DecodeError> {
decode(decoder)
}
}
/// A queue for aggregation update jobs.
#[derive(Default, Encode, Decode, Clone)]
#[derive(Default)]
pub struct AggregationUpdateQueue {
#[bincode(with = "encode_jobs")]
jobs: VecDeque<AggregationUpdateJobItem>,
#[bincode(with = "turbo_bincode::indexmap")]
aggregation_number_updates: FxIndexMap<TaskId, AggregationNumberUpdate>,
done_aggregation_number_updates: FxHashMap<TaskId, AggregationNumberUpdate>,
#[bincode(with = "turbo_bincode::ringset")]
find_and_schedule: FxRingSet<FindAndScheduleJob>,
#[bincode(with = "turbo_bincode::ringset")]
balance_queue: FxRingSet<BalanceJob>,
#[bincode(with = "turbo_bincode::ringset")]
optimize_queue: FxRingSet<OptimizeJob>,
/// Number of optimizations executed by this queue so far. See
/// `MAX_OPTIMIZATIONS_PER_QUEUE`. Persisted with the queue so the budget is preserved
/// across suspend/resume — otherwise resuming a queue would reset the budget and a long
/// operation could perform arbitrarily many optimizations by going through several
/// suspend/resume cycles.
/// `MAX_OPTIMIZATIONS_PER_QUEUE`.
optimizations_executed: usize,
#[bincode(skip, default = "FxHashMap::default")]
scheduled_tasks: FxHashMap<TaskId, TaskPriority>,
#[cfg(feature = "trace_aggregation_update_stats")]
pub stats: AggregationUpdateQueueStats,
......@@ -1177,8 +1059,7 @@ impl AggregationUpdateQueue {
let _ = self.try_enqueue_optimize_job(task.id(), true);
}
/// Runs the job and all dependent jobs until it's done. It can persist the operation, so
/// following code might not be executed when persisted.
/// Runs the job and all dependent jobs until it's done.
pub fn run(job: AggregationUpdateJob, ctx: &mut impl ExecuteContext<'_>) {
let mut queue = Self::new();
queue.push(job);
......@@ -1216,7 +1097,7 @@ impl AggregationUpdateQueue {
/// Takes the deferred balance edges, leaving the queue empty of them.
///
/// Only meaningful for a queue stopped at the rebalance boundary; see
/// [`CleanupOldEdgesOperation::run_edge_deletions_only`], which is the only caller.
/// [`super::cleanup_old_edges_deletions_only`], which is the only caller.
pub(super) fn take_deferred_balance_edges(
&mut self,
) -> impl Iterator<Item = (TaskId, TaskId)> + use<> {
......@@ -1258,7 +1139,6 @@ impl AggregationUpdateQueue {
if let Some(job) = self.jobs.pop_front() {
let job: AggregationUpdateJobGuard = job.entered();
match job.job {
AggregationUpdateJob::Noop => {}
AggregationUpdateJob::UpdateAggregationNumber { .. }
| AggregationUpdateJob::BalanceEdge { .. } => {
// These jobs are never pushed to the queue
......@@ -1401,17 +1281,6 @@ impl AggregationUpdateQueue {
self.inner_of_upper_has_new_followers(ctx, new_follower_ids, upper_id);
}
}
AggregationUpdateJob::InnerOfUpperHasNewFollower {
upper_id,
new_follower_id,
} => {
#[cfg(feature = "trace_aggregation_update_stats")]
{
self.stats.new_followers += 1;
self.stats.inner_of_upper_has_new_follower += 1;
}
self.inner_of_upper_has_new_follower(ctx, new_follower_id, upper_id, 1);
}
AggregationUpdateJob::InnerOfUpperLostFollower {
lost_follower_id,
upper_id,
......@@ -3390,7 +3259,7 @@ impl AggregationUpdateQueue {
// For performance reasons this should stay `Meta` and not `All`
AGGREGATION_UPDATE_CATEGORY,
);
// Skip deleted tasks, GC can run during suspend points of aggregation updates
// Skip deleted tasks, which can be encountered while processing GC's deferred cleanup.
// This just means there is no point in rebalancing the subgraph here since this 'root' is
// dead.
if task.deleted() {
......@@ -3624,26 +3493,17 @@ impl AggregationUpdateQueue {
#[cfg(feature = "trace_aggregation_update_stats")]
pub fn execute_with_stats(
mut self,
&mut self,
ctx: &mut impl ExecuteContext<'_>,
) -> AggregationUpdateQueueStats {
loop {
ctx.operation_suspend_point(&self);
if self.process(ctx) {
return self.stats;
}
}
while !self.process(ctx) {}
take(&mut self.stats)
}
}
impl Operation for AggregationUpdateQueue {
fn execute(mut self, ctx: &mut impl ExecuteContext<'_>) {
loop {
ctx.operation_suspend_point(&self);
if self.process(ctx) {
return;
}
}
impl AggregationUpdateQueue {
pub fn execute(&mut self, ctx: &mut impl ExecuteContext<'_>) {
while !self.process(ctx) {}
}
}
......
use std::mem::take;
use auto_hash_map::AutoSet;
use bincode::{Decode, Encode};
use rustc_hash::{FxBuildHasher, FxHashSet};
use smallvec::SmallVec;
use turbo_tasks::TaskId;
......@@ -10,7 +9,7 @@ use crate::{
backend::{
TaskDataCategory,
operation::{
AggregatedDataUpdate, ExecuteContext, Operation,
AggregatedDataUpdate, ExecuteContext,
aggregation_update::{
AggregationUpdateJob, AggregationUpdateQueue, InnerOfUppersLostFollowersJob,
get_aggregation_number, get_uppers, is_aggregating_node,
......@@ -21,31 +20,6 @@ use crate::{
data::{CellRef, CollectibleRef, CollectiblesRef},
};
#[derive(Encode, Decode, Clone)]
pub enum CleanupOldEdgesOperation {
RemoveEdges {
task_id: TaskId,
outdated: Vec<OutdatedEdge>,
queue: AggregationUpdateQueue,
},
AggregationUpdate {
queue: AggregationUpdateQueue,
},
Done {
stats: Stats,
},
// TODO Add aggregated edge
}
impl Default for CleanupOldEdgesOperation {
fn default() -> Self {
Self::Done {
stats: Default::default(),
}
}
}
#[derive(Encode, Decode, Clone)]
pub enum OutdatedEdge {
Child(TaskId),
Collectible(CollectibleRef, i32),
......@@ -113,340 +87,294 @@ pub struct DeferredCleanup {
pub dirty_dependents: AutoSet<TaskId, FxBuildHasher, 2>,
}
impl CleanupOldEdgesOperation {
pub fn run(
task_id: TaskId,
outdated: Vec<OutdatedEdge>,
queue: AggregationUpdateQueue,
ctx: &mut impl ExecuteContext<'_>,
) -> Stats {
CleanupOldEdgesOperation::RemoveEdges {
task_id,
outdated,
queue,
}
.execute_with_stats(ctx)
}
/// GC variant: tears down `outdated`, running only the edge deletions.
///
/// Returns the work the deletions produced but did not run, for the caller to replay once the
/// parallel collect is quiescent. Deletion is safe to run concurrently; the deferred work is
/// not. `balance_edge` *adds* edges, and dirtying propagates through the aggregation graph --
/// neither is safe while other workers are still collecting.
pub fn run_edge_deletions_only<'a, C: ExecuteContext<'a>>(
task_id: TaskId,
outdated: Vec<OutdatedEdge>,
ctx: &mut C,
) -> DeferredCleanup {
let op = CleanupOldEdgesOperation::RemoveEdges {
task_id,
outdated,
queue: AggregationUpdateQueue::new_without_optimizations(),
};
let (_, stopped) = op.execute_inner(ctx, true);
// the option must be Some when stop_when_only_rebalance
stopped.unwrap()
}
fn execute_with_stats(self, ctx: &mut impl ExecuteContext<'_>) -> Stats {
self.execute_inner(ctx, false).0
}
pub fn cleanup_old_edges(
task_id: TaskId,
outdated: Vec<OutdatedEdge>,
queue: AggregationUpdateQueue,
ctx: &mut impl ExecuteContext<'_>,
) -> Stats {
cleanup_old_edges_inner(task_id, outdated, queue, ctx, false).0
}
fn execute_inner(
mut self,
ctx: &mut impl ExecuteContext<'_>,
stop_when_only_rebalance_remains: bool,
) -> (Stats, Option<DeferredCleanup>) {
let mut dirty_dependents = AutoSet::default();
loop {
ctx.operation_suspend_point(&self);
match self {
CleanupOldEdgesOperation::RemoveEdges {
task_id,
ref mut outdated,
ref mut queue,
} => {
if let Some(edge) = outdated.pop() {
match edge {
OutdatedEdge::Child(child_id) => {
let mut children = SmallVec::new();
children.push(child_id);
outdated.retain(|e| match e {
OutdatedEdge::Child(id) => {
children.push(*id);
false
}
_ => true,
});
let mut task = ctx.task(task_id, TaskDataCategory::All);
/// GC variant: tears down `outdated`, running only the edge deletions.
///
/// Returns the work the deletions produced but did not run, for the caller to replay once the
/// parallel collect is quiescent. Deletion is safe to run concurrently; the deferred work is
/// not. `balance_edge` *adds* edges, and dirtying propagates through the aggregation graph --
/// neither is safe while other workers are still collecting.
pub fn cleanup_old_edges_deletions_only<'a, C: ExecuteContext<'a>>(
task_id: TaskId,
outdated: Vec<OutdatedEdge>,
ctx: &mut C,
) -> DeferredCleanup {
let (_, stopped) = cleanup_old_edges_inner(
task_id,
outdated,
AggregationUpdateQueue::new_without_optimizations(),
ctx,
true,
);
// the option must be Some when stop_when_only_rebalance
stopped.unwrap()
}
// Mirror `ConnectChildrenOperation`'s split exactly: an edge
// counted as durable is released from `parent_count`, everything
// else from `transient_ref_count`. Getting this wrong either
// strands a task forever or underflows the count.
let parent_is_transient = task_id.is_transient();
let mut removed_durable = SmallVec::<[TaskId; 4]>::new();
let mut removed_transient = SmallVec::<[TaskId; 4]>::new();
children.retain(|child_id| {
if task.remove_children(child_id) {
if parent_is_transient || child_id.is_transient() {
removed_transient.push(*child_id);
} else {
removed_durable.push(*child_id);
}
true
} else {
false
}
});
if !removed_durable.is_empty() {
queue.push(AggregationUpdateJob::AdjustParentCount {
task_ids: removed_durable,
delta: -1,
});
}
if !removed_transient.is_empty() {
queue.push(AggregationUpdateJob::AdjustTransientRefCount {
task_ids: removed_transient,
delta: -1,
});
}
if is_aggregating_node(get_aggregation_number(&task)) {
drop(task);
queue.push(AggregationUpdateJob::InnerOfUpperLostFollowers {
upper_id: task_id,
lost_follower_ids: children,
retry: 0,
});
} else {
let upper_ids = get_uppers(&task);
let has_active_count = ctx.should_track_activeness()
&& task
.get_activeness()
.is_some_and(|a| a.active_counter > 0);
drop(task);
if has_active_count {
// TODO combine both operations to avoid the clone
queue.push(AggregationUpdateJob::DecreaseActiveCounts {
task_ids: children.clone(),
});
}
queue.push(
InnerOfUppersLostFollowersJob {
upper_ids,
lost_follower_ids: children,
}
.into(),
);
}
}
OutdatedEdge::Collectible(collectible, count) => {
let mut collectibles = Vec::new();
collectibles.push((collectible, -count));
outdated.retain(|e| match e {
OutdatedEdge::Collectible(collectible, count) => {
collectibles.push((*collectible, -*count));
false
}
_ => true,
});
let mut task = ctx.task(task_id, TaskDataCategory::All);
let mut emptied_collectables = FxHashSet::default();
for (collectible, count) in collectibles.iter_mut() {
if task
.update_collectibles_positive_crossing(*collectible, *count)
{
emptied_collectables.insert(collectible.collectible_type);
}
}
fn cleanup_old_edges_inner(
task_id: TaskId,
mut outdated: Vec<OutdatedEdge>,
mut queue: AggregationUpdateQueue,
ctx: &mut impl ExecuteContext<'_>,
stop_when_only_rebalance_remains: bool,
) -> (Stats, Option<DeferredCleanup>) {
let mut dirty_dependents = AutoSet::default();
while let Some(edge) = outdated.pop() {
match edge {
OutdatedEdge::Child(child_id) => {
let mut children = SmallVec::new();
children.push(child_id);
outdated.retain(|e| match e {
OutdatedEdge::Child(id) => {
children.push(*id);
false
}
_ => true,
});
let mut task = ctx.task(task_id, TaskDataCategory::All);
for ty in emptied_collectables {
let task_ids: SmallVec<[_; 4]> = task
.iter_collectibles_dependents()
.filter_map(|(collectible_type, task)| {
(collectible_type == ty).then_some(task)
})
.collect();
queue.push(
AggregationUpdateJob::InvalidateDueToCollectiblesChange {
task_ids,
#[cfg(feature = "task_dirty_cause")]
collectible_type: ty,
},
);
}
queue.extend(AggregationUpdateJob::data_update(
&mut task,
AggregatedDataUpdate::new().collectibles_update(collectibles),
));
}
OutdatedEdge::CellDependency(forward) => {
let CellRef {
task: cell_task_id,
cell,
} = forward;
{
let mut task = ctx.task(cell_task_id, TaskDataCategory::Data);
task.remove_cell_dependents(&CellRef {
task: task_id,
cell,
});
}
{
let mut task = ctx.task(task_id, TaskDataCategory::Data);
task.remove_cell_dependencies(&forward);
}
}
OutdatedEdge::HashedCellDependency(forward, key) => {
// ame as above but in the `_hashed` sets.
let CellRef {
task: cell_task_id,
cell,
} = forward;
{
let mut task = ctx.task(cell_task_id, TaskDataCategory::Data);
task.remove_cell_dependents_hashed(&(
CellRef {
task: task_id,
cell,
},
key,
));
}
{
let mut task = ctx.task(task_id, TaskDataCategory::Data);
task.remove_cell_dependencies_hashed(&(forward, key));
}
}
OutdatedEdge::OutputDependency(output_task_id) => {
#[cfg(feature = "trace_task_output_dependencies")]
let _span = tracing::trace_span!(
"remove output dependency",
task = %output_task_id,
dependent_task = %task_id
)
.entered();
{
let mut task = ctx.task(output_task_id, TaskDataCategory::Data);
task.remove_output_dependent(&task_id);
}
{
let mut task = ctx.task(task_id, TaskDataCategory::Data);
task.remove_output_dependencies(&output_task_id);
}
}
OutdatedEdge::CollectiblesDependency(CollectiblesRef {
collectible_type,
task: dependent_task_id,
}) => {
{
let mut task =
ctx.task(dependent_task_id, TaskDataCategory::Meta);
task.remove_collectibles_dependents(&(
collectible_type,
task_id,
));
}
{
let mut task = ctx.task(task_id, TaskDataCategory::Data);
task.remove_collectibles_dependencies(&CollectiblesRef {
collectible_type,
task: dependent_task_id,
});
}
}
// Handle reverse edges, we remove these when `task_id` is being
// deleted. The reverse dependents must exist and we dirty them as we
// go. We also don't bother removing cell_dependents from `task_id`
// since that task is being deleted.
OutdatedEdge::CellDependentOfDeleted(CellRef {
task: dependent_task_id,
cell,
}) => {
// Orientation flip: the stored entry names the dependent, the
// forward entry we remove names `task_id`.
let forward = CellRef {
task: task_id,
cell,
};
let mut task = ctx.task(dependent_task_id, TaskDataCategory::Data);
task.remove_cell_dependencies(&forward);
task.remove_outdated_cell_dependencies(&forward);
drop(task);
dirty_dependents.insert(dependent_task_id);
}
OutdatedEdge::HashedCellDependentOfDeleted(
CellRef {
task: dependent_task_id,
cell,
},
key,
) => {
let forward = CellRef {
task: task_id,
cell,
};
let mut task = ctx.task(dependent_task_id, TaskDataCategory::Data);
task.remove_cell_dependencies_hashed(&(forward, key));
task.remove_outdated_cell_dependencies_hashed(&(forward, key));
drop(task);
dirty_dependents.insert(dependent_task_id);
}
OutdatedEdge::OutputDependentOfDeleted(dependent_task_id) => {
let mut task = ctx.task(dependent_task_id, TaskDataCategory::Data);
task.remove_output_dependencies(&task_id);
task.remove_outdated_output_dependencies(&task_id);
drop(task);
dirty_dependents.insert(dependent_task_id);
}
// Mirror `ConnectChildrenOperation`'s split exactly: an edge
// counted as durable is released from `parent_count`, everything
// else from `transient_ref_count`. Getting this wrong either
// strands a task forever or underflows the count.
let parent_is_transient = task_id.is_transient();
let mut removed_durable = SmallVec::<[TaskId; 4]>::new();
let mut removed_transient = SmallVec::<[TaskId; 4]>::new();
children.retain(|child_id| {
if task.remove_children(child_id) {
if parent_is_transient || child_id.is_transient() {
removed_transient.push(*child_id);
} else {
removed_durable.push(*child_id);
}
true
} else {
false
}
// If we accumulated any dirty_dependents flush them to the aggregation update
// queue before suspending.
if !stop_when_only_rebalance_remains && !dirty_dependents.is_empty() {
queue.push(AggregationUpdateJob::InvalidateDueToDependencyTornDown {
task_ids: take(&mut dirty_dependents).into_iter().collect(),
});
if !removed_durable.is_empty() {
queue.push(AggregationUpdateJob::AdjustParentCount {
task_ids: removed_durable,
delta: -1,
});
}
if !removed_transient.is_empty() {
queue.push(AggregationUpdateJob::AdjustTransientRefCount {
task_ids: removed_transient,
delta: -1,
});
}
if is_aggregating_node(get_aggregation_number(&task)) {
drop(task);
queue.push(AggregationUpdateJob::InnerOfUpperLostFollowers {
upper_id: task_id,
lost_follower_ids: children,
retry: 0,
});
} else {
let upper_ids = get_uppers(&task);
let has_active_count = ctx.should_track_activeness()
&& task.get_activeness().is_some_and(|a| a.active_counter > 0);
drop(task);
if has_active_count {
// TODO combine both operations to avoid the clone
queue.push(AggregationUpdateJob::DecreaseActiveCounts {
task_ids: children.clone(),
});
}
if outdated.is_empty() {
self = CleanupOldEdgesOperation::AggregationUpdate { queue: take(queue) };
}
queue.push(
InnerOfUppersLostFollowersJob {
upper_ids,
lost_follower_ids: children,
}
.into(),
);
}
CleanupOldEdgesOperation::AggregationUpdate { ref mut queue } => {
if stop_when_only_rebalance_remains && queue.only_rebalance_remains() {
// Edge removal is done; hand the rebalance back to the caller. Any
// other pending work would be dropped here, so `only_rebalance_remains`
// asserts that nothing else is left.
return (
Default::default(),
Some(DeferredCleanup {
balance_edges: queue.take_deferred_balance_edges().collect(),
dirty_dependents,
}),
);
}
OutdatedEdge::Collectible(collectible, count) => {
let mut collectibles = Vec::new();
collectibles.push((collectible, -count));
outdated.retain(|e| match e {
OutdatedEdge::Collectible(collectible, count) => {
collectibles.push((*collectible, -*count));
false
}
if queue.process(ctx) {
self = CleanupOldEdgesOperation::Done {
#[cfg(feature = "trace_aggregation_update_stats")]
stats: take(&mut queue.stats),
#[cfg(not(feature = "trace_aggregation_update_stats"))]
stats: (),
};
_ => true,
});
let mut task = ctx.task(task_id, TaskDataCategory::All);
let mut emptied_collectables = FxHashSet::default();
for (collectible, count) in collectibles.iter_mut() {
if task.update_collectibles_positive_crossing(*collectible, *count) {
emptied_collectables.insert(collectible.collectible_type);
}
}
CleanupOldEdgesOperation::Done { stats } => {
return (stats, None);
for ty in emptied_collectables {
let task_ids: SmallVec<[_; 4]> = task
.iter_collectibles_dependents()
.filter_map(|(collectible_type, task)| {
(collectible_type == ty).then_some(task)
})
.collect();
queue.push(AggregationUpdateJob::InvalidateDueToCollectiblesChange {
task_ids,
#[cfg(feature = "task_dirty_cause")]
collectible_type: ty,
});
}
queue.extend(AggregationUpdateJob::data_update(
&mut task,
AggregatedDataUpdate::new().collectibles_update(collectibles),
));
}
OutdatedEdge::CellDependency(forward) => {
let CellRef {
task: cell_task_id,
cell,
} = forward;
{
let mut task = ctx.task(cell_task_id, TaskDataCategory::Data);
task.remove_cell_dependents(&CellRef {
task: task_id,
cell,
});
}
{
let mut task = ctx.task(task_id, TaskDataCategory::Data);
task.remove_cell_dependencies(&forward);
}
}
OutdatedEdge::HashedCellDependency(forward, key) => {
// ame as above but in the `_hashed` sets.
let CellRef {
task: cell_task_id,
cell,
} = forward;
{
let mut task = ctx.task(cell_task_id, TaskDataCategory::Data);
task.remove_cell_dependents_hashed(&(
CellRef {
task: task_id,
cell,
},
key,
));
}
{
let mut task = ctx.task(task_id, TaskDataCategory::Data);
task.remove_cell_dependencies_hashed(&(forward, key));
}
}
OutdatedEdge::OutputDependency(output_task_id) => {
#[cfg(feature = "trace_task_output_dependencies")]
let _span = tracing::trace_span!(
"remove output dependency",
task = %output_task_id,
dependent_task = %task_id
)
.entered();
{
let mut task = ctx.task(output_task_id, TaskDataCategory::Data);
task.remove_output_dependent(&task_id);
}
{
let mut task = ctx.task(task_id, TaskDataCategory::Data);
task.remove_output_dependencies(&output_task_id);
}
}
OutdatedEdge::CollectiblesDependency(CollectiblesRef {
collectible_type,
task: dependent_task_id,
}) => {
{
let mut task = ctx.task(dependent_task_id, TaskDataCategory::Meta);
task.remove_collectibles_dependents(&(collectible_type, task_id));
}
{
let mut task = ctx.task(task_id, TaskDataCategory::Data);
task.remove_collectibles_dependencies(&CollectiblesRef {
collectible_type,
task: dependent_task_id,
});
}
}
// Handle reverse edges, we remove these when `task_id` is being
// deleted. The reverse dependents must exist and we dirty them as we
// go. We also don't bother removing cell_dependents from `task_id`
// since that task is being deleted.
OutdatedEdge::CellDependentOfDeleted(CellRef {
task: dependent_task_id,
cell,
}) => {
// Orientation flip: the stored entry names the dependent, the
// forward entry we remove names `task_id`.
let forward = CellRef {
task: task_id,
cell,
};
let mut task = ctx.task(dependent_task_id, TaskDataCategory::Data);
task.remove_cell_dependencies(&forward);
task.remove_outdated_cell_dependencies(&forward);
drop(task);
dirty_dependents.insert(dependent_task_id);
}
OutdatedEdge::HashedCellDependentOfDeleted(
CellRef {
task: dependent_task_id,
cell,
},
key,
) => {
let forward = CellRef {
task: task_id,
cell,
};
let mut task = ctx.task(dependent_task_id, TaskDataCategory::Data);
task.remove_cell_dependencies_hashed(&(forward, key));
task.remove_outdated_cell_dependencies_hashed(&(forward, key));
drop(task);
dirty_dependents.insert(dependent_task_id);
}
OutdatedEdge::OutputDependentOfDeleted(dependent_task_id) => {
let mut task = ctx.task(dependent_task_id, TaskDataCategory::Data);
task.remove_output_dependencies(&task_id);
task.remove_outdated_output_dependencies(&task_id);
drop(task);
dirty_dependents.insert(dependent_task_id);
}
}
// Flush accumulated dirty dependents to the aggregation update queue.
if !stop_when_only_rebalance_remains && !dirty_dependents.is_empty() {
queue.push(AggregationUpdateJob::InvalidateDueToDependencyTornDown {
task_ids: take(&mut dirty_dependents).into_iter().collect(),
});
}
}
}
impl Operation for CleanupOldEdgesOperation {
fn execute(self, ctx: &mut impl ExecuteContext<'_>) {
self.execute_with_stats(ctx);
while !stop_when_only_rebalance_remains || !queue.only_rebalance_remains() {
if queue.process(ctx) {
#[cfg(feature = "trace_aggregation_update_stats")]
let stats = take(&mut queue.stats);
#[cfg(not(feature = "trace_aggregation_update_stats"))]
let stats = ();
return (stats, None);
}
}
// Edge removal is done; hand the rebalance back to the caller. Any
// other pending work would be dropped here, so `only_rebalance_remains`
// asserts that nothing else is left.
(
Default::default(),
Some(DeferredCleanup {
balance_edges: queue.take_deferred_balance_edges().collect(),
dirty_dependents,
}),
)
}
use bincode::{Decode, Encode};
use turbo_tasks::{TaskExecutionReason, TaskId, event::EventDescription};
use crate::{
backend::{
TaskDataCategory,
operation::{
ExecuteContext, Operation, TaskGuard,
ExecuteContext, TaskGuard,
aggregation_update::{
AggregationUpdateJob, AggregationUpdateQueue, get_aggregation_number, is_root_node,
},
......@@ -70,171 +69,134 @@ fn release_construction_ref<'e, C: ExecuteContext<'e>>(task_id: TaskId, ctx: &mu
task.update_and_get_transient_ref_count(-1);
}
#[derive(Encode, Decode, Clone, Default)]
#[allow(clippy::large_enum_variant)]
pub enum ConnectChildOperation {
UpdateAggregation {
aggregation_update: AggregationUpdateQueue,
},
#[default]
Done,
}
impl ConnectChildOperation {
pub fn run(
parent_task_id: Option<TaskId>,
child_task_id: TaskId,
release_construction_ref: bool,
mut ctx: impl ExecuteContext<'_>,
) {
if parent_task_id.is_none() {
// All parentless tasks receive a transient ref when connected: their lifetime cannot be
// constrained by turbo-tasks and needs to be managed by the caller. If the caller
// doesn't manage it, the GC root TTL handles it in a later session.
let mut child_task = ctx.task_or_create(child_task_id, TaskDataCategory::Meta);
child_task.update_and_get_transient_ref_count(1);
pub fn connect_child(
parent_task_id: Option<TaskId>,
child_task_id: TaskId,
release_construction_ref: bool,
mut ctx: impl ExecuteContext<'_>,
) {
if parent_task_id.is_none() {
// All parentless tasks receive a transient ref when connected: their lifetime cannot be
// constrained by turbo-tasks and needs to be managed by the caller. If the caller
// doesn't manage it, the GC root TTL handles it in a later session.
let mut child_task = ctx.task_or_create(child_task_id, TaskDataCategory::Meta);
child_task.update_and_get_transient_ref_count(1);
}
if let Some(parent_task_id) = parent_task_id {
let mut parent_task = ctx.task(parent_task_id, TaskDataCategory::Meta);
let Some(InProgressState::InProgress(InProgressStateInner { new_children, .. })) =
parent_task.get_in_progress()
else {
panic!("Task is not in progress while calling another task: {parent_task:?}");
};
// Quick skip if the child was already connected before
// We defer the insert until after the aggregation queue is processed.
if new_children.contains(&child_task_id) {
drop(parent_task);
if release_construction_ref {
self::release_construction_ref(child_task_id, &mut ctx);
}
return;
}
if let Some(parent_task_id) = parent_task_id {
let mut parent_task = ctx.task(parent_task_id, TaskDataCategory::Meta);
if parent_task.children_contains(&child_task_id) {
// It is already connected, we can skip the rest
// but we still need to update the new_children set
let Some(InProgressState::InProgress(InProgressStateInner { new_children, .. })) =
parent_task.get_in_progress()
parent_task.get_in_progress_mut()
else {
panic!("Task is not in progress while calling another task: {parent_task:?}");
unreachable!();
};
// Quick skip if the child was already connected before
// We defer the insert until after the aggregation queue is processed.
if new_children.contains(&child_task_id) {
drop(parent_task);
if release_construction_ref {
self::release_construction_ref(child_task_id, &mut ctx);
}
return;
}
if parent_task.children_contains(&child_task_id) {
// It is already connected, we can skip the rest
// but we still need to update the new_children set
let Some(InProgressState::InProgress(InProgressStateInner {
new_children, ..
})) = parent_task.get_in_progress_mut()
else {
unreachable!();
};
new_children.insert(child_task_id);
drop(parent_task);
if release_construction_ref {
self::release_construction_ref(child_task_id, &mut ctx);
}
return;
new_children.insert(child_task_id);
drop(parent_task);
if release_construction_ref {
self::release_construction_ref(child_task_id, &mut ctx);
}
return;
}
}
let mut queue = AggregationUpdateQueue::new();
let mut queue = AggregationUpdateQueue::new();
// Handle the transient to persistent boundary by making the persistent task a root task.
let should_make_root =
parent_task_id.is_none_or(|id| id.is_transient() && !child_task_id.is_transient());
// Handle the transient to persistent boundary by making the persistent task a root task.
let should_make_root =
parent_task_id.is_none_or(|id| id.is_transient() && !child_task_id.is_transient());
if ctx.should_track_activeness() && parent_task_id.is_some() {
if should_make_root {
queue.push(AggregationUpdateJob::UpdateAggregationNumber {
task_id: child_task_id,
base_aggregation_number: u32::MAX,
distance: None,
});
}
queue.push(AggregationUpdateJob::IncreaseActiveCount {
task: child_task_id,
release_construction_ref,
if ctx.should_track_activeness() && parent_task_id.is_some() {
if should_make_root {
queue.push(AggregationUpdateJob::UpdateAggregationNumber {
task_id: child_task_id,
base_aggregation_number: u32::MAX,
distance: None,
});
} else {
// First connect of this child: its id is minted but the storage entry may not exist
// yet, and concurrent connects race to be the one that first touches it.
let child_task = ctx.task_or_create(child_task_id, TaskDataCategory::Meta);
// Revive the child if GC soft-deleted it. This can happen in a rare race between a
// cache hit on a task and snapshotting actually performing the delete.
let mut child_task = resurrect_deleted(child_task, child_task_id, &mut queue, &mut ctx);
let has_output = child_task.has_output();
// An already constructed top-level task was made a root when it was first connected.
// It may still be dirty and need to run; this only avoids repeating the idempotent
// aggregation update.
let is_already_constructed_root = parent_task_id.is_none()
&& has_output
&& is_root_node(get_aggregation_number(&child_task));
if should_make_root && !is_already_constructed_root {
queue.push(AggregationUpdateJob::UpdateAggregationNumber {
task_id: child_task_id,
base_aggregation_number: u32::MAX,
distance: None,
});
}
if !has_output
&& child_task.add_scheduled(
TaskExecutionReason::Connect,
EventDescription::new(|| child_task.get_task_desc_fn()),
)
{
ctx.schedule_task(&child_task, ctx.get_current_task_priority());
}
if release_construction_ref {
child_task.update_and_get_transient_ref_count(-1);
}
}
if !queue.is_empty() {
ConnectChildOperation::UpdateAggregation {
aggregation_update: queue,
}
.execute(&mut ctx);
queue.push(AggregationUpdateJob::IncreaseActiveCount {
task: child_task_id,
release_construction_ref,
});
} else {
// First connect of this child: its id is minted but the storage entry may not exist
// yet, and concurrent connects race to be the one that first touches it.
let child_task = ctx.task_or_create(child_task_id, TaskDataCategory::Meta);
// Revive the child if GC soft-deleted it. This can happen in a rare race between a
// cache hit on a task and snapshotting actually performing the delete.
let mut child_task = resurrect_deleted(child_task, child_task_id, &mut queue, &mut ctx);
let has_output = child_task.has_output();
// An already constructed top-level task was made a root when it was first connected.
// It may still be dirty and need to run; this only avoids repeating the idempotent
// aggregation update.
let is_already_constructed_root = parent_task_id.is_none()
&& has_output
&& is_root_node(get_aggregation_number(&child_task));
if should_make_root && !is_already_constructed_root {
queue.push(AggregationUpdateJob::UpdateAggregationNumber {
task_id: child_task_id,
base_aggregation_number: u32::MAX,
distance: None,
});
}
if let Some(parent_task_id) = parent_task_id {
let mut parent_task = ctx.task(parent_task_id, TaskDataCategory::Meta);
let Some(InProgressState::InProgress(InProgressStateInner { new_children, .. })) =
parent_task.get_in_progress_mut()
else {
panic!("Task is not in progress while calling another task: {parent_task:?}");
};
// Really add the child to the new children set
if !new_children.insert(child_task_id) {
drop(parent_task);
// There was a concurrent connect child operation,
// so we need to undo the active count update.
AggregationUpdateQueue::run(
AggregationUpdateJob::DecreaseActiveCount {
task: child_task_id,
},
&mut ctx,
);
}
if !has_output
&& child_task.add_scheduled(
TaskExecutionReason::Connect,
EventDescription::new(|| child_task.get_task_desc_fn()),
)
{
ctx.schedule_task(&child_task, ctx.get_current_task_priority());
}
if release_construction_ref {
child_task.update_and_get_transient_ref_count(-1);
}
}
}
impl Operation for ConnectChildOperation {
fn execute(mut self, ctx: &mut impl ExecuteContext<'_>) {
loop {
ctx.operation_suspend_point(&self);
match self {
ConnectChildOperation::UpdateAggregation {
ref mut aggregation_update,
} => {
if aggregation_update.process(ctx) {
self = ConnectChildOperation::Done
}
}
ConnectChildOperation::Done => {
return;
}
}
if !queue.is_empty() {
queue.execute(&mut ctx);
}
if let Some(parent_task_id) = parent_task_id {
let mut parent_task = ctx.task(parent_task_id, TaskDataCategory::Meta);
let Some(InProgressState::InProgress(InProgressStateInner { new_children, .. })) =
parent_task.get_in_progress_mut()
else {
panic!("Task is not in progress while calling another task: {parent_task:?}");
};
// Really add the child to the new children set
if !new_children.insert(child_task_id) {
drop(parent_task);
// There was a concurrent connect child operation,
// so we need to undo the active count update.
AggregationUpdateQueue::run(
AggregationUpdateJob::DecreaseActiveCount {
task: child_task_id,
},
&mut ctx,
);
}
}
}
......@@ -11,9 +11,8 @@ use turbo_tasks::{
use crate::backend::{
operation::{
AggregationUpdateJob, AggregationUpdateQueue, ChildExecuteContext, ExecuteContext,
Operation, TaskGuard, aggregation_update::InnerOfUppersHasNewFollowersJob,
get_aggregation_number, get_uppers, invalidate::make_task_dirty_internal,
is_aggregating_node,
TaskGuard, aggregation_update::InnerOfUppersHasNewFollowersJob, get_aggregation_number,
get_uppers, invalidate::make_task_dirty_internal, is_aggregating_node,
},
storage_schema::TaskStorageAccessors,
};
......@@ -60,8 +59,7 @@ pub fn connect_children(
// Single pass over the newly-connected children, two things per child under one guard:
//
// 1. Bump the child-side parent reference count. it is important to do this before any
// suspend points persistence/GC cannot run
// 1. Bump the child-side parent reference count before graph propagation.
//
// 2. Make any child that has not produced output yet dirty, so it gets scheduled and
// computes.
......@@ -151,21 +149,19 @@ pub fn connect_children(
});
}
#[cfg(any(
feature = "trace_task_completion",
feature = "trace_aggregation_update_stats"
))]
let _span =
tracing::trace_span!("connect new children", stats = tracing::field::Empty).entered();
#[cfg(feature = "trace_aggregation_update_stats")]
{
#[cfg(any(
feature = "trace_task_completion",
feature = "trace_aggregation_update_stats"
))]
let _span = tracing::trace_span!("connect new children", stats = tracing::field::Empty)
.entered();
#[cfg(feature = "trace_aggregation_update_stats")]
{
let stats = queue.execute_with_stats(ctx);
_span.record("stats", tracing::field::debug(stats));
}
#[cfg(not(feature = "trace_aggregation_update_stats"))]
queue.execute(ctx);
let stats = queue.execute_with_stats(ctx);
_span.record("stats", tracing::field::debug(stats));
}
#[cfg(not(feature = "trace_aggregation_update_stats"))]
queue.execute(ctx);
}
// Connecting a child varies a lot, but it's in the range of 10-30µs.
......
use bincode::{Decode, Encode};
use smallvec::SmallVec;
#[cfg(feature = "task_dirty_cause")]
use turbo_tasks::TaskDirtyCause;
......@@ -8,7 +7,7 @@ use crate::{
backend::{
TaskDataCategory,
operation::{
ExecuteContext, Operation, TaskGuard,
ExecuteContext, TaskGuard,
aggregation_update::{
AggregationUpdateJob, AggregationUpdateQueue, ComputeDirtyAndCleanUpdate,
},
......@@ -18,74 +17,22 @@ use crate::{
data::{Dirtyness, InProgressState, InProgressStateInner},
};
#[derive(Encode, Decode, Clone, Default)]
#[allow(clippy::large_enum_variant)]
pub enum InvalidateOperation {
MakeDirty {
task_ids: SmallVec<[TaskId; 4]>,
#[cfg(feature = "task_dirty_cause")]
cause: TaskDirtyCause,
},
AggregationUpdate {
queue: AggregationUpdateQueue,
},
#[default]
Done,
}
impl InvalidateOperation {
pub fn run(
task_ids: SmallVec<[TaskId; 4]>,
#[cfg(feature = "task_dirty_cause")] cause: TaskDirtyCause,
mut ctx: impl ExecuteContext<'_>,
) {
InvalidateOperation::MakeDirty {
task_ids,
pub fn invalidate(
task_ids: SmallVec<[TaskId; 4]>,
#[cfg(feature = "task_dirty_cause")] cause: TaskDirtyCause,
mut ctx: impl ExecuteContext<'_>,
) {
let mut queue = AggregationUpdateQueue::new();
for task_id in task_ids {
try_make_task_dirty(
task_id,
#[cfg(feature = "task_dirty_cause")]
cause,
}
.execute(&mut ctx)
}
}
impl Operation for InvalidateOperation {
fn execute(mut self, ctx: &mut impl ExecuteContext<'_>) {
loop {
ctx.operation_suspend_point(&self);
match self {
InvalidateOperation::MakeDirty {
task_ids,
#[cfg(feature = "task_dirty_cause")]
cause,
} => {
let mut queue = AggregationUpdateQueue::new();
for task_id in task_ids {
try_make_task_dirty(
task_id,
#[cfg(feature = "task_dirty_cause")]
cause.clone(),
&mut queue,
ctx,
);
}
if queue.is_empty() {
self = InvalidateOperation::Done
} else {
self = InvalidateOperation::AggregationUpdate { queue }
}
continue;
}
InvalidateOperation::AggregationUpdate { ref mut queue } => {
if queue.process(ctx) {
self = InvalidateOperation::Done
}
}
InvalidateOperation::Done => {
return;
}
}
}
cause.clone(),
&mut queue,
&mut ctx,
);
}
queue.execute(&mut ctx);
}
/// Marks a task dirty. The task must exist.
......
......@@ -3,21 +3,16 @@ use std::{
collections::{BinaryHeap, hash_map::Entry},
};
use bincode::{Decode, Encode};
use rustc_hash::FxHashMap;
#[cfg(feature = "trace_leaf_distance_update")]
use tracing::{span::Span, trace_span};
use turbo_tasks::TaskId;
use crate::backend::{
TaskDataCategory,
operation::{ExecuteContext, Operation},
storage_schema::TaskStorageAccessors,
TaskDataCategory, operation::ExecuteContext, storage_schema::TaskStorageAccessors,
};
/// The maximum number of leaf distance updates to process before yielding back to the executor.
/// This prevents long blocking operations and allows to interrupt the processing for persistent
/// caching.
/// The maximum number of leaf distance updates processed in one step.
const MAX_COUNT_BEFORE_YIELD: usize = 1000;
/// We avoid incrementing the leaf distance by 1 each time to avoid frequent updates.
......@@ -26,13 +21,11 @@ const MAX_COUNT_BEFORE_YIELD: usize = 1000;
const BASE_LEAF_DISTANCE_BUFFER: u32 = 128;
/// An leaf distance update job that is enqueued.
#[derive(Encode, Decode, Clone)]
struct LeafDistanceUpdate {
dependencies_distance: u32,
dependencies_max_distance_in_buffer: u32,
done: bool,
#[cfg(feature = "trace_leaf_distance_update")]
#[bincode(skip)]
span: Option<Span>,
}
......@@ -48,7 +41,7 @@ impl LeafDistanceUpdate {
/// A queue of leaf distance update jobs.
/// It will execute these jobs in order of their minimum dependency leaf distance.
/// This ensures that we never have to re-process a task.
#[derive(Default, Encode, Decode, Clone)]
#[derive(Default)]
pub struct LeafDistanceUpdateQueue {
queue: BinaryHeap<(Reverse<u32>, TaskId)>,
leaf_distance_updates: FxHashMap<TaskId, LeafDistanceUpdate>,
......@@ -175,18 +168,11 @@ impl LeafDistanceUpdateQueue {
}
task.set_leaf_distance(leaf_distance);
}
}
impl Operation for LeafDistanceUpdateQueue {
fn execute(mut self, ctx: &mut impl ExecuteContext<'_>) {
pub fn execute(&mut self, ctx: &mut impl ExecuteContext<'_>) {
if self.is_empty() {
return;
}
loop {
ctx.operation_suspend_point(&self);
if self.process(ctx) {
return;
}
}
while !self.process(ctx) {}
}
}
......@@ -14,7 +14,6 @@ use std::{
};
use anyhow::{Context, Result};
use bincode::{Decode, Encode};
use parking_lot::RwLockReadGuard;
use tracing::info_span;
#[cfg(feature = "trace_prepare_tasks")]
......@@ -25,7 +24,7 @@ use turbo_tasks::{
macro_helpers::NativeFunction,
};
pub use self::aggregation_update::ComputeDirtyAndCleanUpdate;
pub use self::aggregation_update::{AggregationUpdateQueue, ComputeDirtyAndCleanUpdate};
use crate::{
backend::{
EventDescription, TaskDataCategory, TurboTasksBackend,
......@@ -37,10 +36,6 @@ use crate::{
data::{ActivenessState, CollectibleRef, Dirtyness, InProgressState, TransientTask},
};
pub trait Operation: Encode + Decode<()> + Default + TryFrom<AnyOperation, Error = ()> {
fn execute(self, ctx: &mut impl ExecuteContext<'_>);
}
/// The task storage `open_task` is working with, which may or may not still own its map entry.
enum OpenedTask<'a> {
Owned(TaskEntryGuard<'a>),
......@@ -181,9 +176,6 @@ pub trait ExecuteContext<'e>: Sized {
) -> (Self::TaskGuardImpl, Self::TaskGuardImpl);
fn schedule_task(&self, task: &Self::TaskGuardImpl, parent_priority: TaskPriority);
fn get_current_task_priority(&self) -> TaskPriority;
fn operation_suspend_point<T>(&mut self, op: &T)
where
T: Clone + Into<AnyOperation>;
/// Record `task` as a GC candidate **if it is in fact collectible**.
///
/// Call this wherever an operation removes the last reference of some kind to a task. This may
......@@ -262,18 +254,12 @@ impl TaskLockCounter {
}
}
enum ExecutePhase<'e> {
Normal {
guard: Option<OperationGuard<'e, AnyOperation>>,
},
Child,
Gc(&'e dyn Fn(TaskId)),
}
pub struct ExecuteContextImpl<'e> {
backend: &'e TurboTasksBackend,
turbo_tasks: &'e TurboTasks<TurboTasksBackend>,
phase: ExecutePhase<'e>,
gc_collectible: Option<&'e dyn Fn(TaskId)>,
/// Held until all graph changes made by this context have completed.
_operation_guard: Option<OperationGuard<'e>>,
/// Held by contexts built through `TurboTasksBackend::try_execute_context`, so that storage
/// teardown in `stop()` waits for this context to be dropped.
_shutdown_guard: Option<RwLockReadGuard<'e, bool>>,
......@@ -288,9 +274,8 @@ impl<'e> ExecuteContextImpl<'e> {
Self {
backend,
turbo_tasks,
phase: ExecutePhase::Normal {
guard: backend.start_operation(),
},
gc_collectible: None,
_operation_guard: backend.start_operation(),
_shutdown_guard: None,
task_lock_counter: TaskLockCounter::new(),
}
......@@ -307,9 +292,8 @@ impl<'e> ExecuteContextImpl<'e> {
Self {
backend,
turbo_tasks,
phase: ExecutePhase::Normal {
guard: backend.start_operation(),
},
gc_collectible: None,
_operation_guard: backend.start_operation(),
_shutdown_guard: Some(shutdown_guard),
task_lock_counter: TaskLockCounter::new(),
}
......@@ -319,18 +303,19 @@ impl<'e> ExecuteContextImpl<'e> {
/// collector while it holds the coordinator's exclusion phase.
///
/// The exclusion excludes all concurrent operations and task execution, so taking an operation
/// guard here would deadlock. Requiring `&ExclusionPhase` makes that a type-level obligation:
/// guard here would deadlock. Requiring `&SnapshotPhase` makes that a type-level obligation:
/// the caller cannot construct this context without actually holding the exclusion.
pub(super) fn new_for_gc(
backend: &'e TurboTasksBackend,
turbo_tasks: &'e TurboTasks<TurboTasksBackend>,
_phase: &'e SnapshotPhase<'_, AnyOperation>,
_phase: &'e SnapshotPhase<'_>,
gc_collectible: &'e dyn Fn(TaskId),
) -> Self {
Self {
backend,
turbo_tasks,
phase: ExecutePhase::Gc(gc_collectible),
gc_collectible: Some(gc_collectible),
_operation_guard: None,
_shutdown_guard: None,
task_lock_counter: TaskLockCounter::new(),
}
......@@ -1364,15 +1349,8 @@ impl<'e> ExecuteContext<'e> for ExecuteContextImpl<'e> {
self.turbo_tasks.get_current_task_priority()
}
fn operation_suspend_point<T: Clone + Into<AnyOperation>>(&mut self, op: &T) {
let ExecutePhase::Normal { guard: Some(guard) } = &mut self.phase else {
return;
};
guard.suspend_point(|| op.clone().into());
}
fn note_maybe_collectible(&mut self, task: &impl TaskGuard) {
if let ExecutePhase::Gc(collector) = self.phase
if let Some(collector) = self.gc_collectible
&& task.is_gc_collectible()
{
collector(task.id());
......@@ -1435,7 +1413,8 @@ impl<'e> ChildExecuteContext<'e> for ChildExecuteContextImpl<'e> {
ExecuteContextImpl {
backend: self.backend,
turbo_tasks: self.turbo_tasks,
phase: ExecutePhase::Child,
gc_collectible: None,
_operation_guard: None,
// A child context runs inside its parent's execution, which the foreground drain
// already waits for, so it needs no shutdown guard of its own.
_shutdown_guard: None,
......@@ -2025,74 +2004,20 @@ impl TaskStorageAccessors for TaskGuardImpl<'_> {
}
}
macro_rules! impl_operation {
($name:ident $type_path:path) => {
impl From<$type_path> for AnyOperation {
fn from(op: $type_path) -> Self {
AnyOperation::$name(op)
}
}
impl TryFrom<AnyOperation> for $type_path {
type Error = ();
fn try_from(op: AnyOperation) -> Result<Self, Self::Error> {
match op {
AnyOperation::$name(op) => Ok(op),
_ => Err(()),
}
}
}
pub use $type_path;
};
}
#[derive(Encode, Decode, Clone)]
pub enum AnyOperation {
ConnectChild(connect_child::ConnectChildOperation),
Invalidate(invalidate::InvalidateOperation),
UpdateCell(update_cell::UpdateCellOperation),
CleanupOldEdges(cleanup_old_edges::CleanupOldEdgesOperation),
AggregationUpdate(aggregation_update::AggregationUpdateQueue),
LeafDistanceUpdate(leaf_distance_update::LeafDistanceUpdateQueue),
Nested(Vec<AnyOperation>),
}
impl AnyOperation {
pub fn execute(self, ctx: &mut impl ExecuteContext<'_>) {
match self {
AnyOperation::ConnectChild(op) => op.execute(ctx),
AnyOperation::Invalidate(op) => op.execute(ctx),
AnyOperation::UpdateCell(op) => op.execute(ctx),
AnyOperation::CleanupOldEdges(op) => op.execute(ctx),
AnyOperation::AggregationUpdate(op) => op.execute(ctx),
AnyOperation::LeafDistanceUpdate(op) => op.execute(ctx),
AnyOperation::Nested(ops) => {
for op in ops {
op.execute(ctx);
}
}
}
}
}
impl_operation!(ConnectChild connect_child::ConnectChildOperation);
impl_operation!(Invalidate invalidate::InvalidateOperation);
impl_operation!(UpdateCell update_cell::UpdateCellOperation);
impl_operation!(CleanupOldEdges cleanup_old_edges::CleanupOldEdgesOperation);
impl_operation!(AggregationUpdate aggregation_update::AggregationUpdateQueue);
impl_operation!(LeafDistanceUpdate leaf_distance_update::LeafDistanceUpdateQueue);
pub use self::{
aggregation_update::{
AggregatedDataUpdate, AggregationUpdateJob, get_aggregation_number, get_uppers,
is_aggregating_node, is_root_node,
},
cleanup_old_edges::{OutdatedEdge, capture_all_edges},
cleanup_old_edges::{
OutdatedEdge, capture_all_edges, cleanup_old_edges, cleanup_old_edges_deletions_only,
},
connect_child::connect_child,
connect_children::connect_children,
invalidate::make_task_dirty_internal,
invalidate::{invalidate, make_task_dirty_internal},
leaf_distance_update::LeafDistanceUpdateQueue,
prepare_new_children::prepare_new_children,
update_cell::update_cell,
update_collectible::UpdateCollectibleOperation,
};
......
use std::{cell::LazyCell, mem::take};
use std::cell::LazyCell;
use bincode::{Decode, Encode};
use rustc_hash::FxHashSet;
use smallvec::SmallVec;
#[cfg(feature = "task_dirty_cause")]
......@@ -15,252 +14,205 @@ use crate::{
backend::{
TaskDataCategory,
operation::{
AggregationUpdateQueue, ExecuteContext, Operation, TaskGuard,
invalidate::make_task_dirty_internal,
AggregationUpdateQueue, ExecuteContext, TaskGuard, invalidate::make_task_dirty_internal,
},
storage_schema::TaskStorageAccessors,
},
data::CellRef,
};
#[derive(Encode, Decode, Clone, Default)]
#[allow(clippy::large_enum_variant)]
pub enum UpdateCellOperation {
InvalidateWhenCellDependency {
cell_ref: CellRef,
#[bincode(with = "turbo_bincode::indexmap")]
dependent_tasks: FxIndexMap<TaskId, SmallVec<[Option<u64>; 2]>>,
#[cfg(feature = "task_dirty_cause")]
has_updated_key_hashes: bool,
content: Option<TypedSharedReference>,
queue: AggregationUpdateQueue,
},
FinalCellChange {
cell_ref: CellRef,
content: Option<TypedSharedReference>,
queue: AggregationUpdateQueue,
},
AggregationUpdate {
queue: AggregationUpdateQueue,
},
#[default]
Done,
}
impl UpdateCellOperation {
pub fn run(
task_id: TaskId,
cell: CellId,
content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<CellHash>,
#[cfg(feature = "verify_determinism")] verification_mode: VerificationMode,
#[cfg(not(feature = "verify_determinism"))] _verification_mode: VerificationMode,
mut ctx: impl ExecuteContext<'_>,
) {
let value_type = registry::get_value_type(cell.type_id());
// `content_hash` is only ever supplied for `HashOnly` cells — only the
// `"hash"`-mode write path emits a hash, and no other mode consumes
// it. (It can still be `None` for `HashOnly` when the cell is being
// cleared.)
debug_assert!(
content_hash.is_none()
|| matches!(value_type.persistence, ValueTypePersistence::HashOnly),
"content_hash must only be supplied for HashOnly cells"
);
let content = content.0;
let mut task = ctx.task(task_id, TaskDataCategory::All);
// We need to detect recomputation, because here the content has not actually changed (even
// if it's not equal to the old content, as not all values implement Eq). We have to
// assume that tasks are deterministic and pure.
let assume_unchanged = !ctx.should_track_dependencies() || !task.has_dirty();
if assume_unchanged {
let has_old_content = task.cell_data_contains(&cell);
if has_old_content {
// Never update cells when recomputing if they already have a value.
// It's not expected that content changes during recomputation.
// Check if this assumption holds.
#[cfg(feature = "verify_determinism")]
if !task.stateful()
&& matches!(
verification_mode,
turbo_tasks::backend::VerificationMode::EqualityCheck
)
&& content.as_ref() != task.get_cell_data(&cell)
{
let task_description = task.get_task_description();
let cell_type = value_type.ty.global_name;
eprintln!(
"Task {} updated cell #{} (type: {}) while recomputing",
task_description,
cell.index(),
cell_type
);
}
return;
} else {
// Initial computation, or computation after a cell has been cleared.
// We can just set the content, but we don't want to notify dependent tasks,
// as we assume that content hasn't changed (deterministic tasks).
pub fn update_cell(
task_id: TaskId,
cell: CellId,
content: CellContent,
updated_key_hashes: Option<SmallVec<[u64; 2]>>,
content_hash: Option<CellHash>,
#[cfg(feature = "verify_determinism")] verification_mode: VerificationMode,
#[cfg(not(feature = "verify_determinism"))] _verification_mode: VerificationMode,
mut ctx: impl ExecuteContext<'_>,
) {
let value_type = registry::get_value_type(cell.type_id());
// `content_hash` is only ever supplied for `HashOnly` cells — only the
// `"hash"`-mode write path emits a hash, and no other mode consumes
// it. (It can still be `None` for `HashOnly` when the cell is being
// cleared.)
debug_assert!(
content_hash.is_none() || matches!(value_type.persistence, ValueTypePersistence::HashOnly),
"content_hash must only be supplied for HashOnly cells"
);
let content = content.0;
let mut task = ctx.task(task_id, TaskDataCategory::All);
// We need to detect recomputation, because here the content has not actually changed (even
// if it's not equal to the old content, as not all values implement Eq). We have to
// assume that tasks are deterministic and pure.
let assume_unchanged = !ctx.should_track_dependencies() || !task.has_dirty();
if assume_unchanged {
let has_old_content = task.cell_data_contains(&cell);
if has_old_content {
// Never update cells when recomputing if they already have a value.
// It's not expected that content changes during recomputation.
// Check if this assumption holds.
#[cfg(feature = "verify_determinism")]
if !task.stateful()
&& matches!(
verification_mode,
turbo_tasks::backend::VerificationMode::EqualityCheck
)
&& content.as_ref() != task.get_cell_data(&cell)
{
let task_description = task.get_task_description();
let cell_type = value_type.ty.global_name;
eprintln!(
"Task {} updated cell #{} (type: {}) while recomputing",
task_description,
cell.index(),
cell_type
);
}
return;
} else {
// When not recomputing, we need to notify dependent tasks if the content actually
// changes.
// For HashOnly cells without available content, use hash-based comparison to
// detect whether the value actually changed—avoiding unnecessary invalidation.
let skip_invalidation =
matches!(value_type.persistence, ValueTypePersistence::HashOnly) && {
let has_old_content = task.cell_data_contains(&cell);
if !has_old_content {
match (content_hash, task.get_cell_data_hash(&cell)) {
(Some(new_hash), Some(old_hash)) => new_hash == *old_hash,
_ => false,
}
} else {
false
// Initial computation, or computation after a cell has been cleared.
// We can just set the content, but we don't want to notify dependent tasks,
// as we assume that content hasn't changed (deterministic tasks).
}
} else {
// When not recomputing, we need to notify dependent tasks if the content actually
// changes.
// For HashOnly cells without available content, use hash-based comparison to
// detect whether the value actually changed—avoiding unnecessary invalidation.
let skip_invalidation = matches!(value_type.persistence, ValueTypePersistence::HashOnly)
&& {
let has_old_content = task.cell_data_contains(&cell);
if !has_old_content {
match (content_hash, task.get_cell_data_hash(&cell)) {
(Some(new_hash), Some(old_hash)) => new_hash == *old_hash,
_ => false,
}
};
#[cfg(feature = "task_dirty_cause")]
let has_updated_key_hashes = updated_key_hashes.is_some();
let updated_key_hashes_set = updated_key_hashes.map(|updated_key_hashes| {
LazyCell::new(|| updated_key_hashes.into_iter().collect::<FxHashSet<u64>>())
});
} else {
false
}
};
// Collect dependent tasks only when not skipping invalidation.
// The iterators borrow from `task`, so they must be scoped to drop before
// we mutably borrow `task` again in the fast path.
let mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[Option<u64>; 2]>> =
FxIndexMap::default();
if !skip_invalidation {
// Keyless dependents: always invalidate when the cell matches.
for CellRef {
#[cfg(feature = "task_dirty_cause")]
let has_updated_key_hashes = updated_key_hashes.is_some();
let updated_key_hashes_set = updated_key_hashes.map(|updated_key_hashes| {
LazyCell::new(|| updated_key_hashes.into_iter().collect::<FxHashSet<u64>>())
});
// Collect dependent tasks only when not skipping invalidation.
// The iterators borrow from `task`, so they must be scoped to drop before
// we mutably borrow `task` again in the fast path.
let mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[Option<u64>; 2]>> =
FxIndexMap::default();
if !skip_invalidation {
// Keyless dependents: always invalidate when the cell matches.
for CellRef {
task: dependent_task,
cell: dependent_cell,
} in task.iter_cell_dependents()
{
if dependent_cell == cell {
dependent_tasks
.entry(dependent_task)
.or_default()
.push(None);
}
}
// Keyed dependents: invalidate only when the changed sub-value (key) matches.
for (
CellRef {
task: dependent_task,
cell: dependent_cell,
} in task.iter_cell_dependents()
{
if dependent_cell == cell {
dependent_tasks
.entry(dependent_task)
.or_default()
.push(None);
}
}
// Keyed dependents: invalidate only when the changed sub-value (key) matches.
for (
CellRef {
task: dependent_task,
cell: dependent_cell,
},
key_hash,
) in task.iter_cell_dependents_hashed()
},
key_hash,
) in task.iter_cell_dependents_hashed()
{
if dependent_cell == cell
&& updated_key_hashes_set
.as_ref()
.is_none_or(|set| set.contains(&key_hash))
{
if dependent_cell == cell
&& updated_key_hashes_set
.as_ref()
.is_none_or(|set| set.contains(&key_hash))
{
dependent_tasks
.entry(dependent_task)
.or_default()
.push(Some(key_hash));
}
}
}
if !dependent_tasks.is_empty() {
// Slow path: We need to invalidate tasks depending on this cell.
// To avoid a race condition, we need to remove the old content first,
// then invalidate dependent tasks and only then update the cell content.
// The reason behind this is that we consider tasks that haven't the dirty flag set
// as "recomputing" tasks. Recomputing tasks won't invalidate
// dependent tasks, when a cell is changed. This would cause missing invalidating if
// a task is recomputing while a dependency is in the middle of a cell update (where
// the value has been changed, but the dependent tasks have not be flagged dirty
// yet). So to avoid that we first remove the cell content, invalidate all dependent
// tasks and after that set the new cell content. When the cell content is unset,
// readers will wait for it to be set via InProgressCell.
let old_content = task.remove_cell_data(&cell, &value_type.persistence);
// Update cell_data_hash before dropping the task lock
if matches!(value_type.persistence, ValueTypePersistence::HashOnly) {
update_cell_data_hash(&mut task, &cell, content_hash);
}
drop(task);
drop(old_content);
ctx.prepare_tasks(
dependent_tasks
.keys()
.map(|&id| (id, TaskDataCategory::All)),
"invalidate cell dependents",
);
UpdateCellOperation::InvalidateWhenCellDependency {
cell_ref: CellRef {
task: task_id,
cell,
},
dependent_tasks,
#[cfg(feature = "task_dirty_cause")]
has_updated_key_hashes,
content: content.map(|r| r.into_typed(cell.type_id())),
queue: AggregationUpdateQueue::new(),
.entry(dependent_task)
.or_default()
.push(Some(key_hash));
}
.execute(&mut ctx);
return;
}
}
// Fast path: We don't need to invalidate anything.
// So we can just update the cell content.
let old_content = if let Some(new_content) = content {
task.insert_cell_data(cell, new_content, &value_type.persistence)
} else {
task.remove_cell_data(&cell, &value_type.persistence)
};
if !dependent_tasks.is_empty() {
// Slow path: We need to invalidate tasks depending on this cell.
// To avoid a race condition, we need to remove the old content first,
// then invalidate dependent tasks and only then update the cell content.
// The reason behind this is that we consider tasks that haven't the dirty flag set
// as "recomputing" tasks. Recomputing tasks won't invalidate
// dependent tasks, when a cell is changed. This would cause missing invalidating if
// a task is recomputing while a dependency is in the middle of a cell update (where
// the value has been changed, but the dependent tasks have not be flagged dirty
// yet). So to avoid that we first remove the cell content, invalidate all dependent
// tasks and after that set the new cell content. When the cell content is unset,
// readers will wait for it to be set via InProgressCell.
let old_content = task.remove_cell_data(&cell, &value_type.persistence);
// Update cell_data_hash before dropping the task lock
if matches!(value_type.persistence, ValueTypePersistence::HashOnly) {
update_cell_data_hash(&mut task, &cell, content_hash);
}
// Update cell_data_hash for hash-only cells.
if matches!(value_type.persistence, ValueTypePersistence::HashOnly) {
update_cell_data_hash(&mut task, &cell, content_hash);
drop(task);
drop(old_content);
ctx.prepare_tasks(
dependent_tasks
.keys()
.map(|&id| (id, TaskDataCategory::All)),
"invalidate cell dependents",
);
invalidate_cell_dependents(
CellRef {
task: task_id,
cell,
},
dependent_tasks,
#[cfg(feature = "task_dirty_cause")]
has_updated_key_hashes,
content.map(|r| r.into_typed(cell.type_id())),
&mut ctx,
);
return;
}
}
let in_progress_cell = task.remove_in_progress_cells(&cell);
// Fast path: We don't need to invalidate anything.
// So we can just update the cell content.
drop(task);
drop(old_content);
let old_content = if let Some(new_content) = content {
task.insert_cell_data(cell, new_content, &value_type.persistence)
} else {
task.remove_cell_data(&cell, &value_type.persistence)
};
if let Some(in_progress) = in_progress_cell {
in_progress.event.notify(usize::MAX);
}
// Update cell_data_hash for hash-only cells.
if matches!(value_type.persistence, ValueTypePersistence::HashOnly) {
update_cell_data_hash(&mut task, &cell, content_hash);
}
/// Whether this operation's mid-flight state can safely be persisted to
/// the operation suspend log. True iff the cell's value type has bincode —
/// non-persistable values cannot be recovered across restart, so we don't
/// write a suspend point for them.
fn is_serializable(&self) -> bool {
match self {
UpdateCellOperation::InvalidateWhenCellDependency { cell_ref, .. }
| UpdateCellOperation::FinalCellChange { cell_ref, .. } => {
matches!(
registry::get_value_type(cell_ref.cell.type_id()).persistence,
ValueTypePersistence::Persistable(_, _),
)
}
UpdateCellOperation::AggregationUpdate { .. } => true,
UpdateCellOperation::Done => true,
}
let in_progress_cell = task.remove_in_progress_cells(&cell);
drop(task);
drop(old_content);
if let Some(in_progress) = in_progress_cell {
in_progress.event.notify(usize::MAX);
}
}
......@@ -278,108 +230,78 @@ fn update_cell_data_hash(task: &mut impl TaskGuard, cell: &CellId, content_hash:
}
}
impl Operation for UpdateCellOperation {
fn execute(mut self, ctx: &mut impl ExecuteContext<'_>) {
loop {
if self.is_serializable() {
ctx.operation_suspend_point(&self);
fn invalidate_cell_dependents(
cell_ref: CellRef,
mut dependent_tasks: FxIndexMap<TaskId, SmallVec<[Option<u64>; 2]>>,
#[cfg(feature = "task_dirty_cause")] has_updated_key_hashes: bool,
content: Option<TypedSharedReference>,
ctx: &mut impl ExecuteContext<'_>,
) {
let mut queue = AggregationUpdateQueue::new();
while let Some((dependent_task_id, keys)) = dependent_tasks.pop() {
let mut make_stale = false;
let mut dependent = ctx.task(dependent_task_id, TaskDataCategory::All);
for key in keys.iter().copied() {
let (in_outdated, in_current) = if let Some(k) = key {
let in_outdated =
dependent.outdated_cell_dependencies_hashed_contains(&(cell_ref, k));
let in_current =
!in_outdated && dependent.cell_dependencies_hashed_contains(&(cell_ref, k));
(in_outdated, in_current)
} else {
let in_outdated = dependent.outdated_cell_dependencies_contains(&cell_ref);
let in_current = !in_outdated && dependent.cell_dependencies_contains(&cell_ref);
(in_outdated, in_current)
};
if in_outdated {
// cell dependency is outdated, so it hasn't read the cell yet
// and doesn't need to be invalidated.
// We do not need to make the task stale in this case.
// But importantly we still need to make the task dirty as it should
// no longer be considered as
// "recomputation".
} else if !in_current {
// cell dependency has been removed, so the task doesn't depend on
// the cell anymore and doesn't need
// to be invalidated
continue;
} else {
make_stale = true;
}
match self {
UpdateCellOperation::InvalidateWhenCellDependency {
cell_ref,
ref mut dependent_tasks,
#[cfg(feature = "task_dirty_cause")]
has_updated_key_hashes,
ref mut content,
ref mut queue,
} => {
if let Some((dependent_task_id, keys)) = dependent_tasks.pop() {
let mut make_stale = false;
let mut dependent = ctx.task(dependent_task_id, TaskDataCategory::All);
for key in keys.iter().copied() {
let (in_outdated, in_current) = if let Some(k) = key {
let in_outdated = dependent
.outdated_cell_dependencies_hashed_contains(&(cell_ref, k));
let in_current = !in_outdated
&& dependent.cell_dependencies_hashed_contains(&(cell_ref, k));
(in_outdated, in_current)
} else {
let in_outdated =
dependent.outdated_cell_dependencies_contains(&cell_ref);
let in_current =
!in_outdated && dependent.cell_dependencies_contains(&cell_ref);
(in_outdated, in_current)
};
if in_outdated {
// cell dependency is outdated, so it hasn't read the cell yet
// and doesn't need to be invalidated.
// We do not need to make the task stale in this case.
// But importantly we still need to make the task dirty as it should
// no longer be considered as
// "recomputation".
} else if !in_current {
// cell dependency has been removed, so the task doesn't depend on
// the cell anymore and doesn't need
// to be invalidated
continue;
} else {
make_stale = true;
}
}
make_task_dirty_internal(
&mut dependent,
make_stale,
#[cfg(feature = "task_dirty_cause")]
TaskDirtyCause::CellChange {
value_type: cell_ref.cell.type_id(),
keys: has_updated_key_hashes.then_some(keys).unwrap_or_default(),
},
queue,
ctx,
);
}
if dependent_tasks.is_empty() {
self = UpdateCellOperation::FinalCellChange {
cell_ref,
content: take(content),
queue: take(queue),
};
}
}
UpdateCellOperation::FinalCellChange {
cell_ref: CellRef { task, cell },
content,
ref mut queue,
} => {
let mut task = ctx.task(task, TaskDataCategory::Data);
if let Some(content) = content {
// This arm only carries the CellId, so resolve the cell's
// persistence here (one lookup per final change, not on the
// inner hot path) to decide whether the write tracks.
let persistence = &registry::get_value_type(cell.type_id()).persistence;
task.add_cell_data(cell, content.into_untyped(), persistence);
}
let in_progress_cell = task.remove_in_progress_cells(&cell);
}
make_task_dirty_internal(
&mut dependent,
make_stale,
#[cfg(feature = "task_dirty_cause")]
TaskDirtyCause::CellChange {
value_type: cell_ref.cell.type_id(),
keys: if has_updated_key_hashes {
keys
} else {
Default::default()
},
},
&mut queue,
ctx,
);
}
let mut task = ctx.task(cell_ref.task, TaskDataCategory::Data);
if let Some(content) = content {
// This arm only carries the CellId, so resolve the cell's
// persistence here (one lookup per final change, not on the
// inner hot path) to decide whether the write tracks.
let persistence = &registry::get_value_type(cell_ref.cell.type_id()).persistence;
task.add_cell_data(cell_ref.cell, content.into_untyped(), persistence);
}
drop(task);
let in_progress_cell = task.remove_in_progress_cells(&cell_ref.cell);
if let Some(in_progress) = in_progress_cell {
in_progress.event.notify(usize::MAX);
}
drop(task);
self = UpdateCellOperation::AggregationUpdate { queue: take(queue) };
}
UpdateCellOperation::AggregationUpdate { ref mut queue } => {
if queue.process(ctx) {
self = UpdateCellOperation::Done
}
}
UpdateCellOperation::Done => {
return;
}
}
}
if let Some(in_progress) = in_progress_cell {
in_progress.event.notify(usize::MAX);
}
queue.execute(ctx);
}
......@@ -8,7 +8,6 @@ use crate::{
TaskDataCategory,
operation::{
AggregatedDataUpdate, AggregationUpdateJob, AggregationUpdateQueue, ExecuteContext,
Operation,
},
storage_schema::TaskStorageAccessors,
},
......
......@@ -6,102 +6,103 @@
//! - When no exclusive phase is in flight,
//! [`begin_operation`](SnapshotCoordinator::begin_operation) is a single uncontended atomic
//! increment.
//! - When a phase is requested, new operations block until it finishes, and operations already in
//! flight either complete or call [`suspend_point`](OperationGuard::suspend_point) to suspend.
//! - The phase holder waits for every in-flight operation to drain or suspend, does its work, then
//! wakes everyone.
//!
//! Snapshotting and GC are the same kind of exclusion and share one [`ExclusionPhase`]: both need
//! every operation stopped, neither can overlap the other, and GC hands its work straight to the
//! snapshot that persists it. A single [`EXCLUSION_REQUESTED_BIT`] covers both, which is also what
//! lets a GC pass and the snapshot that commits it run under one uninterrupted guard.
use std::sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
//! - A phase waits for a zero-active boundary while new operations remain free to enter. An
//! operation can depend on work started by another operation, so closing admission before all
//! active work completes could deadlock graph propagation.
//! - At that boundary the phase atomically closes admission, does its work, then wakes new
//! operations. No partially propagated graph work needs to be saved for replay.
//! - Because admission stays open while waiting, a busy graph may not reach a boundary for a long
//! time. [`begin_snapshot`](SnapshotCoordinator::begin_snapshot) reports long waits to its
//! caller, and [`try_begin_snapshot`](SnapshotCoordinator::try_begin_snapshot) doesn't wait at
//! all, for callers that can retry later.
use std::{
sync::atomic::{AtomicBool, AtomicUsize, Ordering},
time::{Duration, Instant},
};
use parking_lot::{Condvar, Mutex};
use rustc_hash::FxHashSet;
use parking_lot::{Condvar, Mutex, MutexGuard};
use tracing::info_span;
use crate::{backend::AnyOperation, utils::ptr_eq_arc::PtrEqArc};
/// High bit: set while a snapshot is requested or in flight.
/// Low bits: count of operations currently executing (not suspended).
const SNAPSHOT_REQUESTED_BIT: usize = 1 << (usize::BITS - 1);
/// Blocks admission while a snapshot is in flight.
const SNAPSHOT_RUNNING_BIT: usize = 1 << (usize::BITS - 1);
/// Requests notification at a zero-active boundary without blocking admission.
const SNAPSHOT_WAITING_BIT: usize = 1 << (usize::BITS - 2);
/// Low bits count operations; the two high bits coordinate snapshot admission.
const OPERATION_COUNT_MASK: usize = !(SNAPSHOT_RUNNING_BIT | SNAPSHOT_WAITING_BIT);
/// How long a snapshot waits for operations to settle before reporting it. Later reports follow
/// each time the total wait doubles.
const DEFAULT_SLOW_SETTLE_REPORT_TIME: Duration = Duration::from_secs(10);
/// Passed to the [`begin_snapshot`](SnapshotCoordinator::begin_snapshot) callback when a snapshot
/// has been waiting a long time for active operations to finish.
///
/// Operations keep being admitted while the snapshot waits, so the counts can't tell whether the
/// same operations are still running or new ones keep replacing them.
pub struct SlowSettle {
/// How long the snapshot has been waiting so far.
pub waited: Duration,
/// Operations that were active when the snapshot was requested.
pub active_at_start: usize,
/// Operations that are active now.
pub active_now: usize,
}
/// State protected by the mutex.
struct State<O> {
struct State {
/// `true` between `begin_snapshot` and `SnapshotPhase::drop`.
snapshot_requested: bool,
/// Operations that called [`OperationGuard::suspend_point`] and have
/// not yet resumed. Returned to the snapshotter via
/// [`SnapshotPhase::suspended_operations`] so it can persist them in the
/// uncompleted-operations log.
suspended_operations: FxHashSet<PtrEqArc<O>>,
}
/// Coordinates operation/snapshot/GC interleaving.
///
/// Generic over the operation type the caller wants to suspend. The
/// coordinator only requires `O: Send + Sync + 'static`; it never inspects
/// the value, just stores it via [`PtrEqArc`].
pub struct SnapshotCoordinator<O = AnyOperation> {
/// Combined count + bit. See [`SNAPSHOT_REQUESTED_BIT`].
pub struct SnapshotCoordinator {
/// Operation count plus [`SNAPSHOT_WAITING_BIT`] and [`SNAPSHOT_RUNNING_BIT`].
in_progress_operations: AtomicUsize,
operations_waiting: AtomicBool,
state: Mutex<State<O>>,
/// Notified by the last operation to drain (count drops to `BIT` while
/// `SNAPSHOT_REQUESTED_BIT` is set). Awaited by [`begin_snapshot`].
state: Mutex<State>,
/// Notified whenever the last active operation leaves while a phase is waiting.
operations_drained: Condvar,
/// Notified by [`SnapshotPhase::drop`]. Awaited by operations that hit a
/// suspend point or arrive while a snapshot is in flight.
/// Notified by [`SnapshotPhase::drop`]. Awaited by operations arriving during a snapshot.
snapshot_completed: Condvar,
/// How long to
slow_settle_report_timeout: Duration,
}
impl<O> Default for SnapshotCoordinator<O> {
impl Default for SnapshotCoordinator {
fn default() -> Self {
Self::new()
}
}
impl<O> SnapshotCoordinator<O> {
impl SnapshotCoordinator {
pub fn new() -> Self {
Self::new_with_custom_slow_settle_report_timeout(DEFAULT_SLOW_SETTLE_REPORT_TIME)
}
fn new_with_custom_slow_settle_report_timeout(slow_settle_report_timeout: Duration) -> Self {
Self {
in_progress_operations: AtomicUsize::new(0),
operations_waiting: AtomicBool::new(false),
state: Mutex::new(State {
snapshot_requested: false,
suspended_operations: FxHashSet::default(),
}),
operations_drained: Condvar::new(),
snapshot_completed: Condvar::new(),
slow_settle_report_timeout,
}
}
/// Cheap check used by hot paths. Returns `true` while a snapshot is in
/// flight (or being requested). May return `false` racily if a snapshot
/// is just about to start; the actual coordination happens in
/// [`OperationGuard::suspend_point`] and [`begin_operation`](Self::begin_operation).
pub fn snapshot_pending(&self) -> bool {
// Acquire so that observing the bit synchronizes with anything the
// snapshotter wrote before setting it.
(self.in_progress_operations.load(Ordering::Acquire) & SNAPSHOT_REQUESTED_BIT) != 0
}
/// Begin an operation. Returns a guard that decrements on drop.
///
/// If a snapshot is in flight, blocks until the snapshot finishes before
/// returning the guard.
pub fn begin_operation(&self) -> OperationGuard<'_, O> {
pub fn begin_operation(&self) -> OperationGuard<'_> {
// Fast path: no snapshot in flight, single atomic increment.
let prev = self.in_progress_operations.fetch_add(1, Ordering::AcqRel);
if (prev & SNAPSHOT_REQUESTED_BIT) == 0 {
if (prev & SNAPSHOT_RUNNING_BIT) == 0 {
return OperationGuard { coord: self };
}
#[cold]
fn wait_for_snapshot_to_complete<O>(this: &SnapshotCoordinator<O>) {
fn wait_for_snapshot_to_complete(this: &SnapshotCoordinator) {
// We arrive here holding our +1 (the fetch_add in begin_operation).
// Two cases:
// - Snapshot is still in flight: back out our +1, wait for it to finish, then re-add.
......@@ -110,11 +111,7 @@ impl<O> SnapshotCoordinator<O> {
// our +1 in place; the drop balances it directly. No extra atomics needed.
let mut state = this.state.lock();
if state.snapshot_requested {
let prev = this.in_progress_operations.fetch_sub(1, Ordering::AcqRel);
if prev - 1 == SNAPSHOT_REQUESTED_BIT {
this.operations_drained.notify_all();
}
this.in_progress_operations.fetch_sub(1, Ordering::AcqRel);
this.operations_waiting.store(true, Ordering::Relaxed);
tokio::task::block_in_place(|| {
this.snapshot_completed
......@@ -126,130 +123,120 @@ impl<O> SnapshotCoordinator<O> {
this.in_progress_operations.fetch_add(1, Ordering::AcqRel);
}
}
// Slow path: a snapshot is in flight (or just requested). Back out
// the increment, wait for the snapshot to complete, then re-increment.
wait_for_snapshot_to_complete(self);
OperationGuard { coord: self }
}
/// Begin a snapshot. Sets the snapshot bit, blocks until all in-flight
/// operations have drained or suspended, and returns a [`SnapshotPhase`]
/// guard that releases the bit on drop.
/// Begin a snapshot. Wait for all admitted work to finish without preventing dependent
/// operations from entering, then atomically close admission at a zero-active boundary.
///
/// Concurrent callers panic via the debug assertion. Production callers
/// Waits for as long as it takes. If the wait gets long, `on_slow_settle` is called after
/// [`SLOW_SETTLE_REPORT`] and again each time the total wait doubles.
///
/// Concurrent callers panic. Production callers
/// must serialize themselves (see `snapshot_in_progress` lock in
/// `mod.rs`); the coordinator does not own that mutex because some
/// callers want to interleave additional work between phases.
pub fn begin_snapshot(&self) -> SnapshotPhase<'_, O> {
pub fn begin_snapshot(&self, mut on_slow_settle: impl FnMut(SlowSettle)) -> SnapshotPhase<'_> {
let mut state = self.state.lock();
// Protocol violation: callers must serialize snapshots themselves.
// Promoted from debug_assert: silently ignoring this leads directly
// to a stuck counter and a hung process.
// Callers must serialize snapshots themselves.
assert!(
!state.snapshot_requested,
"begin_snapshot called while another snapshot was already in flight"
);
state.snapshot_requested = true;
// AcqRel so the writes leading up to setting the bit are visible to
// the operation hot path's Acquire load in `snapshot_pending`.
let active = self
// Request a drain without blocking new operations that an active graph update may
// depend on. Sharing the counter means the last decrement either observes this bit
// and notifies us, or precedes this fetch_or so we observe the drained count.
let prev = self
.in_progress_operations
.fetch_or(SNAPSHOT_REQUESTED_BIT, Ordering::AcqRel);
.fetch_or(SNAPSHOT_WAITING_BIT, Ordering::AcqRel);
assert!(
(active & SNAPSHOT_REQUESTED_BIT) == 0,
"snapshot bit was already set when begin_snapshot ran: {active:#x}"
(prev & (SNAPSHOT_WAITING_BIT | SNAPSHOT_RUNNING_BIT)) == 0,
"begin_snapshot called while another snapshot was already in flight"
);
if (active & !SNAPSHOT_REQUESTED_BIT) != 0 {
// The predicate is Acquire-loaded so we synchronize with the AcqRel decrement that woke
// us. This can block for a while under load (until every in-flight operation reaches a
// suspend point or finishes), so it gets its own span for latency attribution.
let num_operations = active & !SNAPSHOT_REQUESTED_BIT;
let _span = info_span!("await operations settle", num_operations).entered();
// Release our worker thread so pending operations have it available. This preserves
// liveness: this runs as a `tokio::spawn` background job, so parking here without
// handing the worker back would starve the very operations we are waiting on.
let active_at_start = prev & OPERATION_COUNT_MASK;
let _span =
info_span!("await operations settle", num_operations = active_at_start).entered();
let wait_start = Instant::now();
let mut next_report = wait_start + self.slow_settle_report_timeout;
loop {
if self
.in_progress_operations
.compare_exchange(
SNAPSHOT_WAITING_BIT,
SNAPSHOT_RUNNING_BIT,
Ordering::AcqRel,
Ordering::Acquire,
)
.is_ok()
{
break;
}
let now = Instant::now();
if now >= next_report {
let waited = now - wait_start;
let slow_settle = SlowSettle {
waited,
active_at_start,
active_now: self.in_progress_operations.load(Ordering::Relaxed)
& OPERATION_COUNT_MASK,
};
// Don't hold the mutex while running caller code. A drain notification sent
// meanwhile isn't lost: the wait below checks the count before parking.
MutexGuard::unlocked(&mut state, || on_slow_settle(slow_settle));
next_report = now + waited;
}
// This runs in a background Tokio task; release its worker so admitted work can
// complete. The guard's drop synchronizes with this mutex when notifying. Wake up
// at `next_report` even without a notification so a long wait gets reported.
tokio::task::block_in_place(|| {
self.operations_drained.wait_while(&mut state, |_| {
(self.in_progress_operations.load(Ordering::Acquire) & !SNAPSHOT_REQUESTED_BIT)
!= 0
});
self.operations_drained.wait_while_until(
&mut state,
|_| {
(self.in_progress_operations.load(Ordering::Acquire) & OPERATION_COUNT_MASK)
!= 0
},
next_report,
);
});
}
// Snapshot ranges that follow can read the suspended_operations
// list; we leave the mutex held until the caller drops the phase.
let suspended_operations: Vec<Arc<O>> = state
.suspended_operations
.iter()
.map(|op| op.arc().clone())
.collect();
// Release the mutex now — the snapshotter does the heavy work
// without holding it. Operations attempting to start during this
// window observe the bit set and either suspend or wait on
// `snapshot_completed`.
state.snapshot_requested = true;
// Release the mutex now — the snapshotter does the heavy work without holding it.
// New operations wait for the phase to complete.
drop(state);
SnapshotPhase {
coord: self,
suspended_operations,
}
SnapshotPhase { coord: self }
}
/// Like [`begin_snapshot`](Self::begin_snapshot), but never waits: begins the snapshot only
/// if no operation is active right now, otherwise returns `None` and leaves the coordinator
/// untouched.
pub fn try_begin_snapshot(&self) -> Option<SnapshotPhase<'_>> {
let mut state = self.state.lock();
// Callers must serialize snapshots themselves.
assert!(
!state.snapshot_requested,
"begin_snapshot called while another snapshot was already in flight"
);
// Without waiting there is no need to request a drain: either nothing is active and we
// close admission immediately, or we give up without having published anything.
self.in_progress_operations
.compare_exchange(0, SNAPSHOT_RUNNING_BIT, Ordering::AcqRel, Ordering::Acquire)
.ok()?;
// Operations that see the bit before this is set block on the state mutex we hold, then
// observe the flag.
state.snapshot_requested = true;
drop(state);
Some(SnapshotPhase { coord: self })
}
}
/// Guard returned by [`SnapshotCoordinator::begin_operation`]. Decrements the
/// in-progress count on drop and notifies the snapshotter if it is waiting.
pub struct OperationGuard<'a, O> {
coord: &'a SnapshotCoordinator<O>,
}
impl<O> OperationGuard<'_, O> {
/// Suspend this operation if a snapshot is requested. Otherwise a no-op. The closure is called
/// only when actually suspending and must produce a handle to this operation so the
/// snapshotter can persist it for replay on the next startup.
pub fn suspend_point(&mut self, suspend: impl FnOnce() -> O) {
let coord = self.coord;
if !coord.snapshot_pending() {
return;
}
#[cold]
fn suspend_point_cold<O>(coord: &SnapshotCoordinator<O>, suspend: impl FnOnce() -> O) {
let mut state = coord.state.lock();
if !state.snapshot_requested {
// Race: snapshot finished between the `snapshot_pending` check
// and acquiring the mutex. Nothing to do.
return;
}
let op = Arc::new(suspend());
state
.suspended_operations
.insert(PtrEqArc::from(op.clone()));
// Decrement the count so the snapshotter can drain.
let prev = coord.in_progress_operations.fetch_sub(1, Ordering::AcqRel);
// Protocol violation if either invariant fails. Keep as a regular
// `assert!` so production builds also catch it: the alternative is
// a corrupted counter that hangs the next snapshot indefinitely.
assert!(
(prev & SNAPSHOT_REQUESTED_BIT) != 0 && (prev & !SNAPSHOT_REQUESTED_BIT) > 0,
"suspend_point called without a live operation: prev={prev:#x}"
);
if prev - 1 == SNAPSHOT_REQUESTED_BIT {
coord.operations_drained.notify_all();
}
coord.operations_waiting.store(true, Ordering::Relaxed);
// Wait for the snapshot to finish.
tokio::task::block_in_place(|| {
coord
.snapshot_completed
.wait_while(&mut state, |s| s.snapshot_requested);
});
// Resume: re-increment and remove ourselves from the suspended set.
coord.in_progress_operations.fetch_add(1, Ordering::AcqRel);
state.suspended_operations.remove(&PtrEqArc::from(op));
}
suspend_point_cold(coord, suspend);
}
pub struct OperationGuard<'a> {
coord: &'a SnapshotCoordinator,
}
impl<O> Drop for OperationGuard<'_, O> {
impl Drop for OperationGuard<'_> {
fn drop(&mut self) {
let coord = self.coord;
let prev = coord.in_progress_operations.fetch_sub(1, Ordering::AcqRel);
......@@ -257,12 +244,12 @@ impl<O> Drop for OperationGuard<'_, O> {
// promoted from debug_assert because the alternative is silently
// wrapping to usize::MAX and breaking every subsequent snapshot.
assert!(
(prev & !SNAPSHOT_REQUESTED_BIT) > 0,
(prev & OPERATION_COUNT_MASK) > 0,
"OperationGuard::drop underflow: in_progress_operations was {prev:#x}"
);
if prev - 1 == SNAPSHOT_REQUESTED_BIT {
if prev == (SNAPSHOT_WAITING_BIT | 1) {
#[cold]
fn notify_drained<O>(coord: &SnapshotCoordinator<O>) {
fn notify_drained(coord: &SnapshotCoordinator) {
// Take the state mutex around `notify_all`. This is defensive against
// `parking_lot::Condvar::notify_all`'s fast path: it does a `Relaxed` load
// on the condvar's internal `state` and short-circuits if it observes
......@@ -280,34 +267,19 @@ impl<O> Drop for OperationGuard<'_, O> {
}
/// Guard returned by [`SnapshotCoordinator::begin_snapshot`]. Holds the
/// snapshot bit; on drop, releases it and wakes any operations parked on
/// `snapshot_completed`.
pub struct SnapshotPhase<'a, O> {
coord: &'a SnapshotCoordinator<O>,
suspended_operations: Vec<Arc<O>>,
/// snapshot bit; on drop, releases it and wakes new operations.
pub struct SnapshotPhase<'a> {
coord: &'a SnapshotCoordinator,
}
impl<O> SnapshotPhase<'_, O> {
/// Operations that were suspended at the moment the snapshot started.
/// The snapshotter must persist these so they can be replayed on the
/// next startup.
#[cfg(test)]
pub fn suspended_operations(&self) -> &[Arc<O>] {
&self.suspended_operations
}
/// Take ownership of the suspended-operations list.
pub fn take_suspended_operations(&mut self) -> Vec<Arc<O>> {
std::mem::take(&mut self.suspended_operations)
}
impl SnapshotPhase<'_> {
/// Whether any operation is currently blocked waiting for this exclusion to end
pub fn operations_waiting(&self) -> bool {
self.coord.operations_waiting.load(Ordering::Relaxed)
}
}
impl<O> Drop for SnapshotPhase<'_, O> {
impl Drop for SnapshotPhase<'_> {
fn drop(&mut self) {
let mut state = self.coord.state.lock();
state.snapshot_requested = false;
......@@ -319,9 +291,9 @@ impl<O> Drop for SnapshotPhase<'_, O> {
let prev = self
.coord
.in_progress_operations
.fetch_and(!SNAPSHOT_REQUESTED_BIT, Ordering::AcqRel);
.fetch_and(!SNAPSHOT_RUNNING_BIT, Ordering::AcqRel);
assert!(
(prev & SNAPSHOT_REQUESTED_BIT) != 0,
(prev & SNAPSHOT_RUNNING_BIT) != 0,
"SnapshotPhase::drop: snapshot bit was already cleared (prev={prev:#x})"
);
// Notify everyone waiting for the snapshot to finish under the
......@@ -344,28 +316,27 @@ mod tests {
use super::*;
/// Trivial operation type for tests — just a u32 tag.
type Op = u32;
impl SnapshotCoordinator {
fn snapshot_pending(&self) -> bool {
(self.in_progress_operations.load(Ordering::Acquire) & SNAPSHOT_RUNNING_BIT) != 0
}
}
/// Spin until `snapshot_pending()` returns true, yielding occasionally so
/// we don't starve the snapshotter thread on single-core CI. Replaces
/// fixed `thread::sleep` waits — those introduced both flakiness (too
/// short) and slowness (too long).
fn wait_for_snapshot_pending<O>(coord: &SnapshotCoordinator<O>) {
while !coord.snapshot_pending() {
fn wait_for_snapshot_request(coord: &SnapshotCoordinator) {
while (coord.in_progress_operations.load(Ordering::Acquire) & SNAPSHOT_WAITING_BIT) == 0 {
thread::yield_now();
}
}
#[test]
fn no_snapshot_pending_initially() {
let coord = SnapshotCoordinator::<Op>::new();
let coord = SnapshotCoordinator::new();
assert!(!coord.snapshot_pending());
}
#[test]
fn begin_operation_fast_path() {
let coord = SnapshotCoordinator::<Op>::new();
let coord = SnapshotCoordinator::new();
let g = coord.begin_operation();
assert_eq!(coord.in_progress_operations.load(Ordering::Acquire), 1);
drop(g);
......@@ -374,17 +345,20 @@ mod tests {
#[test]
fn snapshot_with_no_ops_proceeds_immediately() {
let coord = SnapshotCoordinator::<Op>::new();
let phase = coord.begin_snapshot();
let coord = SnapshotCoordinator::new();
let phase = coord.begin_snapshot(|_| {});
assert!(coord.snapshot_pending());
assert!(phase.suspended_operations().is_empty());
assert_eq!(
coord.in_progress_operations.load(Ordering::Acquire),
SNAPSHOT_RUNNING_BIT
);
drop(phase);
assert!(!coord.snapshot_pending());
}
#[test]
fn snapshot_waits_for_ops_to_drain() {
let coord = Arc::new(SnapshotCoordinator::<Op>::new());
let coord = Arc::new(SnapshotCoordinator::new());
let g = coord.begin_operation();
let started_snapshot = Arc::new(AtomicUsize::new(0));
......@@ -393,15 +367,18 @@ mod tests {
let snap_thread = thread::spawn({
let started_snapshot = started_snapshot.clone();
move || {
let _phase = coord2.begin_snapshot();
let _phase = coord2.begin_snapshot(|_| {});
started_snapshot.store(1, Ordering::Release);
}
});
// Wait for the snapshotter to set the bit. It can't make progress
// past begin_snapshot while we hold `g`, so started_snapshot must
// still be 0.
wait_for_snapshot_pending(&coord);
// New work must remain admitted while the existing operation is running.
wait_for_snapshot_request(&coord);
assert!(!coord.snapshot_pending());
assert_eq!(
coord.in_progress_operations.load(Ordering::Acquire),
SNAPSHOT_WAITING_BIT | 1
);
assert_eq!(started_snapshot.load(Ordering::Acquire), 0);
// Drop the operation — snapshotter should now proceed.
......@@ -412,8 +389,8 @@ mod tests {
#[test]
fn new_operation_blocks_during_snapshot() {
let coord = Arc::new(SnapshotCoordinator::<Op>::new());
let phase = coord.begin_snapshot();
let coord = Arc::new(SnapshotCoordinator::new());
let phase = coord.begin_snapshot(|_| {});
let started_op = Arc::new(AtomicUsize::new(0));
let arrived = Arc::new(AtomicUsize::new(0));
......@@ -454,53 +431,34 @@ mod tests {
}
#[test]
fn suspend_point_lets_snapshot_proceed() {
let coord = Arc::new(SnapshotCoordinator::<Op>::new());
let mut g = coord.begin_operation();
let snapshotter_done = Arc::new(AtomicUsize::new(0));
let coord_snap = coord.clone();
let snap_thread = thread::spawn({
let snapshotter_done = snapshotter_done.clone();
move || {
let phase = coord_snap.begin_snapshot();
assert_eq!(
phase.suspended_operations().len(),
1,
"must record the suspended operation for replay"
);
snapshotter_done.store(1, Ordering::Release);
// Hold the snapshot for a moment so the suspend_point thread
// observes `snapshot_requested == true` after waking.
thread::sleep(Duration::from_millis(20));
}
});
wait_for_snapshot_pending(&coord);
// The phase is waiting for our operation to drain; suspending should let it proceed.
let recorded = Arc::new(AtomicUsize::new(0));
g.suspend_point({
let recorded = recorded.clone();
move || {
recorded.fetch_add(1, Ordering::Release);
42u32
}
fn snapshot_waits_for_dependent_operations() {
run_with_timeout("dependent operations", Duration::from_secs(10), || {
let coord = Arc::new(SnapshotCoordinator::new());
let removal = coord.begin_operation();
let done = Arc::new(AtomicBool::new(false));
let snap_coord = coord.clone();
let done_at_snapshot = done.clone();
let snapshot = thread::spawn(move || {
let _phase = snap_coord.begin_snapshot(|_| {});
assert!(done_at_snapshot.load(Ordering::Acquire));
});
wait_for_snapshot_request(&coord);
// The add arrives after the snapshot was requested, but the active removal
// depends on it. Closing admission before this point would deadlock.
let add = coord.begin_operation();
assert_eq!(
coord.in_progress_operations.load(Ordering::Acquire),
SNAPSHOT_WAITING_BIT | 2
);
done.store(true, Ordering::Release);
drop(add);
assert_eq!(
coord.in_progress_operations.load(Ordering::Acquire),
SNAPSHOT_WAITING_BIT | 1
);
drop(removal);
snapshot.join().unwrap();
});
// `suspend_point` returns only once the phase has finished.
assert_eq!(
snapshotter_done.load(Ordering::Acquire),
1,
"suspend_point must not return before the phase completes"
);
assert_eq!(
recorded.load(Ordering::Acquire),
1,
"the suspend closure must run so the operation is recorded for a possible snapshot"
);
snap_thread.join().unwrap();
drop(g);
}
/// Run `body` on a worker thread and wait up to `timeout` for it to
......@@ -546,7 +504,7 @@ mod tests {
)]
fn stress_no_missed_wakeups() {
run_with_timeout("stress_no_missed_wakeups", Duration::from_secs(60), || {
let coord = Arc::new(SnapshotCoordinator::<Op>::new());
let coord = Arc::new(SnapshotCoordinator::new());
let snapshot_lock = Arc::new(Mutex::new(()));
let stop = Arc::new(AtomicBool::new(false));
let snap_count = Arc::new(AtomicUsize::new(0));
......@@ -572,7 +530,7 @@ mod tests {
move || {
for _ in 0..200 {
let _ser = snapshot_lock.lock();
let _phase = coord.begin_snapshot();
let _phase = coord.begin_snapshot(|_| {});
snap_count.fetch_add(1, Ordering::Relaxed);
}
}
......@@ -616,7 +574,7 @@ mod tests {
// Stress test: hammer the protocol from many threads.
// The coordinator does not serialize concurrent snapshotters (callers
// are expected to do that with their own mutex), so we use one here.
let coord = Arc::new(SnapshotCoordinator::<Op>::new());
let coord = Arc::new(SnapshotCoordinator::new());
let snapshot_lock = Arc::new(Mutex::new(()));
let counter = Arc::new(AtomicUsize::new(0));
......@@ -640,13 +598,24 @@ mod tests {
move || {
for _ in 0..50 {
let _ser = snapshot_lock.lock();
let _phase = coord.begin_snapshot();
let _phase = coord.begin_snapshot(|_| {});
// Pretend to do snapshot work.
thread::sleep(Duration::from_micros(10));
}
}
}));
}
// Attempts that frequently give up must leave the counter consistent.
handles.push(thread::spawn({
let coord = coord.clone();
let snapshot_lock = snapshot_lock.clone();
move || {
for _ in 0..100 {
let _ser = snapshot_lock.lock();
drop(coord.try_begin_snapshot());
}
}
}));
for h in handles {
h.join().unwrap();
......@@ -661,7 +630,7 @@ mod tests {
#[test]
fn operations_waiting_tracks_blocked_operations() {
let coord = Arc::new(SnapshotCoordinator::<Op>::new());
let coord = Arc::new(SnapshotCoordinator::new());
// Fast path: no exclusion in flight, so these never blocked and are not waiters.
let unblocked = coord.begin_operation();
......@@ -671,7 +640,7 @@ mod tests {
);
drop(unblocked);
let phase = coord.begin_snapshot();
let phase = coord.begin_snapshot(|_| {});
assert!(
!phase.operations_waiting(),
"holding the exclusion alone is not a waiter"
......@@ -696,11 +665,71 @@ mod tests {
op_thread.join().unwrap();
}
#[test]
fn slow_settle_is_reported() {
const SLOW_SETTLE_TIME: Duration = Duration::from_millis(200);
run_with_timeout("slow settle", Duration::from_secs(10), || {
let coord = Arc::new(
SnapshotCoordinator::new_with_custom_slow_settle_report_timeout(SLOW_SETTLE_TIME),
);
let op = coord.begin_operation();
let reports = Arc::new(Mutex::new(Vec::new()));
let snapshot = thread::spawn({
let coord = coord.clone();
let reports = reports.clone();
move || {
drop(coord.begin_snapshot(|slow| {
reports
.lock()
.push((slow.waited, slow.active_at_start, slow.active_now))
}));
}
});
while reports.lock().is_empty() {
thread::sleep(Duration::from_millis(50));
}
// An operation can still be admitted after the report released the mutex.
drop(coord.begin_operation());
drop(op);
snapshot.join().unwrap();
let reports = reports.lock();
assert_eq!(reports.len(), 1);
let (waited, active_at_start, active_now) = reports[0];
assert!(waited >= SLOW_SETTLE_TIME);
assert_eq!((active_at_start, active_now), (1, 1));
});
}
#[test]
fn try_begin_snapshot_proceeds_when_idle() {
let coord = SnapshotCoordinator::new();
let phase = coord.try_begin_snapshot().expect("no operation is active");
assert!(coord.snapshot_pending());
drop(phase);
assert_eq!(coord.in_progress_operations.load(Ordering::Acquire), 0);
}
#[test]
fn try_begin_snapshot_gives_up_while_busy() {
let coord = SnapshotCoordinator::new();
let op = coord.begin_operation();
assert!(coord.try_begin_snapshot().is_none());
// Giving up leaves no trace: only the active operation remains.
assert_eq!(coord.in_progress_operations.load(Ordering::Acquire), 1);
// Admission was never closed.
drop(coord.begin_operation());
drop(op);
assert_eq!(coord.in_progress_operations.load(Ordering::Acquire), 0);
// A later snapshot is unaffected by the abandoned one.
drop(coord.begin_snapshot(|_| {}));
assert_eq!(coord.in_progress_operations.load(Ordering::Acquire), 0);
}
#[test]
#[should_panic(expected = "already in flight")]
fn overlapping_exclusions_panic() {
let coord = SnapshotCoordinator::<Op>::new();
let _first = coord.begin_snapshot();
let _second = coord.begin_snapshot();
let coord = SnapshotCoordinator::new();
let _first = coord.begin_snapshot(|_| {});
let _second = coord.begin_snapshot(|_| {});
}
}
......@@ -18,7 +18,7 @@ use turbo_tasks::{
use crate::{
GitVersionInfo,
backend::{AnyOperation, SpecificTaskDataCategory, TtlCounter, storage_schema::TaskStorage},
backend::{SpecificTaskDataCategory, TtlCounter, storage_schema::TaskStorage},
backing_storage::{SnapshotItem, SnapshotMeta, compute_task_type_hash_from_components},
database::{
db_invalidation::{StartupCacheState, check_db_invalidation_and_cleanup, invalidate_db},
......@@ -34,9 +34,8 @@ use crate::{
#[derive(Clone, Copy)]
#[repr(u8)]
enum InfraKey {
Operations = 0,
NextFreeTaskId = 1,
GcRoots = 2,
NextFreeTaskId = 0,
GcRoots = 1,
}
impl InfraKey {
......@@ -237,19 +236,6 @@ impl TurboBackingStorage {
.map_or(Ok(TaskId::MIN), TaskId::try_from)?)
}
pub(crate) fn uncompleted_operations(&self) -> Result<Vec<AnyOperation>> {
fn get(database: &TurboKeyValueDatabase) -> Result<Vec<AnyOperation>> {
let Some(operations) =
database.get(KeySpace::Infra, InfraKey::Operations.key().as_ref())?
else {
return Ok(Vec::new());
};
let operations = turbo_bincode_decode(operations.borrow())?;
Ok(operations)
}
get(&self.inner.database).context("Unable to read uncompleted operations from database")
}
/// Reads the persisted GC roots set (see [`InfraKey::GcRoots`]). Empty on a fresh database.
pub(crate) fn roots(&self) -> Result<Vec<(TaskId, TtlCounter)>> {
fn get(database: &TurboKeyValueDatabase) -> Result<Vec<(TaskId, TtlCounter)>> {
......@@ -265,14 +251,13 @@ impl TurboBackingStorage {
pub(crate) fn save_snapshot<I>(
&self,
operations: Vec<Arc<AnyOperation>>,
roots: Option<Vec<(TaskId, TtlCounter)>>,
snapshots: Vec<I>,
) -> Result<SnapshotMeta>
where
I: IntoIterator<Item = SnapshotItem> + Send + Sync,
{
let _span = tracing::info_span!("save snapshot", operations = operations.len()).entered();
let _span = tracing::info_span!("save snapshot").entered();
let batch = self.inner.database.write_batch()?;
{
......@@ -367,7 +352,7 @@ impl TurboBackingStorage {
let mut next_task_id = get_next_free_task_id(&batch)?;
next_task_id = next_task_id.max(snapshot_meta.max_next_task_id + 1);
save_infra(&batch, next_task_id, operations, roots)?;
save_infra(&batch, next_task_id, roots)?;
{
let _span = tracing::trace_span!("commit").entered();
// Byte totals are the physical on-disk bytes (post-compression, including .sst /
......@@ -494,7 +479,6 @@ fn get_next_free_task_id(batch: &TurboWriteBatch<'_>) -> Result<u32, anyhow::Err
fn save_infra(
batch: &TurboWriteBatch<'_>,
next_task_id: u32,
operations: Vec<Arc<AnyOperation>>,
roots: Option<Vec<(TaskId, TtlCounter)>>,
) -> Result<(), anyhow::Error> {
batch
......@@ -504,19 +488,6 @@ fn save_infra(
WriteBuffer::Borrowed(&next_task_id.to_le_bytes()),
)
.context("Unable to write next free task id")?;
{
let _span =
tracing::trace_span!("update operations", operations = operations.len()).entered();
let operations =
turbo_bincode_encode(&operations).context("Unable to serialize operations")?;
batch
.put(
KeySpace::Infra,
WriteBuffer::Borrowed(InfraKey::Operations.key().as_ref()),
WriteBuffer::SmallVec(operations),
)
.context("Unable to write operations")?;
}
if let Some(roots) = roots {
let _span = tracing::trace_span!("update roots", roots = roots.len()).entered();
let roots = turbo_bincode_encode(&roots).context("Unable to serialize GC roots")?;
......@@ -731,7 +702,6 @@ mod tests {
// Snapshot with no task data, just the one deletion.
storage.save_snapshot(
Vec::new(),
None,
vec![vec![SnapshotItem::Delete {
task_id: deleted_id,
......
......@@ -2,7 +2,6 @@ pub mod dash_map_drop_contents;
pub mod dash_map_entry;
pub mod dash_map_multi;
pub mod markdown_table;
pub mod ptr_eq_arc;
pub mod shard_amount;
pub mod stopwatch;
pub mod swap_retain;
......
use std::{
hash::{Hash, Hasher},
ops::Deref,
sync::Arc,
};
pub struct PtrEqArc<T>(Arc<T>);
impl<T> PtrEqArc<T> {
pub fn arc(&self) -> &Arc<T> {
&self.0
}
}
impl<T> From<Arc<T>> for PtrEqArc<T> {
fn from(value: Arc<T>) -> Self {
Self(value)
}
}
impl<T> Deref for PtrEqArc<T> {
type Target = Arc<T>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> Clone for PtrEqArc<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T> PartialEq for PtrEqArc<T> {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl<T> Eq for PtrEqArc<T> {}
impl<T> Hash for PtrEqArc<T> {
fn hash<H: Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.0).hash(state)
}
}
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