diff --git a/crates/solverforge-scoring/src/stream/relational/operator/complement.rs b/crates/solverforge-scoring/src/stream/relational/operator/complement.rs index e518f866..11ebcd7c 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/complement.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/complement.rs @@ -1,3 +1,4 @@ +use super::links::Links; use super::{ComplementView, GroupedOperator, Operator, Pair, PairDelta, ProjectView}; use crate::stream::joiner::plan::{CompileCondition, ExecutablePlan, IndexedPlan}; use crate::stream::relational::hash::FastMap; @@ -48,8 +49,8 @@ pub struct ComplementNode< rows: DenseRowStore>, real_outputs: FastMap, default_outputs: HandleMap, - left_outputs: HandleMap>, - right_outputs: HandleMap>, + left_outputs: Links, + right_outputs: Links, /// Child notification scratch, reused across events (targets/results). child_l_removed: Vec, child_l_inserted: Vec, @@ -82,8 +83,8 @@ where rows: DenseRowStore::new(), real_outputs: FastMap::default(), default_outputs: HandleMap::new(), - left_outputs: HandleMap::new(), - right_outputs: HandleMap::new(), + left_outputs: Links::new(), + right_outputs: Links::new(), child_l_removed: Vec::new(), child_l_inserted: Vec::new(), child_r_removed: Vec::new(), @@ -150,11 +151,14 @@ where } = delta; for handle in left.iter().copied() { self.plan.remove_left(&mut self.indexes, handle); - for h in self.left_outputs.remove(handle).unwrap_or_default() { - if self.rows.get(h).is_some() { - self.remove_output(h); - removed.push(h); + if let Some(mut outputs) = self.left_outputs.take(handle) { + for h in outputs.drain(..) { + if self.rows.get(h).is_some() { + self.remove_output(h); + removed.push(h); + } } + self.left_outputs.retire(outputs); } } // Keys of the result rows this event removes, read back from the @@ -167,11 +171,14 @@ where .collect(); for handle in right.iter().copied() { self.plan.remove_right(&mut self.indexes, handle); - for h in self.right_outputs.remove(handle).unwrap_or_default() { - if self.rows.get(h).is_some() { - self.remove_output(h); - removed.push(h); + if let Some(mut outputs) = self.right_outputs.take(handle) { + for h in outputs.drain(..) { + if self.rows.get(h).is_some() { + self.remove_output(h); + removed.push(h); + } } + self.right_outputs.retire(outputs); } } for handle in left_inserted.iter().copied() { diff --git a/crates/solverforge-scoring/src/stream/relational/operator/complement/outputs.rs b/crates/solverforge-scoring/src/stream/relational/operator/complement/outputs.rs index 889853da..054e66f7 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/complement/outputs.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/complement/outputs.rs @@ -1,5 +1,5 @@ use super::*; -use crate::stream::relational::operator::links::remove_link; +use crate::stream::relational::operator::links::Links; impl, R: Operator, P, F, T> ComplementNode where @@ -13,7 +13,8 @@ where OutputValue::Real(id) => { self.real_outputs.remove(&id); if let Some(moved) = - remove_link(&mut self.left_outputs, id.left(), h, row.left_position) + self.left_outputs + .remove_link(id.left(), h, row.left_position) { self.rows .get_mut(moved) @@ -21,7 +22,8 @@ where .left_position = row.left_position; } if let Some(moved) = - remove_link(&mut self.right_outputs, id.right(), h, row.right_position) + self.right_outputs + .remove_link(id.right(), h, row.right_position) { self.rows .get_mut(moved) @@ -31,8 +33,7 @@ where } OutputValue::Default(input, _) => { self.default_outputs.remove(input); - if let Some(moved) = - remove_link(&mut self.left_outputs, input, h, row.left_position) + if let Some(moved) = self.left_outputs.remove_link(input, h, row.left_position) { self.rows .get_mut(moved) @@ -47,8 +48,8 @@ where pub(super) fn emit_real( rows: &mut DenseRowStore>, outputs: &mut FastMap, - left_outputs: &mut HandleMap>, - right_outputs: &mut HandleMap>, + left_outputs: &mut Links, + right_outputs: &mut Links, left: RowHandle, right: RowHandle, inserted: &mut Vec, @@ -57,8 +58,8 @@ where if outputs.contains_key(&id) { return None; } - let left_bucket = left_outputs.get_or_insert_with(left, Vec::new); - let right_bucket = right_outputs.get_or_insert_with(right, Vec::new); + let left_bucket = left_outputs.bucket(left); + let right_bucket = right_outputs.bucket(right); let h = rows.insert(Output { value: OutputValue::Real(id), left_position: left_bucket.len(), @@ -86,7 +87,7 @@ where .resolve(solution, input) .expect("live complement target"); let value = (self.default)(solution, &row); - let bucket = self.left_outputs.get_or_insert_with(input, Vec::new); + let bucket = self.left_outputs.bucket(input); let h = self.rows.insert(Output { value: OutputValue::Default(input, value), left_position: bucket.len(), diff --git a/crates/solverforge-scoring/src/stream/relational/operator/join.rs b/crates/solverforge-scoring/src/stream/relational/operator/join.rs index 0b083299..54e512cd 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/join.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/join.rs @@ -1,5 +1,5 @@ -use super::super::{DenseRowStore, HandleMap, JoinedIdentity, RowHandle}; -use super::{links::remove_link, GroupedOperator, Operator, Pair, PairDelta}; +use super::super::{DenseRowStore, JoinedIdentity, RowHandle}; +use super::{links::Links, GroupedOperator, Operator, Pair, PairDelta}; use super::{ExplainOperator, RowOrigin}; use crate::api::analysis::EntityRef; use crate::stream::joiner::plan::{CompileCondition, ExecutablePlan, IndexedPlan}; @@ -21,8 +21,8 @@ pub struct JoinNode { indexes: P::Indexes, rows: DenseRowStore, outputs: FastMap, - left_outputs: HandleMap>, - right_outputs: HandleMap>, + left_outputs: Links, + right_outputs: Links, /// Child notification scratch, reused across events (L/R, removed/inserted). child_l_removed: Vec, child_l_inserted: Vec, @@ -46,8 +46,8 @@ where indexes, rows: DenseRowStore::new(), outputs: FastMap::default(), - left_outputs: HandleMap::new(), - right_outputs: HandleMap::new(), + left_outputs: Links::new(), + right_outputs: Links::new(), child_l_removed: Vec::new(), child_l_inserted: Vec::new(), child_r_removed: Vec::new(), @@ -70,20 +70,26 @@ where } = delta; for handle in left_removed.iter().copied() { self.plan.remove_left(&mut self.indexes, handle); - for output in self.left_outputs.remove(handle).unwrap_or_default() { - if self.rows.get(output).is_some() { - self.remove_output(output); - removed.push(output); + if let Some(mut outputs) = self.left_outputs.take(handle) { + for output in outputs.drain(..) { + if self.rows.get(output).is_some() { + self.remove_output(output); + removed.push(output); + } } + self.left_outputs.retire(outputs); } } for handle in right_removed.iter().copied() { self.plan.remove_right(&mut self.indexes, handle); - for output in self.right_outputs.remove(handle).unwrap_or_default() { - if self.rows.get(output).is_some() { - self.remove_output(output); - removed.push(output); + if let Some(mut outputs) = self.right_outputs.take(handle) { + for output in outputs.drain(..) { + if self.rows.get(output).is_some() { + self.remove_output(output); + removed.push(output); + } } + self.right_outputs.retire(outputs); } } for handle in left_inserted.iter().copied() { @@ -110,23 +116,19 @@ where fn remove_output(&mut self, handle: RowHandle) { if let Some(row) = self.rows.retract(handle) { self.outputs.remove(&row.identity); - if let Some(moved) = remove_link( - &mut self.left_outputs, - row.identity.left(), - handle, - row.left_position, - ) { + if let Some(moved) = + self.left_outputs + .remove_link(row.identity.left(), handle, row.left_position) + { self.rows .get_mut(moved) .expect("moved left output") .left_position = row.left_position; } - if let Some(moved) = remove_link( - &mut self.right_outputs, - row.identity.right(), - handle, - row.right_position, - ) { + if let Some(moved) = + self.right_outputs + .remove_link(row.identity.right(), handle, row.right_position) + { self.rows .get_mut(moved) .expect("moved right output") @@ -143,8 +145,8 @@ where fn emit_output( rows: &mut DenseRowStore, outputs: &mut FastMap, - left_outputs: &mut HandleMap>, - right_outputs: &mut HandleMap>, + left_outputs: &mut Links, + right_outputs: &mut Links, left: RowHandle, right: RowHandle, ) -> Option { @@ -152,8 +154,8 @@ where if outputs.contains_key(&identity) { return None; } - let left_bucket = left_outputs.get_or_insert_with(left, Vec::new); - let right_bucket = right_outputs.get_or_insert_with(right, Vec::new); + let left_bucket = left_outputs.bucket(left); + let right_bucket = right_outputs.bucket(right); let handle = rows.insert(JoinedRow { identity, left_position: left_bucket.len(), diff --git a/crates/solverforge-scoring/src/stream/relational/operator/links.rs b/crates/solverforge-scoring/src/stream/relational/operator/links.rs index fbbd1b97..e98714f7 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/links.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/links.rs @@ -1,18 +1,76 @@ use crate::stream::relational::{HandleMap, RowHandle}; -#[inline] -pub(super) fn remove_link( - links: &mut HandleMap>, - input: RowHandle, - output: RowHandle, - position: usize, -) -> Option { - let bucket = links.get_mut(input)?; - debug_assert_eq!(bucket[position], output); - bucket.swap_remove(position); - let moved = bucket.get(position).copied(); - if bucket.is_empty() { - links.remove(input); - } - moved +/// Output links of each input row, with a pool of emptied buckets. +/// +/// A row that leaves and re-enters a node on every move would otherwise drop +/// its bucket on retraction and allocate a new one on insertion; the pool +/// keeps those buckets, so steady-state notification allocates nothing. +pub(super) struct Links { + buckets: HandleMap>, + retired: Vec>, +} + +impl Links { + pub(super) fn new() -> Self { + Self { + buckets: HandleMap::new(), + retired: Vec::new(), + } + } + + pub(super) fn clear(&mut self) { + self.buckets.clear(); + } + + pub(super) fn get(&self, input: RowHandle) -> Option<&Vec> { + self.buckets.get(input) + } + + pub(super) fn get_mut(&mut self, input: RowHandle) -> Option<&mut Vec> { + self.buckets.get_mut(input) + } + + /// The bucket of `input`, taken from the pool when it has none. + #[inline] + pub(super) fn bucket(&mut self, input: RowHandle) -> &mut Vec { + let Self { buckets, retired } = self; + buckets.get_or_insert_with(input, || retired.pop().unwrap_or_default()) + } + + /// Detaches the bucket of `input`; hand it back with [`Links::retire`]. + #[inline] + pub(super) fn take(&mut self, input: RowHandle) -> Option> { + self.buckets.remove(input) + } + + /// Returns an emptied bucket to the pool. + #[inline] + pub(super) fn retire(&mut self, mut bucket: Vec) { + bucket.clear(); + self.retired.push(bucket); + } +} + +impl Links { + /// Removes `output` from the bucket of `input` at `position` by swap + /// removal and returns the output moved into that position. An emptied + /// bucket goes back to the pool. + #[inline] + pub(super) fn remove_link( + &mut self, + input: RowHandle, + output: RowHandle, + position: usize, + ) -> Option { + let bucket = self.buckets.get_mut(input)?; + debug_assert_eq!(bucket[position], output); + bucket.swap_remove(position); + let moved = bucket.get(position).copied(); + if bucket.is_empty() { + if let Some(bucket) = self.buckets.remove(input) { + self.retired.push(bucket); + } + } + moved + } } diff --git a/crates/solverforge-scoring/src/stream/relational/operator/project.rs b/crates/solverforge-scoring/src/stream/relational/operator/project.rs index e9fd4e7c..2f04d31a 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/project.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/project.rs @@ -1,7 +1,8 @@ +use super::links::Links; use super::Operator; use super::{ExplainOperator, RowOrigin}; use crate::api::analysis::EntityRef; -use crate::stream::relational::{DenseRowStore, HandleMap, RowHandle}; +use crate::stream::relational::{DenseRowStore, RowHandle}; /// Borrowed owned output with its entire upstream row and emission position. pub struct ProjectView<'a, V, T> { @@ -29,7 +30,7 @@ pub struct ProjectNode { input: O, mapper: F, rows: DenseRowStore>, - outputs: HandleMap>, + outputs: Links, /// Child notification scratch, reused across events. child_removed: Vec, child_inserted: Vec, @@ -47,13 +48,13 @@ impl ProjectNode { input, mapper, rows: DenseRowStore::new(), - outputs: HandleMap::new(), + outputs: Links::new(), child_removed: Vec::new(), child_inserted: Vec::new(), } } fn add(&mut self, input: RowHandle, values: Vec, inserted: &mut Vec) { - let outputs = self.outputs.get_or_insert_with(input, Vec::new); + let outputs = self.outputs.bucket(input); for (emission, value) in values.into_iter().enumerate() { let h = self.rows.insert(Output { input, @@ -78,9 +79,12 @@ impl ProjectNode { F: for<'a> Fn(&S, &O::View<'a>) -> Vec + 'static, { for input in input_removed.iter().copied() { - for h in self.outputs.remove(input).unwrap_or_default() { - self.rows.retract(h); - removed.push(h); + if let Some(mut outputs) = self.outputs.take(input) { + for h in outputs.drain(..) { + self.rows.retract(h); + removed.push(h); + } + self.outputs.retire(outputs); } } for input in input_inserted.iter().copied() { diff --git a/crates/solverforge-scoring/src/stream/relational/operator/self_join.rs b/crates/solverforge-scoring/src/stream/relational/operator/self_join.rs index 8b9bc93a..b9211bf6 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/self_join.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/self_join.rs @@ -9,6 +9,7 @@ //! input handle tuples; identities resolve on demand, and provenance falls out of //! each member's own provenance. +use super::links::Links; use super::Operator; use super::{ExplainOperator, RowOrigin}; use crate::api::analysis::EntityRef; @@ -82,7 +83,7 @@ pub struct SelfJoinNode { handle_index: HandleMap, rows: DenseRowStore<[RowHandle; N]>, combos: FastMap<[RowHandle; N], RowHandle>, - of_input: HandleMap>, + of_input: Links<[RowHandle; N]>, /// Child notification scratch, reused across events. child_removed: Vec, child_inserted: Vec, @@ -99,7 +100,7 @@ impl SelfJoinNode { handle_index: HandleMap::new(), rows: DenseRowStore::new(), combos: FastMap::default(), - of_input: HandleMap::new(), + of_input: Links::new(), child_removed: Vec::new(), child_inserted: Vec::new(), marker: PhantomData, @@ -260,7 +261,8 @@ where /// the retracted handles. fn retract_row(&mut self, handle: RowHandle) -> Vec { let mut removed = Vec::new(); - for tuple in self.of_input.remove(handle).unwrap_or_default() { + let mut tuples = self.of_input.take(handle).unwrap_or_default(); + for tuple in tuples.drain(..) { if let Some(output) = self.combos.remove(&tuple) { self.rows.retract(output); for member in tuple { @@ -273,6 +275,7 @@ where removed.push(output); } } + self.of_input.retire(tuples); if let Some(index) = self.handle_index.remove(handle) { if let Some(key) = self .by_key @@ -319,9 +322,7 @@ where let output = self.rows.insert(tuple); self.combos.insert(tuple, output); for member in tuple { - self.of_input - .get_or_insert_with(member, Vec::new) - .push(tuple); + self.of_input.bucket(member).push(tuple); } inserted.push(output); } diff --git a/crates/solverforge-solver/tests/join_link_reuse.rs b/crates/solverforge-solver/tests/join_link_reuse.rs new file mode 100644 index 00000000..0a29f538 --- /dev/null +++ b/crates/solverforge-solver/tests/join_link_reuse.rs @@ -0,0 +1,101 @@ +//! A join whose rows leave and re-enter on every move reuses the output-link +//! buckets it emptied, so steady-state incremental scoring allocates nothing. +//! +//! This is its own test binary because it replaces the global allocator. It +//! counts only the test thread's allocations, so the harness's other threads +//! cannot touch the count. + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; + +use solverforge_core::score::SoftScore; +use solverforge_scoring::api::constraint_set::IncrementalConstraint; +use solverforge_scoring::stream::joiner::equal_bi; +use solverforge_scoring::stream::{source, ChangeSource, ConstraintFactory}; + +struct CountingAllocator; + +thread_local! { + static ALLOCATIONS: Cell = const { Cell::new(0) }; +} + +fn count_allocation() { + // `try_with` skips allocations made while the thread-local is torn down. + let _ = ALLOCATIONS.try_with(|count| count.set(count.get() + 1)); +} + +// SAFETY: every call forwards to the system allocator unchanged. +unsafe impl GlobalAlloc for CountingAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count_allocation(); + unsafe { System.alloc(layout) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + count_allocation(); + unsafe { System.realloc(ptr, layout, new_size) } + } +} + +#[global_allocator] +static ALLOCATOR: CountingAllocator = CountingAllocator; + +#[derive(Debug)] +struct Item { + key: u32, +} + +struct Model { + left: Vec, + right: Vec, +} + +fn left(model: &Model) -> &[Item] { + &model.left +} + +fn right(model: &Model) -> &[Item] { + &model.right +} + +#[test] +fn rejoining_rows_reuse_their_link_buckets() { + let mut constraint = ConstraintFactory::::new() + .for_each(source( + left as fn(&Model) -> &[Item], + ChangeSource::Descriptor(0), + )) + .join(( + source(right as fn(&Model) -> &[Item], ChangeSource::Descriptor(1)), + equal_bi(|l: &Item| l.key, |r: &Item| r.key), + )) + .penalize(SoftScore::of(1)) + .named("matching keys"); + let mut model = Model { + left: vec![Item { key: 1 }, Item { key: 2 }], + right: vec![Item { key: 1 }, Item { key: 1 }, Item { key: 2 }], + }; + let mut score = constraint.initialize(&model); + let mut cycle = |model: &mut Model, score: &mut SoftScore| { + *score = *score + constraint.on_retract(model, 0, 0); + model.left[0].key = if model.left[0].key == 1 { 2 } else { 1 }; + *score = *score + constraint.on_insert(model, 0, 0); + }; + // Warm-up: the first moves size every bucket and scratch buffer. + for _ in 0..4 { + cycle(&mut model, &mut score); + } + + let before = ALLOCATIONS.with(Cell::get); + for _ in 0..64 { + cycle(&mut model, &mut score); + } + let allocated = ALLOCATIONS.with(Cell::get) - before; + + assert_eq!(allocated, 0, "steady-state moves allocate nothing"); + assert_eq!(score, SoftScore::of(-3), "left 0 is back on key 1"); +}