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