Unverified Commit c82d85e6 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

[Turbopack] add active_counter to keep tasks active (#74772)

Rename AggregateRoot to Activeness and split into both sources

improve readablility

add active_counter as source of activeness

add Debug for DequeSet

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the PR.
- Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to understand the PR)
- When linking to a Slack thread, you might want to share details of the conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent 3256ff86
......@@ -44,13 +44,13 @@ use crate::{
ExecuteContext, ExecuteContextImpl, Operation, OutdatedEdge, TaskDirtyCause, TaskGuard,
},
persisted_storage_log::PersistedStorageLog,
storage::{get, get_many, get_mut, iter_many, remove, Storage},
storage::{get, get_many, get_mut, get_mut_or_insert_with, iter_many, remove, Storage},
},
backing_storage::BackingStorage,
data::{
ActiveType, AggregationNumber, CachedDataItem, CachedDataItemKey, CachedDataItemType,
ActivenessState, AggregationNumber, CachedDataItem, CachedDataItemKey, CachedDataItemType,
CachedDataItemValue, CachedDataItemValueRef, CachedDataUpdate, CellRef, CollectibleRef,
CollectiblesRef, DirtyState, InProgressCellState, InProgressState, OutputValue, RootState,
CollectiblesRef, DirtyState, InProgressCellState, InProgressState, OutputValue, RootType,
},
utils::{bi_map::BiMap, chunked_vec::ChunkedVec, ptr_eq_arc::PtrEqArc, sharded::Sharded},
};
......@@ -447,7 +447,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
.unwrap_or_default()
.get(self.session_id);
if dirty_tasks > 0 || is_dirty {
let root = get!(task, AggregateRoot);
let root = get!(task, Activeness);
let mut task_ids_to_schedule: Vec<_> = Vec::new();
// When there are dirty task, subscribe to the all_clean_event
let root = if let Some(root) = root {
......@@ -456,10 +456,9 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
// If we don't have a root state, add one. This also makes sure all tasks stay
// active and this task won't stale. CachedActiveUntilClean
// is automatically removed when this task is clean.
task.add_new(CachedDataItem::AggregateRoot {
value: RootState::new(ActiveType::CachedActiveUntilClean, task_id),
});
// A newly added AggregateRoot need to make sure to schedule the tasks
get_mut_or_insert_with!(task, Activeness, || ActivenessState::new(task_id))
.set_active_until_clean();
// A newly added Activeness need to make sure to schedule the tasks
task_ids_to_schedule = get_many!(
task,
AggregatedDirtyContainer {
......@@ -471,7 +470,7 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
if is_dirty {
task_ids_to_schedule.push(task_id);
}
get!(task, AggregateRoot).unwrap()
get!(task, Activeness).unwrap()
};
let listener = root.all_clean_event.listen_with_note(move || {
format!(
......@@ -1373,10 +1372,11 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
};
if !aggregated_update.is_zero() {
if aggregated_update.get(self.session_id) < 0 {
if let Some(root_state) = get!(task, AggregateRoot) {
if let Some(root_state) = get_mut!(task, Activeness) {
root_state.all_clean_event.notify(usize::MAX);
if matches!(root_state.ty, ActiveType::CachedActiveUntilClean) {
task.remove(&CachedDataItemKey::AggregateRoot {});
root_state.unset_active_until_clean();
if root_state.is_empty() {
task.remove(&CachedDataItemKey::Activeness {});
}
}
}
......@@ -1700,8 +1700,8 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
fn create_transient_task(&self, task_type: TransientTaskType) -> TaskId {
let task_id = self.transient_task_id_factory.get();
let root_type = match task_type {
TransientTaskType::Root(_) => ActiveType::RootTask,
TransientTaskType::Once(_) => ActiveType::OnceTask,
TransientTaskType::Root(_) => RootType::RootTask,
TransientTaskType::Once(_) => RootType::OnceTask,
};
self.transient_tasks.insert(
task_id,
......@@ -1719,13 +1719,12 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
effective: u32::MAX,
},
});
task.add(CachedDataItem::AggregateRoot {
value: RootState::new(root_type, task_id),
task.add(CachedDataItem::Activeness {
value: ActivenessState::new_root(root_type, task_id),
});
task.add(CachedDataItem::new_scheduled(move || match root_type {
ActiveType::RootTask => "Root Task".to_string(),
ActiveType::OnceTask => "Once Task".to_string(),
_ => unreachable!(),
RootType::RootTask => "Root Task".to_string(),
RootType::OnceTask => "Once Task".to_string(),
}));
}
task_id
......@@ -1744,11 +1743,12 @@ impl<B: BackingStorage> TurboTasksBackendInner<B> {
dirty_containers.get(self.session_id) > 0
});
if is_dirty || has_dirty_containers {
if let Some(root_state) = get_mut!(task, AggregateRoot) {
if let Some(root_state) = get_mut!(task, Activeness) {
// We will finish the task, but it would be removed after the task is done
root_state.ty = ActiveType::CachedActiveUntilClean;
root_state.unset_root_type();
root_state.set_active_until_clean();
};
} else if let Some(root_state) = remove!(task, AggregateRoot) {
} else if let Some(root_state) = remove!(task, Activeness) {
// Technically nobody should be listening to this event, but just in case
// we notify it anyway
root_state.all_clean_event.notify(usize::MAX);
......
......@@ -18,6 +18,7 @@ use turbo_tasks::{FxIndexMap, SessionId, TaskId, TraitTypeId};
use crate::{
backend::{
get_mut, get_mut_or_insert_with,
operation::{
invalidate::{make_task_dirty, TaskDirtyCause},
ExecuteContext, Operation, TaskGuard,
......@@ -26,8 +27,8 @@ use crate::{
TaskDataCategory,
},
data::{
ActiveType, AggregationNumber, CachedDataItem, CachedDataItemKey, CollectibleRef,
DirtyContainerCount, RootState,
ActivenessState, AggregationNumber, CachedDataItem, CachedDataItemKey, CollectibleRef,
DirtyContainerCount,
},
utils::deque_set::DequeSet,
};
......@@ -137,6 +138,14 @@ pub enum AggregationUpdateJob {
task_ids: SmallVec<[TaskId; 4]>,
collectible_type: TraitTypeId,
},
/// Increases the active counter of the task
IncreaseActiveCount { task: TaskId },
/// Increases the active counters of the tasks
IncreaseActiveCounts { task_ids: Vec<TaskId> },
/// Decreases the active counter of the task
DecreaseActiveCount { task: TaskId },
/// Decreases the active counters of the tasks
DecreaseActiveCounts { task_ids: Vec<TaskId> },
/// Balances the edges of the graph. This checks if the graph invariant is still met for this
/// edge and coverts a upper edge to a follower edge or vice versa. Balancing might triggers
/// more changes to the structure.
......@@ -244,9 +253,9 @@ impl AggregatedDataUpdate {
let mut result = Self::default();
if let Some((dirty_container_id, count)) = dirty_container_update {
// When a dirty container count is increased and the task is considered as active
// `AggregateRoot` 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.get(session_id);
if current_session_update > 0 && task.has_key(&CachedDataItemKey::AggregateRoot {}) {
if current_session_update > 0 && task.has_key(&CachedDataItemKey::Activeness {}) {
queue.push_find_and_schedule_dirty(*dirty_container_id)
}
......@@ -286,10 +295,11 @@ impl AggregatedDataUpdate {
if count.get(session_id) < 0 {
// When the current task is no longer dirty, we need to fire the aggregate
// root events and do some cleanup
if let Some(root_state) = get!(task, AggregateRoot) {
if let Some(root_state) = get_mut!(task, Activeness) {
root_state.all_clean_event.notify(usize::MAX);
if matches!(root_state.ty, ActiveType::CachedActiveUntilClean) {
task.remove(&CachedDataItemKey::AggregateRoot {});
root_state.unset_active_until_clean();
if root_state.is_empty() {
task.remove(&CachedDataItemKey::Activeness {});
}
}
}
......@@ -774,6 +784,32 @@ impl AggregationUpdateQueue {
);
}
}
AggregationUpdateJob::DecreaseActiveCount { task } => {
self.decrease_active_count(ctx, task);
}
AggregationUpdateJob::DecreaseActiveCounts { mut task_ids } => {
if let Some(task_id) = task_ids.pop() {
self.decrease_active_count(ctx, task_id);
if !task_ids.is_empty() {
self.jobs.push_front(AggregationUpdateJobItem::new(
AggregationUpdateJob::DecreaseActiveCounts { task_ids },
));
}
}
}
AggregationUpdateJob::IncreaseActiveCount { task } => {
self.increase_active_count(ctx, task);
}
AggregationUpdateJob::IncreaseActiveCounts { mut task_ids } => {
if let Some(task_id) = task_ids.pop() {
self.increase_active_count(ctx, task_id);
if !task_ids.is_empty() {
self.jobs.push_front(AggregationUpdateJobItem::new(
AggregationUpdateJob::IncreaseActiveCounts { task_ids },
));
}
}
}
}
false
} else if !self.number_updates.is_empty() {
......@@ -905,6 +941,8 @@ impl AggregationUpdateQueue {
// followers
let data = AggregatedDataUpdate::from_task(&mut task);
let followers = get_followers(&task);
let has_active_count =
get!(task, Activeness).is_some_and(|a| a.active_counter > 0);
let diff = data.apply(&mut upper, ctx.session_id(), self);
if !upper_ids.is_empty() && !diff.is_empty() {
......@@ -915,14 +953,20 @@ impl AggregationUpdateQueue {
});
}
if !followers.is_empty() {
if has_active_count {
// TODO combine both operations to avoid the clone
self.push(AggregationUpdateJob::IncreaseActiveCounts {
task_ids: followers.clone(),
})
}
self.push(AggregationUpdateJob::InnerOfUpperHasNewFollowers {
upper_id,
new_follower_ids: followers,
});
}
if upper.has_key(&CachedDataItemKey::AggregateRoot {}) {
// If the upper node is an `AggregateRoot` we need to schedule the
if upper.has_key(&CachedDataItemKey::Activeness {}) {
// If the upper node is has `Activeness` we need to schedule the
// dirty tasks in the new dirty container
self.push_find_and_schedule_dirty(task_id);
}
......@@ -958,6 +1002,10 @@ impl AggregationUpdateQueue {
// Add the same amount of follower edges
if update_count!(upper, Follower { task: task_id }, count) {
// update active count
if get!(task, Activeness).is_some_and(|a| a.active_counter > 0) {
self.push(AggregationUpdateJob::IncreaseActiveCount { task: task_id });
}
// notify uppers about new follower
if !upper_ids.is_empty() {
self.push(AggregationUpdateJob::InnerOfUppersHasNewFollower {
......@@ -1025,14 +1073,17 @@ impl AggregationUpdateQueue {
}
}
if is_aggregating_node(get_aggregation_number(&task)) {
// if it has an `AggregateRoot` we can skip visiting the nested nodes since
// this would already be scheduled by the `AggregateRoot`
if !task.has_key(&CachedDataItemKey::AggregateRoot {}) {
// if it has `Activeness` we can skip visiting the nested nodes since
// this would already be scheduled by the `Activeness`
if !task.has_key(&CachedDataItemKey::Activeness {}) {
let dirty_containers: Vec<_> = get_many!(task, AggregatedDirtyContainer { task } count if count.get(session_id) > 0 => task);
if !dirty_containers.is_empty() || dirty {
task.insert(CachedDataItem::AggregateRoot {
value: RootState::new(ActiveType::CachedActiveUntilClean, task_id),
let mut activeness_state = ActivenessState::new(task_id);
activeness_state.set_active_until_clean();
task.insert(CachedDataItem::Activeness {
value: activeness_state,
});
drop(task);
self.extend_find_and_schedule_dirty(dirty_containers);
}
......@@ -1135,7 +1186,17 @@ impl AggregationUpdateQueue {
},
-1
) {
let has_active_count =
get!(upper, Activeness).is_some_and(|a| a.active_counter > 0);
let upper_ids = get_uppers(&upper);
drop(upper);
// update active count
if has_active_count {
self.push(AggregationUpdateJob::DecreaseActiveCount {
task: lost_follower_id,
});
}
// notify uppers about new follower
if !upper_ids.is_empty() {
self.push(AggregationUpdateJob::InnerOfUppersLostFollower {
upper_ids,
......@@ -1220,6 +1281,16 @@ impl AggregationUpdateQueue {
-1
) {
let upper_ids = get_uppers(&upper);
let has_active_count =
get!(upper, Activeness).is_some_and(|a| a.active_counter > 0);
drop(upper);
// update active count
if has_active_count {
self.push(AggregationUpdateJob::DecreaseActiveCount {
task: lost_follower_id,
});
}
// notify uppers about new follower
if !upper_ids.is_empty() {
self.push(AggregationUpdateJob::InnerOfUppersLostFollower {
upper_ids,
......@@ -1245,7 +1316,8 @@ impl AggregationUpdateQueue {
get_aggregation_number(&follower)
};
let mut upper_upper_ids_with_new_follower = Vec::new();
let mut is_aggregate_root = false;
let mut tasks_for_which_increment_active_count = Vec::new();
let mut is_active = false;
swap_retain(&mut upper_ids, |&mut upper_id| {
let mut upper = ctx.task(upper_id, TaskDataCategory::Meta);
// decide if it should be an inner or follower
......@@ -1262,6 +1334,11 @@ impl AggregationUpdateQueue {
},
1
) {
// update active count
if get!(upper, Activeness).is_some_and(|a| a.active_counter > 0) {
tasks_for_which_increment_active_count.push(new_follower_id);
}
// notify uppers about new follower
upper_upper_ids_with_new_follower.extend(iter_uppers(&upper));
}
......@@ -1277,8 +1354,8 @@ impl AggregationUpdateQueue {
false
} else {
// It's an inner node, continue with the list
if upper.has_key(&CachedDataItemKey::AggregateRoot {}) {
is_aggregate_root = true;
if upper.has_key(&CachedDataItemKey::Activeness {}) {
is_active = true;
}
true
}
......@@ -1346,9 +1423,14 @@ impl AggregationUpdateQueue {
drop(follower);
}
}
if is_aggregate_root {
if is_active {
self.push_find_and_schedule_dirty(new_follower_id);
}
if !tasks_for_which_increment_active_count.is_empty() {
self.push(AggregationUpdateJob::IncreaseActiveCounts {
task_ids: tasks_for_which_increment_active_count,
});
}
if !upper_upper_ids_with_new_follower.is_empty() {
#[cfg(feature = "trace_aggregation_update")]
let _span = trace_span!("new follower").entered();
......@@ -1381,12 +1463,15 @@ impl AggregationUpdateQueue {
.collect::<Vec<_>>();
let mut new_followers_of_upper_uppers = Vec::new();
let is_aggregate_root;
let is_active;
let has_active_count;
let mut upper_upper_ids_for_new_followers = Vec::new();
let upper_aggregation_number;
{
let mut upper = ctx.task(upper_id, TaskDataCategory::Meta);
is_aggregate_root = upper.has_key(&CachedDataItemKey::AggregateRoot {});
let activeness_state = get!(upper, Activeness);
is_active = activeness_state.is_some();
has_active_count = activeness_state.is_some_and(|a| a.active_counter > 0);
// decide if it should be an inner or follower
upper_aggregation_number = get_aggregation_number(&upper);
......@@ -1493,7 +1578,7 @@ impl AggregationUpdateQueue {
});
}
}
if is_aggregate_root {
if is_active {
self.extend_find_and_schedule_dirty(
followers_with_aggregation_number
.into_iter()
......@@ -1501,14 +1586,23 @@ impl AggregationUpdateQueue {
);
}
}
// notify uppers about new follower
if !upper_upper_ids_for_new_followers.is_empty() {
if !new_followers_of_upper_uppers.is_empty() {
#[cfg(feature = "trace_aggregation_update")]
let _span = trace_span!("new follower").entered();
self.push(AggregationUpdateJob::InnerOfUppersHasNewFollowers {
upper_ids: upper_upper_ids_for_new_followers,
new_follower_ids: new_followers_of_upper_uppers,
});
// update active count
if has_active_count {
// TODO combine both operations to avoid the clone
self.push(AggregationUpdateJob::IncreaseActiveCounts {
task_ids: new_followers_of_upper_uppers.clone(),
});
}
// notify uppers about new follower
if !upper_upper_ids_for_new_followers.is_empty() {
self.push(AggregationUpdateJob::InnerOfUppersHasNewFollowers {
upper_ids: upper_upper_ids_for_new_followers,
new_follower_ids: new_followers_of_upper_uppers,
});
}
}
}
......@@ -1527,7 +1621,7 @@ impl AggregationUpdateQueue {
};
let mut upper = ctx.task(upper_id, TaskDataCategory::Meta);
if upper.has_key(&CachedDataItemKey::AggregateRoot {}) {
if upper.has_key(&CachedDataItemKey::Activeness {}) {
self.push_find_and_schedule_dirty(new_follower_id);
}
// decide if it should be an inner or follower
......@@ -1547,8 +1641,17 @@ impl AggregationUpdateQueue {
},
1
) {
let has_active_count =
get!(upper, Activeness).is_some_and(|a| a.active_counter > 0);
let upper_ids = get_uppers(&upper);
drop(upper);
// update active count
if has_active_count {
self.push(AggregationUpdateJob::IncreaseActiveCount {
task: new_follower_id,
});
}
// notify uppers about new follower
if !upper_ids.is_empty() {
self.push(AggregationUpdateJob::InnerOfUppersHasNewFollower {
upper_ids,
......@@ -1606,6 +1709,52 @@ impl AggregationUpdateQueue {
}
}
fn decrease_active_count(&mut self, ctx: &mut impl ExecuteContext, task_id: TaskId) {
#[cfg(feature = "trace_aggregation_update")]
let _span = trace_span!("decrease active count").entered();
let mut task = ctx.task(task_id, TaskDataCategory::Meta);
let state = get_mut_or_insert_with!(task, Activeness, || ActivenessState::new(task_id));
let is_zero = state.decrement_active_counter();
let is_empty = state.is_empty();
if is_empty {
task.remove(&CachedDataItemKey::Activeness {});
}
if is_zero {
let followers = get_followers(&task);
drop(task);
if !followers.is_empty() {
self.push(AggregationUpdateJob::DecreaseActiveCounts {
task_ids: followers,
});
}
}
}
fn increase_active_count(&mut self, ctx: &mut impl ExecuteContext, task_id: TaskId) {
#[cfg(feature = "trace_aggregation_update")]
let _span = trace_span!("increase active count").entered();
let mut task = ctx.task(task_id, TaskDataCategory::Meta);
let state = get_mut_or_insert_with!(task, Activeness, || ActivenessState::new(task_id));
let is_positive = state.increment_active_counter();
let is_empty = state.is_empty();
// This can happen if active count is negative before
if is_empty {
task.remove(&CachedDataItemKey::Activeness {});
}
if is_positive {
let followers = get_followers(&task);
drop(task);
if !followers.is_empty() {
self.push(AggregationUpdateJob::IncreaseActiveCounts {
task_ids: followers,
});
}
self.push_find_and_schedule_dirty(task_id);
}
}
fn update_aggregation_number(
&mut self,
ctx: &mut impl ExecuteContext,
......
......@@ -5,6 +5,7 @@ use turbo_tasks::{TaskId, ValueTypeId};
use crate::{
backend::{
get,
operation::{
aggregation_update::{
get_aggregation_number, get_uppers, is_aggregating_node, AggregationUpdateJob,
......@@ -89,6 +90,13 @@ impl Operation for CleanupOldEdgesOperation {
});
} else {
let upper_ids = get_uppers(&task);
if get!(task, Activeness).is_some_and(|a| a.active_counter > 0)
{
// TODO combine both operations to avoid the clone
queue.push(AggregationUpdateJob::DecreaseActiveCounts {
task_ids: children.clone(),
});
}
queue.push(AggregationUpdateJob::InnerOfUppersLostFollowers {
upper_ids,
lost_follower_ids: children,
......
......@@ -60,6 +60,12 @@ impl ConnectChildOperation {
}) {
let mut queue = AggregationUpdateQueue::new();
if get!(parent_task, Activeness).is_some_and(|a| a.active_counter > 0) {
queue.push(AggregationUpdateJob::IncreaseActiveCount {
task: child_task_id,
})
}
// Get the children count
let children_count = count!(parent_task, Child);
......
......@@ -232,7 +232,7 @@ pub fn make_task_dirty_internal(
AggregatedDataUpdate::new().dirty_container_update(task_id, aggregated_update),
));
}
task.has_key(&CachedDataItemKey::AggregateRoot {})
task.has_key(&CachedDataItemKey::Activeness {})
} else {
true
};
......
......@@ -370,6 +370,11 @@ pub trait TaskGuard: Debug {
fn remove(&mut self, key: &CachedDataItemKey) -> Option<CachedDataItemValue>;
fn get(&self, key: &CachedDataItemKey) -> Option<CachedDataItemValueRef<'_>>;
fn get_mut(&mut self, key: &CachedDataItemKey) -> Option<CachedDataItemValueRefMut<'_>>;
fn get_mut_or_insert_with(
&mut self,
key: &CachedDataItemKey,
insert: impl FnOnce() -> CachedDataItemValue,
) -> CachedDataItemValueRefMut<'_>;
fn has_key(&self, key: &CachedDataItemKey) -> bool;
fn count(&self, ty: CachedDataItemType) -> usize;
fn iter(
......@@ -596,6 +601,15 @@ impl<B: BackingStorage> TaskGuard for TaskGuardImpl<'_, B> {
self.task.get_mut(key)
}
fn get_mut_or_insert_with(
&mut self,
key: &CachedDataItemKey,
insert: impl FnOnce() -> CachedDataItemValue,
) -> CachedDataItemValueRefMut<'_> {
self.check_access(key.category());
self.task.get_mut_or_insert_with(key, insert)
}
fn has_key(&self, key: &CachedDataItemKey) -> bool {
self.check_access(key.category());
self.task.has_key(key)
......
......@@ -193,6 +193,15 @@ impl InnerStorage {
self.get_map_mut(key.ty()).and_then(|m| m.get_mut(key))
}
pub fn get_mut_or_insert_with(
&mut self,
key: &CachedDataItemKey,
f: impl FnOnce() -> CachedDataItemValue,
) -> CachedDataItemValueRefMut<'_> {
self.get_or_create_map_mut(key.ty())
.get_mut_or_insert_with(key, f)
}
pub fn has_key(&self, key: &CachedDataItemKey) -> bool {
self.get_map(key.ty())
.map(|m| m.contains_key(key))
......@@ -366,6 +375,24 @@ macro_rules! get_mut {
};
}
macro_rules! get_mut_or_insert_with {
($task:ident, $key:ident $input:tt, $f:expr) => {{
#[allow(unused_imports)]
use $crate::backend::operation::TaskGuard;
let () = $crate::data::allow_mut_access::$key;
let functor = $f;
let $crate::data::CachedDataItemValueRefMut::$key {
value,
} = $task.get_mut_or_insert_with(&$crate::data::CachedDataItemKey::$key $input, move || $crate::data::CachedDataItemValue::$key { value: functor() }) else {
unreachable!()
};
value
}};
($task:ident, $key:ident, $f:expr) => {
$crate::backend::storage::get_mut_or_insert_with!($task, $key {}, $f)
};
}
/// Creates an iterator over all [`CachedDataItemKey::$key`][crate::data::CachedDataItemKey]s in
/// `$task` matching the given `$key_pattern`, optional `$value_pattern`, and optional `if $cond`.
///
......@@ -530,6 +557,7 @@ pub(crate) use count;
pub(crate) use get;
pub(crate) use get_many;
pub(crate) use get_mut;
pub(crate) use get_mut_or_insert_with;
pub(crate) use iter_many;
pub(crate) use remove;
pub(crate) use update;
......
......@@ -67,23 +67,78 @@ impl OutputValue {
}
#[derive(Debug)]
pub struct RootState {
pub ty: ActiveType,
pub struct ActivenessState {
/// When this counter is > 0, the task is active.
pub active_counter: i32,
/// The task is a root or once task and is active due to that.
pub root_ty: Option<RootType>,
/// The subgraph is active as long it's dirty. Once it become clean, it will unset this flag.
///
/// This happens primarily when a dirty subgraph wants to be scheduled. It will set this flag
/// to "cache" the activeness.
///
/// It also happens when a task is strongly consistently read. We need the `all_clean_event` in
/// that case and want to keep the task active to not stale the task.
pub active_until_clean: bool,
/// An event which is notifies when the subgraph is no longer dirty. It must be combined with
/// `active_until_clean` to avoid staling the task.
pub all_clean_event: Event,
}
impl RootState {
pub fn new(ty: ActiveType, id: TaskId) -> Self {
impl ActivenessState {
pub fn new(id: TaskId) -> Self {
Self {
ty,
all_clean_event: Event::new(move || format!("RootState::all_clean_event {:?}", id)),
active_counter: 0,
root_ty: None,
active_until_clean: false,
all_clean_event: Event::new(move || {
format!("ActivenessState::all_clean_event {:?}", id)
}),
}
}
pub fn new_root(root_ty: RootType, id: TaskId) -> Self {
let mut this = Self::new(id);
this.set_root(root_ty);
this
}
pub fn set_root(&mut self, root_ty: RootType) {
self.root_ty = Some(root_ty);
}
pub fn set_active_until_clean(&mut self) {
self.active_until_clean = true;
}
/// Increment the active counter and return true if the counter was 0 before.
pub fn increment_active_counter(&mut self) -> bool {
self.active_counter += 1;
self.active_counter == 1
}
/// Decrement the active counter and return true if the counter is 0 after.
pub fn decrement_active_counter(&mut self) -> bool {
self.active_counter -= 1;
self.active_counter == 0
}
pub fn unset_root_type(&mut self) {
self.root_ty = None;
}
pub fn unset_active_until_clean(&mut self) {
self.active_until_clean = false;
}
pub fn is_empty(&self) -> bool {
self.root_ty.is_none() && !self.active_until_clean && self.active_counter == 0
}
}
transient_traits!(RootState);
transient_traits!(ActivenessState);
impl Eq for RootState {}
impl Eq for ActivenessState {}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct DirtyState {
......@@ -239,13 +294,9 @@ impl DirtyContainerCount {
}
#[derive(Debug, Clone, Copy)]
pub enum ActiveType {
pub enum RootType {
RootTask,
OnceTask,
/// The aggregated task graph was scheduled because it has reached an AggregatedRoot while
/// propagating the dirty container or is read strongly consistent. This state is reset when
/// all this sub graph becomes clean again.
CachedActiveUntilClean,
}
#[derive(Debug)]
......@@ -390,8 +441,8 @@ pub enum CachedDataItem {
// Transient Root Type
#[serde(skip)]
AggregateRoot {
value: RootState,
Activeness {
value: ActivenessState,
},
// Transient In Progress state
......@@ -464,7 +515,7 @@ impl CachedDataItem {
!collectible.cell.task.is_transient()
}
CachedDataItem::AggregatedDirtyContainerCount { .. } => true,
CachedDataItem::AggregateRoot { .. } => false,
CachedDataItem::Activeness { .. } => false,
CachedDataItem::InProgress { .. } => false,
CachedDataItem::InProgressCell { .. } => false,
CachedDataItem::OutdatedCollectible { .. } => false,
......@@ -530,7 +581,7 @@ impl CachedDataItem {
| Self::InProgressCell { .. }
| Self::InProgress { .. }
| Self::Error { .. }
| Self::AggregateRoot { .. } => TaskDataCategory::All,
| Self::Activeness { .. } => TaskDataCategory::All,
}
}
}
......@@ -562,7 +613,7 @@ impl CachedDataItemKey {
!collectible.cell.task.is_transient()
}
CachedDataItemKey::AggregatedDirtyContainerCount { .. } => true,
CachedDataItemKey::AggregateRoot { .. } => false,
CachedDataItemKey::Activeness { .. } => false,
CachedDataItemKey::InProgress { .. } => false,
CachedDataItemKey::InProgressCell { .. } => false,
CachedDataItemKey::OutdatedCollectible { .. } => false,
......@@ -616,7 +667,7 @@ impl CachedDataItemType {
| Self::InProgressCell { .. }
| Self::InProgress { .. }
| Self::Error { .. }
| Self::AggregateRoot { .. } => TaskDataCategory::All,
| Self::Activeness { .. } => TaskDataCategory::All,
}
}
}
......@@ -627,7 +678,7 @@ impl CachedDataItemType {
#[allow(non_upper_case_globals, dead_code)]
pub mod allow_mut_access {
pub const InProgress: () = ();
pub const AggregateRoot: () = ();
pub const Activeness: () = ();
}
impl CachedDataItemValue {
......
use std::{
collections::{HashSet, VecDeque},
fmt::Debug,
hash::{BuildHasher, BuildHasherDefault, Hash},
};
......@@ -20,6 +21,12 @@ pub struct DequeSet<T, B: BuildHasher = BuildHasherDefault<FxHasher>> {
queue: VecDeque<T>,
}
impl<T: Debug, B: BuildHasher> Debug for DequeSet<T, B> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.queue.fmt(f)
}
}
impl<T, B: BuildHasher + Default> Default for DequeSet<T, B> {
fn default() -> Self {
Self {
......
......@@ -152,6 +152,19 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
.map(|#(#value_fields)*| #value_ref_mut_name::#variant_name { #(#value_fields)* })
}
},
get_mut_or_insert_with: quote! {
(#storage_name::#variant_name { storage }, #key_name::#variant_name {}) => {
#value_ref_mut_name::#variant_name {
#(#value_fields)*: storage
.get_or_insert_with(|| {
let #value_name::#variant_name { #(#value_fields)* } = insert_with() else {
unreachable!();
};
#(#value_fields)*
})
}
}
},
shrink_to_fit: quote! {
#storage_name::#variant_name { .. } => {
// nothing to do
......@@ -229,6 +242,20 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
.map(|#(#value_fields)*| #value_ref_mut_name::#variant_name { #(#value_fields)* })
}
},
get_mut_or_insert_with: quote! {
(#storage_name::#variant_name { storage }, #key_name::#variant_name { #(#key_fields)* }) => {
#value_ref_mut_name::#variant_name {
#(#value_fields)*: storage
.entry(*#(#key_fields)*)
.or_insert_with(|| {
let #value_name::#variant_name { #(#value_fields)* } = insert_with() else {
unreachable!();
};
#(#value_fields)*
})
}
}
},
shrink_to_fit: quote! {
#storage_name::#variant_name { storage } => {
storage.shrink_to_fit()
......@@ -307,6 +334,20 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
.map(|#(#value_fields)*| #value_ref_mut_name::#variant_name { #(#value_fields)* })
}
},
get_mut_or_insert_with: quote! {
(#storage_name::#variant_name { storage }, #key_name::#variant_name { #(#key_fields),* }) => {
#value_ref_mut_name::#variant_name {
#(#value_fields)*: storage
.entry((#(*#key_fields),*))
.or_insert_with(|| {
let #value_name::#variant_name { #(#value_fields)* } = insert_with() else {
unreachable!();
};
#(#value_fields)*
})
}
}
},
shrink_to_fit: quote! {
#storage_name::#variant_name { storage } => {
storage.shrink_to_fit()
......@@ -351,6 +392,10 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
.collect::<Vec<_>>();
let storage_get = storage.iter().map(|decl| &decl.get).collect::<Vec<_>>();
let storage_get_mut = storage.iter().map(|decl| &decl.get_mut).collect::<Vec<_>>();
let storage_get_mut_or_insert_with = storage
.iter()
.map(|decl| &decl.get_mut_or_insert_with)
.collect::<Vec<_>>();
let storage_shrink_to_fit = storage
.iter()
.map(|decl| &decl.shrink_to_fit)
......@@ -590,6 +635,15 @@ pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
}
}
pub fn get_mut_or_insert_with(&mut self, key: &#key_name, insert_with: impl FnOnce() -> #value_name) -> #value_ref_mut_name {
match (self, key) {
#(
#storage_get_mut_or_insert_with
)*
_ => unreachable!(),
}
}
pub fn shrink_to_fit(&mut self) {
match self {
#(
......@@ -786,6 +840,7 @@ struct StorageDecl {
contains_key: proc_macro2::TokenStream,
get: proc_macro2::TokenStream,
get_mut: proc_macro2::TokenStream,
get_mut_or_insert_with: proc_macro2::TokenStream,
shrink_to_fit: proc_macro2::TokenStream,
is_empty: proc_macro2::TokenStream,
len: proc_macro2::TokenStream,
......
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