diff --git a/Cargo.lock b/Cargo.lock index 94b4f7ac7..74c354c9a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -512,6 +512,7 @@ dependencies = [ name = "solverforge-scoring" version = "0.31.5" dependencies = [ + "smallvec", "solverforge-core", ] diff --git a/crates/solverforge-scoring/Cargo.toml b/crates/solverforge-scoring/Cargo.toml index 7b3eb8cc0..9085631b1 100644 --- a/crates/solverforge-scoring/Cargo.toml +++ b/crates/solverforge-scoring/Cargo.toml @@ -12,6 +12,7 @@ description = "Incremental constraint scoring for SolverForge" [dependencies] solverforge-core = { version = "=0.31.5", path = "../solverforge-core" } +smallvec.workspace = true [lints.rust] unreachable_pub = "warn" diff --git a/crates/solverforge-scoring/WIREFRAME.md b/crates/solverforge-scoring/WIREFRAME.md index 5027b96a5..75d8a0d78 100644 --- a/crates/solverforge-scoring/WIREFRAME.md +++ b/crates/solverforge-scoring/WIREFRAME.md @@ -64,7 +64,8 @@ migration of the fluent stream families: - `ExistenceNode::new(left, right, left_key, right_keys, exists)` answers a pure-key semi/anti join from per-key occurrence counts (dense arrays for `usize` planning ids via `KeyState` in - `stream/relational/count_state.rs`, hash tables otherwise). The left key + `stream/relational/count_state.rs`, otherwise one key table holding each + key once, addressed by slot). The left key adapter implements `ViewKey>`; the right adapter implements `RightKeySet>` (`UnitKeys` for one key per right row, `ParentChildKeys` to expand flattened children in place, `GroupRightKeys` @@ -87,10 +88,14 @@ migration of the fluent stream families: result bindings; unmatched targets own their default payloads. `ComplementView` is `Real(Pair)` or `Default(ProjectView<'a, L, T>)`. Duplicate target rows preserve bag multiplicity, and grouped results have one accumulator owner. -- `JoinNode::new(left, right, condition)` compiles a condition and - produces `Pair, R::View<'a>>`; either input can itself be a join. - `Pair` has public `left` and `right` fields. Depth is recursive rather - than fixed to a named arity. +- `JoinNode::new(left, right, condition)` compiles a + condition and produces `Pair, R::View<'a>>`; either input can + itself be a join. `JoinNode::filtered(left, right, condition, filter)` adds a + row filter `F: FilterPredicate>` that runs when a pair is found, + before it is retained, so a rejected pair is never stored. A pair is emitted + once per change without an identity table: the right probe skips left rows + inserted by the same change. `Pair` has public `left` and `right` + fields. Depth is recursive rather than fixed to a named arity. - `stream::chain::{Chain, ChainBuilder}` is the arity-free fluent continuation: `stream::cross::Penta::join` returns one, and `Chain::join` nests further `JoinNode`s with no ceiling; `Chain::filter` wraps the tree in an identity-preserving @@ -140,11 +145,16 @@ migration of the fluent stream families: on: `ViewKey` reads a key out of a view; `EntityKey` lifts an entity key onto a leaf view, `ChildKey` onto a flattened child view; `PairKey` pairs two keys over one view; `FlattenedPairKey` pairs the owning - entity's key with the flattened child's key; `GroupKey` reads a grouped row's - own key; and `ViewEqualPlan` is the typed hash-equality plan - over two named view keys. + entity's key with the flattened child's key; and `ViewEqualPlan` is the + typed hash-equality plan over two named view keys. `GroupEqualPlan` matches a grouped row's own key to `KeyFn` of the other input + (`GroupLeft` or `GroupRight` names the grouped side); it indexes groups by + key hash, so a group's key is stored once, in its group. - `stream::relational::operator::FilterPredicate` is the named predicate - `FilterNode` evaluates; `FlattenSource` names a flatten extractor over + `FilterNode`, `JoinNode` and `SelfJoinNode` evaluate. Its + `const ACCEPTS_ALL: bool = false` lets an operator skip resolving rows only + to test them; `AcceptAll` is the predicate that sets it and the default row + filter of both joins; `FlattenSource` names a flatten extractor over an operator view, and `ParentFlatten` adapts an entity-level child extractor to it. - `stream::cross::QuadBuilder` and `stream::cross::PentaBuilder` are the @@ -154,11 +164,13 @@ migration of the fluent stream families: New file map: `stream/relational/operator.rs`, `stream/relational/operator/{analysis,collection,complement,complement_view, existence,filter,flatten,group,group_view,join,joiner_existence,merge,project, -self_join}.rs`, -`stream/relational/{count_state,keyed_plan,view_plan}.rs`, +self_join}.rs`, `stream/relational/operator/join/incremental.rs` (a join's +retained-pair maintenance), +`stream/relational/{count_state,key_table,keyed_plan,view_plan}.rs`, +`stream/relational/view_plan/group.rs`, `stream/joiner/plan.rs`, `stream/joiner/plan/{executable,hash_scan,conjunction, composite,mixed_equality,ordered_interval}.rs`, `stream/joiner/row_key.rs`, -`stream/relational/index/{hash,ordered,interval}.rs`, +`stream/relational/index/{hash,hashed,ordered,interval}.rs`, `stream/relational/hash.rs`, and `constraint/relational/operator_terminal.rs`. Generational direct side-tables are internal in `stream/relational/handle_map.rs`; `stream/relational/hash.rs` @@ -281,7 +293,7 @@ src/ │ ├── cross.rs — Public `stream::cross` re-exports of the cross-join streams and builders │ ├── projected.rs — Public `stream::projected` re-exports of the projected streams and builders │ ├── cross_penta_stream.rs — stream::cross::Penta and its Penta::join → Chain -│ ├── cross_penta_stream/scored.rs — PentaScored operator (tree plus authored filter) +│ ├── cross_penta_stream/scored.rs — PentaRowFilter and the filtered penta tree │ ├── grouped_stream.rs — Re-exports │ ├── grouped_stream/base.rs — GroupedConstraintStream │ ├── grouped_stream/weighting.rs — GroupedConstraintBuilder @@ -290,17 +302,18 @@ src/ │ ├── complemented_stream.rs — ComplementedConstraintStream, ComplementedConstraintBuilder │ ├── cross_bi_stream.rs — Re-exports │ ├── cross_bi_stream/base.rs — stream::cross::Bi -│ ├── cross_bi_stream/scored.rs — BiUnaryPlan, BiPredicatePlan, BiScored (first-join execution) +│ ├── cross_bi_stream/scored.rs — BiUnaryPlan, BiPredicatePlan, BiRowFilter (first-join execution) │ ├── cross_bi_stream/view_comparison.rs — ViewComparisonPlan, ViewOverlapPlan (entity conditions over leaf views) │ ├── cross_bi_stream/grouped.rs — stream::cross::Grouped and builder │ ├── cross_bi_stream/complemented_grouped.rs — stream::cross::ComplementedGrouped and builder │ ├── cross_bi_stream/weighting.rs — stream::cross::Builder │ ├── cross_tri_stream.rs — Re-exports │ ├── cross_tri_stream/base.rs — stream::cross::Tri and builder -│ ├── cross_tri_stream/base/scored.rs — TriScored operator (tree plus authored filter) +│ ├── cross_tri_stream/base/scored.rs — TriRowFilter and the filtered tri tree │ ├── flattened_bi_stream.rs — Re-exports │ ├── flattened_bi_stream/base.rs — FlattenedBiConstraintStream │ ├── flattened_bi_stream/builder.rs — FlattenedBiConstraintBuilder +│ ├── flattened_bi_stream/scored.rs — FlattenedBiRowFilter, the join's row filter │ ├── flattened_bi_stream/weighting.rs — Weighting helpers for flattened streams │ ├── existence_stream.rs — ExistsConstraintStream, ExistsConstraintBuilder, ExistenceMode │ ├── existence_target.rs — ExistenceTarget trait for direct and flattened existence targets @@ -338,7 +351,7 @@ src/ │ │ ├── mod.rs — Re-exports filter types │ │ ├── traits.rs — UniFilter, BiFilter, TriFilter, QuadFilter, PentaFilter traits │ │ ├── wrappers.rs — TrueFilter, FnUniFilter, FnBiFilter, FnTriFilter, FnQuadFilter, FnPentaFilter -│ │ ├── adapters.rs — UniBiFilter, UniLeftBiFilter, UniPairFilter, and hidden PairFilter adapters +│ │ ├── adapters.rs — UniBiFilter, UniLeftBiFilter, UniPairFilter, SelfJoinRowFilter, and hidden PairFilter adapters │ │ ├── composition.rs — AndUniFilter, AndBiFilter, AndTriFilter, AndQuadFilter, AndPentaFilter │ │ └── tests/ │ │ ├── mod.rs — Test module declarations @@ -565,8 +578,8 @@ All `Send + Sync`: `BiFilter`, `TriFilter`, `QuadFilter` and `PentaFilter` also carry `const ACCEPTS_ALL: bool = false`. `TrueFilter` sets it, the `And*` filters set it when both sides do, and the arity-lifting adapters forward it. The -penta boundary (`PentaScored`) passes rows straight through when it holds, so -an unfiltered chain pays no accepted-row bookkeeping. +row filters built from them forward it to `FilterPredicate::ACCEPTS_ALL`, so an +unfiltered self-join never resolves a combination just to test it. Joined filter indexes are semantic source indexes, not builder-local placeholders. Same-source joins pass canonical entity indexes; cross-bi passes @@ -715,7 +728,8 @@ collection (`stream::projected::ComplementedGroupedBuilder::named()`, including complement targets keep default rows until matched and each terminal scores independently. -Flattened bi streams finalize into `OperatorTerminal` over `FlattenedBiScored`; +Flattened bi streams finalize into `OperatorTerminal` over a `JoinNode` whose +row filter is the authored bi filter; filters receive the A source index and the owning B source index for each flattened C row. Existence streams finalize into `OperatorTerminal` over `ExistenceNode`, the pure-key, count-backed semi/anti join; conditions with a @@ -884,7 +898,7 @@ ConstraintFactory::::new() - Operations: `filter()`, `join()` → `TriConstraintStream`, `penalize(weight_or_fn)`, `reward(weight_or_fn)` - Low-level constructors: `new_self_join()`, `new_self_join_with_filter()` -**`BiConstraintBuilder`** — `named()` → `OperatorTerminal` over a `SelfJoinNode` + `FilterNode` tree +**`BiConstraintBuilder`** — `named()` → `OperatorTerminal` over a `SelfJoinNode` whose row filter is the authored filter **`TriConstraintStream/Builder`** — Same pattern, tri-arity. `join()` → `QuadConstraintStream`; low-level constructors are `new_self_join()` and @@ -923,7 +937,7 @@ further joins); low-level constructors are `new_self_join()` and **`stream::projected::ComplementedGrouped/Builder`** — Projected grouped complement stream. `penalize(weight_or_fn)`, `reward(weight_or_fn)`, `named()` → `SharedOperatorTerminal` over `ComplementNode(CollectionNode, GroupNode)`. Complement defaults are produced from the complement entity and weighted by key plus collector result. -**`FlattenedBiConstraintStream/Builder`** — Flattened bi stream. `filter()`, `penalize(weight_or_fn)`, `reward(weight_or_fn)`, `named()` → `OperatorTerminal` over `FlattenedBiScored`. Low-level filters receive the A source index and the B owner index for the flattened C row. +**`FlattenedBiConstraintStream/Builder`** — Flattened bi stream. `filter()`, `penalize(weight_or_fn)`, `reward(weight_or_fn)`, `named()` → `OperatorTerminal` over a filtered `JoinNode`. Low-level filters receive the A source index and the B owner index for the flattened C row. **`ExistsConstraintStream/ExistsConstraintBuilder`** — Existence stream over source-aware direct or flattened collection targets. `penalize(weight_or_fn)`, `reward(weight_or_fn)`, `named()` → `OperatorTerminal` over `ExistenceNode`. There is no separate public indexed existence stream. @@ -1015,7 +1029,9 @@ further joins); low-level constructors are `new_self_join()` and **`LoadBalanceCollector`** / **`LoadBalanceAccumulator`** / **`LoadBalance`** — Load balance with unfairness metric. - Factory: `load_balance(key_fn, metric_fn)` -- `LoadBalance` has `loads()` and `unfairness()` methods. +- `LoadBalance` has `loads()` (each item with its total load), `load(&key)` + and `unfairness()` methods. The accumulator stores each item's key once; its + retraction token is the item's slot and metric. **`RunsCollector`** / **`RunsAccumulator`** / **`Run`** / **`Runs`** — Consecutive unique `i64` point runs with duplicate item accounting. - Factory: `consecutive_runs(index_fn)` @@ -1061,13 +1077,16 @@ The `ScoreDirector` delegates to `ConstraintSet::on_retract_all()` / `on_insert_ ### Self-Join Operator -Same-collection n-ary streams build a `SelfJoinNode` over +Same-collection n-ary streams build a `SelfJoinNode` over their collection source. It buckets input rows by key, emits every increasing handle tuple of arity `N` per bucket (unique ordered combinations, so a triple -is `i < j < k` for one key), and maintains exact insert/retract deltas over a -retained combo set. The view is `[Leaf<'a, A>; N]` in canonical index order. -The authored filter runs in a `FilterNode` on top, and the terminal is the -shared `OperatorTerminal`. No per-arity incremental engine remains. +is `i < j < k` for one key), and maintains exact insert/retract deltas: each +input row keeps its key and bucket position and each combination its link +positions, so retraction touches only that row's bucket and combinations. +The view is `[Leaf<'a, A>; N]` in canonical index order. +`SelfJoinNode::filtered(input, key, filter)` applies the authored filter +(`SelfJoinRowFilter`) before a combination is retained, and the terminal is +the shared `OperatorTerminal`. No per-arity incremental engine remains. ### Stream Arity Macros diff --git a/crates/solverforge-scoring/public-api.txt b/crates/solverforge-scoring/public-api.txt index e2500a6d9..752b46329 100644 --- a/crates/solverforge-scoring/public-api.txt +++ b/crates/solverforge-scoring/public-api.txt @@ -102,17 +102,17 @@ struct stream::BalanceConstraintStream: pub struct BalanceConstraintStream BalanceConstraintBuilder stream::BalanceConstraintStream: pub fn reward( self, base_score: Sc, ) -> BalanceConstraintBuilder struct stream::BiConstraintBuilder: pub struct BiConstraintBuilder where Sc: Score,{ /* private fields */ } - stream::BiConstraintBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, K, KE, 2>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 2]) -> bool + Send + Sync>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 2]) -> Sc + Send + Sync, Sc> + stream::BiConstraintBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, K, KE, 2, SelfJoinRowFilter>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 2]) -> Sc + Send + Sync, Sc> struct stream::BiConstraintStream: pub struct BiConstraintStream where Sc: Score,{ /* private fields */ } stream::BiConstraintStream: pub fn new_self_join(extractor: E, key_extractor: KE) -> Self stream::BiConstraintStream: pub fn new_self_join_with_filter( extractor: E, key_extractor: KE, filter: F, ) -> Self stream::BiConstraintStream: pub fn filter

( self, predicate: P, ) -> BiConstraintStream bool + Send + Sync>>, Sc> where P: Fn(&A, &A) -> bool + Send + Sync + 'static, - stream::BiConstraintStream: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, K, KE, 2>, impl Fn(&S, &[Leaf<'_, A>; 2]) -> bool + Send + Sync>, impl Fn(&[Leaf<'_, A>; 2]) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where E: 'static, KE: 'static, F: 'static, K: 'static, GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &A) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i A), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, for<'i> TupleCollector: Collector<[Leaf<'i, A>; 2], Value = V, Result = R, Accumulator = Acc>, + stream::BiConstraintStream: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, K, KE, 2, SelfJoinRowFilter>, impl Fn(&[Leaf<'_, A>; 2]) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where E: 'static, KE: 'static, F: 'static, K: 'static, GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &A) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i A), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, for<'i> TupleCollector: Collector<[Leaf<'i, A>; 2], Value = V, Result = R, Accumulator = Acc>, stream::BiConstraintStream: pub fn penalize( self, weight: W, ) -> BiConstraintBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w A), Sc> + Send + Sync, stream::BiConstraintStream: pub fn reward( self, weight: W, ) -> BiConstraintBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w A), Sc> + Send + Sync, stream::BiConstraintStream: pub fn join( self, joiner: J, ) -> TriConstraintStream, Sc> where J: Joiner + 'static, F: 'static, struct stream::ComplementedConstraintBuilder: pub struct ComplementedConstraintBuilder where Sc: Score,{ /* private fields */ } - stream::ComplementedConstraintBuilder: pub fn named( self, name: &str, ) -> SharedOperatorTerminal, GroupNode, LeafFilter>, impl for<'l> Fn(&Leaf<'l, A>) -> Option + Send + Sync, LeafCollector, Option, Acc, V, R>, ViewEqualPlan, OptionalEntityKey, GroupKey>, impl for<'l> Fn(&S, &Leaf<'l, B>) -> R + Send + Sync, R>, OptionalComplementAdapter, OperatorScorer, Sc>, Sc> + stream::ComplementedConstraintBuilder: pub fn named( self, name: &str, ) -> SharedOperatorTerminal, GroupNode, LeafFilter>, impl for<'l> Fn(&Leaf<'l, A>) -> Option + Send + Sync, LeafCollector, Option, Acc, V, R>, GroupEqualPlan, OptionalEntityKey, GroupRight>, impl for<'l> Fn(&S, &Leaf<'l, B>) -> R + Send + Sync, R>, OptionalComplementAdapter, OperatorScorer, Sc>, Sc> struct stream::ComplementedConstraintStream: pub struct ComplementedConstraintStream where Sc: Score,{ /* private fields */ } stream::ComplementedConstraintStream: pub fn penalize( self, weight: W, ) -> ComplementedConstraintBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w K, &'w R), Sc> + Send + Sync, stream::ComplementedConstraintStream: pub fn reward( self, weight: W, ) -> ComplementedConstraintBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w K, &'w R), Sc> + Send + Sync, @@ -126,7 +126,7 @@ struct stream::ExistsConstraintStream: pub struct ExistsConstraintStream( self, weight: W, ) -> ExistsConstraintBuilder Fn(&S, &Leaf<'a, A>) -> Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A,), Sc> + Send + Sync, struct stream::FixedWeight: pub struct FixedWeight { /* private fields */ } struct stream::FlattenedBiConstraintBuilder: pub struct FlattenedBiConstraintBuilder where Sc: Score,{ /* private fields */ } - stream::FlattenedBiConstraintBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, FlattenNode, ParentFlatten>, ViewEqualPlan<(K, CK), PairKey, EntityKey>, FlattenedPairKey>>, F>, impl for<'a> Fn(&S, &Pair, FlattenView<'a, Leaf<'a, B>, C>>) -> Sc + Send + Sync, Sc> + stream::FlattenedBiConstraintBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, FlattenNode, ParentFlatten>, ViewEqualPlan<(K, CK), PairKey, EntityKey>, FlattenedPairKey>, FlattenedBiRowFilter>, impl for<'a> Fn(&S, &Pair, FlattenView<'a, Leaf<'a, B>, C>>) -> Sc + Send + Sync, Sc> struct stream::FlattenedBiConstraintStream: pub struct FlattenedBiConstraintStream where Sc: Score,{ /* private fields */ } stream::FlattenedBiConstraintStream: pub fn new( extractor_a: EA, extractor_b: EB, key_a: KA, key_b: KB, flatten: Flatten, c_key_fn: CKeyFn, a_lookup_fn: ALookup, ) -> Self stream::FlattenedBiConstraintStream: pub fn filter

( self, predicate: P, ) -> FlattenedBiConstraintStream bool + Send + Sync>>, Sc> where P: Fn(&A, &C) -> bool + Send + Sync, @@ -148,31 +148,31 @@ struct stream::JoinedGroupedStream: pub struct JoinedGroupedStream( self, weight: W, ) -> JoinedGroupedBuilder Sc + Send + Sync, Sc> where W: for<'a> ConstraintWeight<(&'a K, &'a R), Sc> + Send + Sync, stream::JoinedGroupedStream: pub fn reward( self, weight: W, ) -> JoinedGroupedBuilder Sc + Send + Sync, Sc> where W: for<'a> ConstraintWeight<(&'a K, &'a R), Sc> + Send + Sync, struct stream::PentaConstraintBuilder: pub struct PentaConstraintBuilder where Sc: Score,{ /* private fields */ } - stream::PentaConstraintBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, K, KE, 5>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 5]) -> bool + Send + Sync>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 5]) -> Sc + Send + Sync, Sc> + stream::PentaConstraintBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, K, KE, 5, SelfJoinRowFilter>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 5]) -> Sc + Send + Sync, Sc> struct stream::PentaConstraintStream: pub struct PentaConstraintStream where Sc: Score,{ /* private fields */ } stream::PentaConstraintStream: pub fn new_self_join(extractor: E, key_extractor: KE) -> Self stream::PentaConstraintStream: pub fn new_self_join_with_filter( extractor: E, key_extractor: KE, filter: F, ) -> Self stream::PentaConstraintStream: pub fn filter

( self, predicate: P, ) -> PentaConstraintStream bool + Send + Sync>>, Sc> where P: Fn(&A, &A, &A, &A, &A) -> bool + Send + Sync + 'static, - stream::PentaConstraintStream: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, K, KE, 5>, impl Fn(&S, &[Leaf<'_, A>; 5]) -> bool + Send + Sync>, impl Fn(&[Leaf<'_, A>; 5]) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where E: 'static, KE: 'static, F: 'static, K: 'static, GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &A, &A, &A, &A) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i A, &'i A, &'i A, &'i A), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, for<'i> TupleCollector: Collector<[Leaf<'i, A>; 5], Value = V, Result = R, Accumulator = Acc>, + stream::PentaConstraintStream: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, K, KE, 5, SelfJoinRowFilter>, impl Fn(&[Leaf<'_, A>; 5]) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where E: 'static, KE: 'static, F: 'static, K: 'static, GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &A, &A, &A, &A) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i A, &'i A, &'i A, &'i A), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, for<'i> TupleCollector: Collector<[Leaf<'i, A>; 5], Value = V, Result = R, Accumulator = Acc>, stream::PentaConstraintStream: pub fn penalize( self, weight: W, ) -> PentaConstraintBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w A, &'w A, &'w A, &'w A), Sc> + Send + Sync, stream::PentaConstraintStream: pub fn reward( self, weight: W, ) -> PentaConstraintBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w A, &'w A, &'w A, &'w A), Sc> + Send + Sync, struct stream::QuadConstraintBuilder: pub struct QuadConstraintBuilder where Sc: Score,{ /* private fields */ } - stream::QuadConstraintBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, K, KE, 4>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 4]) -> bool + Send + Sync>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 4]) -> Sc + Send + Sync, Sc> + stream::QuadConstraintBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, K, KE, 4, SelfJoinRowFilter>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 4]) -> Sc + Send + Sync, Sc> struct stream::QuadConstraintStream: pub struct QuadConstraintStream where Sc: Score,{ /* private fields */ } stream::QuadConstraintStream: pub fn new_self_join(extractor: E, key_extractor: KE) -> Self stream::QuadConstraintStream: pub fn new_self_join_with_filter( extractor: E, key_extractor: KE, filter: F, ) -> Self stream::QuadConstraintStream: pub fn filter

( self, predicate: P, ) -> QuadConstraintStream bool + Send + Sync>>, Sc> where P: Fn(&A, &A, &A, &A) -> bool + Send + Sync + 'static, - stream::QuadConstraintStream: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, K, KE, 4>, impl Fn(&S, &[Leaf<'_, A>; 4]) -> bool + Send + Sync>, impl Fn(&[Leaf<'_, A>; 4]) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where E: 'static, KE: 'static, F: 'static, K: 'static, GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &A, &A, &A) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i A, &'i A, &'i A), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, for<'i> TupleCollector: Collector<[Leaf<'i, A>; 4], Value = V, Result = R, Accumulator = Acc>, + stream::QuadConstraintStream: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, K, KE, 4, SelfJoinRowFilter>, impl Fn(&[Leaf<'_, A>; 4]) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where E: 'static, KE: 'static, F: 'static, K: 'static, GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &A, &A, &A) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i A, &'i A, &'i A), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, for<'i> TupleCollector: Collector<[Leaf<'i, A>; 4], Value = V, Result = R, Accumulator = Acc>, stream::QuadConstraintStream: pub fn penalize( self, weight: W, ) -> QuadConstraintBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w A, &'w A, &'w A), Sc> + Send + Sync, stream::QuadConstraintStream: pub fn reward( self, weight: W, ) -> QuadConstraintBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w A, &'w A, &'w A), Sc> + Send + Sync, stream::QuadConstraintStream: pub fn join( self, joiner: J, ) -> PentaConstraintStream, Sc> where J: Joiner + 'static, F: 'static, struct stream::TriConstraintBuilder: pub struct TriConstraintBuilder where Sc: Score,{ /* private fields */ } - stream::TriConstraintBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, K, KE, 3>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 3]) -> bool + Send + Sync>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 3]) -> Sc + Send + Sync, Sc> + stream::TriConstraintBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, K, KE, 3, SelfJoinRowFilter>, impl for<'a, 'b> Fn(&'a S, &[Leaf<'b, A>; 3]) -> Sc + Send + Sync, Sc> struct stream::TriConstraintStream: pub struct TriConstraintStream where Sc: Score,{ /* private fields */ } stream::TriConstraintStream: pub fn new_self_join(extractor: E, key_extractor: KE) -> Self stream::TriConstraintStream: pub fn new_self_join_with_filter( extractor: E, key_extractor: KE, filter: F, ) -> Self stream::TriConstraintStream: pub fn filter

( self, predicate: P, ) -> TriConstraintStream bool + Send + Sync>>, Sc> where P: Fn(&A, &A, &A) -> bool + Send + Sync + 'static, - stream::TriConstraintStream: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, K, KE, 3>, impl Fn(&S, &[Leaf<'_, A>; 3]) -> bool + Send + Sync>, impl Fn(&[Leaf<'_, A>; 3]) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where E: 'static, KE: 'static, F: 'static, K: 'static, GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &A, &A) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i A, &'i A), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, for<'i> TupleCollector: Collector<[Leaf<'i, A>; 3], Value = V, Result = R, Accumulator = Acc>, + stream::TriConstraintStream: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, K, KE, 3, SelfJoinRowFilter>, impl Fn(&[Leaf<'_, A>; 3]) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where E: 'static, KE: 'static, F: 'static, K: 'static, GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &A, &A) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i A, &'i A), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, for<'i> TupleCollector: Collector<[Leaf<'i, A>; 3], Value = V, Result = R, Accumulator = Acc>, stream::TriConstraintStream: pub fn penalize( self, weight: W, ) -> TriConstraintBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w A, &'w A), Sc> + Send + Sync, stream::TriConstraintStream: pub fn reward( self, weight: W, ) -> TriConstraintBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w A, &'w A), Sc> + Send + Sync, stream::TriConstraintStream: pub fn join( self, joiner: J, ) -> QuadConstraintStream, Sc> where J: Joiner + 'static, F: 'static, @@ -223,7 +223,8 @@ struct stream::collector::IndexedPresence: pub struct IndexedPresence { /* priva struct stream::collector::IndexedPresenceAccumulator: pub struct IndexedPresenceAccumulator { /* private fields */ } struct stream::collector::IndexedPresenceCollector: pub struct IndexedPresenceCollector { /* private fields */ } struct stream::collector::LoadBalance: pub struct LoadBalance { /* private fields */ } - stream::collector::LoadBalance: pub fn loads(&self) -> &HashMap + stream::collector::LoadBalance: pub fn loads(&self) -> impl Iterator + stream::collector::LoadBalance: pub fn load(&self, key: &K) -> Option where K: Eq + Hash, stream::collector::LoadBalance: pub fn unfairness(&self) -> i64 struct stream::collector::LoadBalanceAccumulator: pub struct LoadBalanceAccumulator { /* private fields */ } struct stream::collector::LoadBalanceCollector: pub struct LoadBalanceCollector { /* private fields */ } @@ -253,40 +254,40 @@ struct stream::cross::Bi: pub struct Bi where Sc: Sco stream::cross::Bi: pub fn penalize( self, weight: W, ) -> Builder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w B), Sc> + Send + Sync, stream::cross::Bi: pub fn reward( self, weight: W, ) -> Builder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w B), Sc> + Send + Sync, struct stream::cross::Builder: pub struct Builder where Sc: Score, P: CompileCondition,{ /* private fields */ } - stream::cross::Builder: pub fn named( self, name: &str, ) -> OperatorTerminal, impl Fn(&S, &Pair, Leaf<'_, B>>) -> Sc + Send + Sync, Sc> where for<'a> JoinNode, CollectionNode, P::Plan>: Operator = Pair, Leaf<'a, B>>>, + stream::cross::Builder: pub fn named( self, name: &str, ) -> OperatorTerminal, CollectionNode, P::Plan, BiRowFilter>, impl Fn(&S, &Pair, Leaf<'_, B>>) -> Sc + Send + Sync, Sc> where for<'a> JoinNode, CollectionNode, P::Plan>: Operator = Pair, Leaf<'a, B>>>, struct stream::cross::ComplementedGrouped: pub struct ComplementedGrouped where Sc: Score,{ /* private fields */ } stream::cross::ComplementedGrouped: pub fn penalize( self, weight: W, ) -> ComplementedGroupedBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w GK, &'w R), Sc> + Send + Sync, stream::cross::ComplementedGrouped: pub fn reward( self, weight: W, ) -> ComplementedGroupedBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w GK, &'w R), Sc> + Send + Sync, struct stream::cross::ComplementedGroupedBuilder: pub struct ComplementedGroupedBuilder where Sc: Score,{ /* private fields */ } - stream::cross::ComplementedGroupedBuilder: pub fn named( self, name: &str, ) -> SharedOperatorTerminal, GroupNode, F>, impl Fn(&Pair, Leaf<'_, B>>) -> GK + Send + Sync, TupleCollector, GK, Acc, V, R>, ViewEqualPlan, GroupKey>, impl Fn(&S, &Leaf<'_, T>) -> R + Send + Sync, R>, DirectComplementAdapter, OperatorScorer, Sc>, Sc> + stream::cross::ComplementedGroupedBuilder: pub fn named( self, name: &str, ) -> SharedOperatorTerminal, GroupNode, CollectionNode, BiUnaryPlan, BiRowFilter>, impl Fn(&Pair, Leaf<'_, B>>) -> GK + Send + Sync, TupleCollector, GK, Acc, V, R>, GroupEqualPlan, GroupRight>, impl Fn(&S, &Leaf<'_, T>) -> R + Send + Sync, R>, DirectComplementAdapter, OperatorScorer, Sc>, Sc> struct stream::cross::Grouped: pub struct Grouped where Sc: Score,{ /* private fields */ } stream::cross::Grouped: pub fn penalize( self, weight: W, ) -> GroupedBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w GK, &'w R), Sc> + Send + Sync, stream::cross::Grouped: pub fn reward( self, weight: W, ) -> GroupedBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w GK, &'w R), Sc> + Send + Sync, stream::cross::Grouped: pub fn complement( self, extractor_t: ET, key_t: KT, default_fn: D, ) -> ComplementedGrouped where T: Send + Sync + 'static, ET: CollectionExtract, KT: Fn(&T) -> GK + Send + Sync, D: Fn(&T) -> R + Send + Sync, struct stream::cross::GroupedBuilder: pub struct GroupedBuilder where Sc: Score,{ /* private fields */ } - stream::cross::GroupedBuilder: pub fn named( self, name: &str, ) -> SharedOperatorTerminal, F>, impl Fn(&Pair, Leaf<'_, B>>) -> GK + Send + Sync, TupleCollector, GK, Acc, V, R>, GroupAdapter, OperatorScorer, Sc>, Sc> + stream::cross::GroupedBuilder: pub fn named( self, name: &str, ) -> SharedOperatorTerminal, CollectionNode, BiUnaryPlan, BiRowFilter>, impl Fn(&Pair, Leaf<'_, B>>) -> GK + Send + Sync, TupleCollector, GK, Acc, V, R>, GroupAdapter, OperatorScorer, Sc>, Sc> struct stream::cross::Penta: pub struct Penta where Sc: Score, P1: CompileCondition, P2: CompileCondition, P3: CompileCondition, P4: CompileCondition,{ /* private fields */ } stream::cross::Penta: pub fn filter

( self, predicate: P, ) -> Penta bool + Send + Sync>>, Sc> where P: Fn(&A, &B, &C, &D, &E) -> bool + Send + Sync, stream::cross::Penta: pub fn penalize( self, weight: W, ) -> PentaBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C, &'w D, &'w E), Sc> + Send + Sync, stream::cross::Penta: pub fn reward( self, weight: W, ) -> PentaBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C, &'w D, &'w E), Sc> + Send + Sync, - stream::cross::Penta: pub fn join( self, target: (EG, P5), ) -> Chain, CollectionNode, ::Plan>, Sc> where G: Clone + Send + Sync + 'static, EG: CollectionExtract + 'static, P5: CompileCondition + 'static, for<'a> P5::Plan: IndexedPlan + ExecutablePlan<, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan> as Operator>::View<'a>, Leaf<'a, G>>, for<'a> JoinNode, CollectionNode, ::Plan>: Operator, - stream::cross::Penta: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, impl Fn(&S, &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, Leaf<'_, E>>) -> bool + Send + Sync>, impl Fn(&Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, Leaf<'_, E>>) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &B, &C, &D, &E) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i B, &'i C, &'i D, &'i E), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, + stream::cross::Penta: pub fn join( self, target: (EG, P5), ) -> Chain, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan, PentaRowFilter>, CollectionNode, ::Plan>, Sc> where G: Clone + Send + Sync + 'static, EG: CollectionExtract + 'static, P5: CompileCondition + 'static, for<'a> P5::Plan: IndexedPlan + ExecutablePlan<, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan> as Operator>::View<'a>, Leaf<'a, G>>, for<'a> JoinNode, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan, PentaRowFilter>, CollectionNode, ::Plan>: Operator, for<'a> JoinNode, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan, PentaRowFilter>: Operator = Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, Leaf<'a, E>>> + Send + Sync, + stream::cross::Penta: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan, PentaRowFilter>, impl Fn(&Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, Leaf<'_, E>>) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &B, &C, &D, &E) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i B, &'i C, &'i D, &'i E), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, struct stream::cross::PentaBuilder: pub struct PentaBuilder where Sc: Score, P1: CompileCondition, P2: CompileCondition, P3: CompileCondition, P4: CompileCondition,{ /* private fields */ } - stream::cross::PentaBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, impl Fn(&S, &, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan> as Operator>::View<'_>) -> Sc + Send + Sync, Sc> + stream::cross::PentaBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan, PentaRowFilter>, impl Fn(&S, &, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan> as Operator>::View<'_>) -> Sc + Send + Sync, Sc> struct stream::cross::Quad: pub struct Quad where Sc: Score, P1: CompileCondition, P2: CompileCondition, P3: CompileCondition,{ /* private fields */ } stream::cross::Quad: pub fn filter

( self, predicate: P, ) -> Quad bool + Send + Sync>>, Sc> where P: Fn(&A, &B, &C, &D) -> bool + Send + Sync, stream::cross::Quad: pub fn join( self, target: (EE, P4), ) -> Penta, Sc> where E: Send + Sync + 'static, EE: CollectionExtract + 'static, P4: CompileCondition + 'static, for<'a> P4::Plan: IndexedPlan + ExecutablePlan, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, Leaf<'a, E>>, for<'a> JoinNode, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>: Operator = Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>>, for<'a> JoinNode, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>: Operator, stream::cross::Quad: pub fn penalize( self, weight: W, ) -> QuadBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C, &'w D), Sc> + Send + Sync, stream::cross::Quad: pub fn reward( self, weight: W, ) -> QuadBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C, &'w D), Sc> + Send + Sync, - stream::cross::Quad: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>, impl Fn(&S, &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>) -> bool + Send + Sync>, impl Fn(&Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &B, &C, &D) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i B, &'i C, &'i D), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, + stream::cross::Quad: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan, QuadRowFilter>, impl Fn(&Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &B, &C, &D) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i B, &'i C, &'i D), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, struct stream::cross::QuadBuilder: pub struct QuadBuilder where Sc: Score, P1: CompileCondition, P2: CompileCondition, P3: CompileCondition,{ /* private fields */ } - stream::cross::QuadBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, impl Fn(&S, &, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan> as Operator>::View<'_>) -> Sc + Send + Sync, Sc> + stream::cross::QuadBuilder: pub fn named( self, name: &str, ) -> OperatorTerminal, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan, QuadRowFilter>, impl Fn(&S, &, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan> as Operator>::View<'_>) -> Sc + Send + Sync, Sc> struct stream::cross::Tri: pub struct Tri where Sc: Score, P1: CompileCondition, P2: CompileCondition,{ /* private fields */ } stream::cross::Tri: pub fn filter

( self, predicate: P, ) -> Tri bool + Send + Sync>>, Sc> where P: Fn(&A, &B, &C) -> bool + Send + Sync, stream::cross::Tri: pub fn join( self, target: (ED, P3), ) -> Quad, Sc> where D: Send + Sync + 'static, ED: CollectionExtract + 'static, P3: CompileCondition + 'static, for<'a> P3::Plan: IndexedPlan + ExecutablePlan, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, for<'a> JoinNode, CollectionNode, ::Plan>, CollectionNode, ::Plan>: Operator = Pair, Leaf<'a, B>>, Leaf<'a, C>>>, for<'a> JoinNode, CollectionNode, ::Plan>, CollectionNode, ::Plan>, CollectionNode, ::Plan>: Operator, stream::cross::Tri: pub fn penalize( self, weight: W, ) -> Builder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C), Sc> + Send + Sync, stream::cross::Tri: pub fn reward( self, weight: W, ) -> Builder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C), Sc> + Send + Sync, - stream::cross::Tri: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, CollectionNode, ::Plan>, CollectionNode, ::Plan>, impl Fn(&S, &Pair, Leaf<'_, B>>, Leaf<'_, C>>) -> bool + Send + Sync>, impl Fn(&Pair, Leaf<'_, B>>, Leaf<'_, C>>) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &B, &C) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i B, &'i C), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, + stream::cross::Tri: pub fn group_by( self, key: GF, collector: Co, ) -> JoinedGroupedStream, CollectionNode, ::Plan>, CollectionNode, ::Plan, TriRowFilter>, impl Fn(&Pair, Leaf<'_, B>>, Leaf<'_, C>>) -> GK + Send + Sync, TupleCollector, GK, V, R, Acc, Sc> where GK: Eq + Hash + Clone + Send + Sync + 'static, GF: Fn(&A, &B, &C) -> GK + Send + Sync + 'static, Co: for<'i> Collector<(&'i A, &'i B, &'i C), Value = V, Result = R, Accumulator = Acc> + 'static, V: Send + Sync + 'static, R: Send + Sync + 'static, Acc: Accumulator + 'static, struct stream::filter::AndBiFilter: pub struct AndBiFilter { /* private fields */ } stream::filter::AndBiFilter: pub fn new(first: F1, second: F2) -> Self struct stream::filter::AndPentaFilter: pub struct AndPentaFilter { /* private fields */ } @@ -307,6 +308,8 @@ struct stream::filter::FnTriFilter: pub struct FnTriFilter { /* private field stream::filter::FnTriFilter: pub fn new(f: F) -> Self struct stream::filter::FnUniFilter: pub struct FnUniFilter { /* private fields */ } stream::filter::FnUniFilter: pub fn new(f: F) -> Self +struct stream::filter::SelfJoinRowFilter: pub struct SelfJoinRowFilter { /* private fields */ } + stream::filter::SelfJoinRowFilter: pub fn new(filter: F) -> Self struct stream::filter::TrueFilter: pub struct TrueFilter; struct stream::filter::UniBiFilter: pub struct UniBiFilter { /* private fields */ } stream::filter::UniBiFilter: pub fn new(filter: F) -> Self @@ -360,7 +363,7 @@ struct stream::projected::ComplementedGrouped: pub struct ComplementedGrouped( self, weight: W, ) -> ComplementedGroupedBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w K, &'w R), Sc> + Send + Sync, stream::projected::ComplementedGrouped: pub fn reward( self, weight: W, ) -> ComplementedGroupedBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w K, &'w R), Sc> + Send + Sync, struct stream::projected::ComplementedGroupedBuilder: pub struct ComplementedGroupedBuilder where Sc: Score,{ /* private fields */ } - stream::projected::ComplementedGroupedBuilder: pub fn named( self, name: &str, ) -> SharedOperatorTerminal, GroupNode, impl Fn(&S, &ProjectedRow<'_, Out>) -> bool + Send + Sync>, impl Fn(&ProjectedRow<'_, Out>) -> Option + Send + Sync, ProjectedCollector, Option, Acc, V, R>, ViewEqualPlan, OptionalEntityKey, GroupKey>, impl Fn(&S, &Leaf<'_, B>) -> R + Send + Sync, R>, OptionalComplementAdapter, OperatorScorer, Sc>, Sc> + stream::projected::ComplementedGroupedBuilder: pub fn named( self, name: &str, ) -> SharedOperatorTerminal, GroupNode, impl Fn(&S, &ProjectedRow<'_, Out>) -> bool + Send + Sync>, impl Fn(&ProjectedRow<'_, Out>) -> Option + Send + Sync, ProjectedCollector, Option, Acc, V, R>, GroupEqualPlan, OptionalEntityKey, GroupRight>, impl Fn(&S, &Leaf<'_, B>) -> R + Send + Sync, R>, OptionalComplementAdapter, OperatorScorer, Sc>, Sc> struct stream::projected::DirectedBi: pub struct DirectedBi where Sc: Score,{ /* private fields */ } stream::projected::DirectedBi: pub fn filter

( self, predicate: P, ) -> DirectedBi bool + Send + Sync>>, Sc> where P: Fn(&Out, &Out) -> bool + Send + Sync + 'static, stream::projected::DirectedBi: pub fn penalize( self, weight: W, ) -> DirectedBiBuilder Sc + Send + Sync, Sc> where W: for<'w> ConstraintWeight<(&'w Out, &'w Out), Sc> + Send + Sync, @@ -392,9 +395,10 @@ struct stream::relational::Concat: pub struct Concat<'r, Left, T> { pub left: Le stream::relational::Concat: pub fn new(left: Left, entity: &'r T, index: usize) -> Concat<'r, Left, T> struct stream::relational::Leaf: pub struct Leaf<'r, T> { pub entity: &'r T, pub index: usize, } stream::relational::Leaf: pub fn new(entity: &'r T, index: usize) -> Leaf<'r, T> +struct stream::relational::operator::AcceptAll: pub struct AcceptAll; struct stream::relational::operator::CollectionNode: pub struct CollectionNode { /* private fields */ } stream::relational::operator::CollectionNode: pub fn new(extractor: E, binding: u32) -> Self -struct stream::relational::operator::ComplementNode: pub struct ComplementNode::Key>, F, T> { /* private fields */ } +struct stream::relational::operator::ComplementNode: pub struct ComplementNode { /* private fields */ } stream::relational::operator::ComplementNode: pub fn new>( targets: L, results: R, condition: C, default: F, ) -> Self struct stream::relational::operator::ExistenceNode: pub struct ExistenceNode { /* private fields */ } stream::relational::operator::ExistenceNode: pub fn new( left: L, right: R, left_key: LK, right_keys: RK, exists: bool, ) -> Self @@ -409,8 +413,9 @@ struct stream::relational::operator::GroupRightKeys: pub struct GroupRightKeys Self struct stream::relational::operator::GroupView: pub struct GroupView<'a, S: 'static, O: Operator, K, A, V, R> { pub key: &'a K, /* private fields */ } stream::relational::operator::GroupView: pub fn with_result(&self, f: impl FnOnce(&R) -> T) -> T -struct stream::relational::operator::JoinNode: pub struct JoinNode { /* private fields */ } +struct stream::relational::operator::JoinNode: pub struct JoinNode { /* private fields */ } stream::relational::operator::JoinNode: pub fn new>( left: L, right: R, condition: C, ) -> Self + stream::relational::operator::JoinNode: pub fn filtered>( left: L, right: R, condition: C, filter: F, ) -> Self struct stream::relational::operator::JoinerExistenceNode: pub struct JoinerExistenceNode { /* private fields */ } stream::relational::operator::JoinerExistenceNode: pub fn new>( left: L, right: R, condition: C, exists: bool, ) -> Self struct stream::relational::operator::MergeNode: pub struct MergeNode { /* private fields */ } @@ -423,8 +428,9 @@ struct stream::relational::operator::ParentFlatten: pub struct ParentFlatten { /* private fields */ } stream::relational::operator::ProjectNode: pub fn new(input: O, mapper: F) -> Self struct stream::relational::operator::ProjectView: pub struct ProjectView<'a, V, T> { pub input: V, pub value: &'a T, pub emission: usize, } -struct stream::relational::operator::SelfJoinNode: pub struct SelfJoinNode { /* private fields */ } +struct stream::relational::operator::SelfJoinNode: pub struct SelfJoinNode { /* private fields */ } stream::relational::operator::SelfJoinNode: pub fn new(input: O, key: KE) -> Self + stream::relational::operator::SelfJoinNode: pub fn filtered(input: O, key: KE, filter: F) -> Self struct stream::relational::operator::UnitKeys: pub struct UnitKeys(/* private fields */); stream::relational::operator::UnitKeys: pub fn new(inner: VK) -> Self struct stream::relational::view_plan::ChildKey: pub struct ChildKey(/* private fields */); @@ -433,7 +439,10 @@ struct stream::relational::view_plan::EntityKey: pub struct EntityKey(/* priv stream::relational::view_plan::EntityKey: pub fn new(inner: F) -> Self struct stream::relational::view_plan::FlattenedPairKey: pub struct FlattenedPairKey(/* private fields */); stream::relational::view_plan::FlattenedPairKey: pub fn new(owner_key: KB, child_key: CK) -> Self -struct stream::relational::view_plan::GroupKey: pub struct GroupKey; +struct stream::relational::view_plan::GroupEqualPlan: pub struct GroupEqualPlan { /* private fields */ } + stream::relational::view_plan::GroupEqualPlan: pub fn new(key: KeyFn) -> Self +struct stream::relational::view_plan::GroupLeft: pub struct GroupLeft; +struct stream::relational::view_plan::GroupRight: pub struct GroupRight; struct stream::relational::view_plan::PairKey: pub struct PairKey(/* private fields */); stream::relational::view_plan::PairKey: pub fn new(first: A, second: B) -> Self struct stream::relational::view_plan::ViewEqualPlan: pub struct ViewEqualPlan { /* private fields */ } @@ -611,7 +620,8 @@ trait stream::projected::Source: pub trait Source: Send + Sync { type St stream::projected::Source: fn collect_entity( &self, solution: &S, state: &Self::State, slot: usize, entity_index: usize, visit: V, ) where V: FnMut(RowCoordinate, Out), stream::projected::Source: fn insert_entity_state( &self, solution: &S, state: &mut Self::State, slot: usize, entity_index: usize, ) stream::projected::Source: fn retract_entity_state( &self, solution: &S, state: &mut Self::State, slot: usize, entity_index: usize, ) -trait stream::relational::operator::FilterPredicate: pub trait FilterPredicate: Send + Sync { // Required method fn accepts(&self, solution: &S, row: &V) -> bool; } +trait stream::relational::operator::FilterPredicate: pub trait FilterPredicate: Send + Sync { const ACCEPTS_ALL: bool = false; // Required method fn accepts(&self, solution: &S, row: &V) -> bool; } + stream::relational::operator::FilterPredicate: const ACCEPTS_ALL: bool = false stream::relational::operator::FilterPredicate: fn accepts(&self, solution: &S, row: &V) -> bool trait stream::relational::operator::FlattenSource: pub trait FlattenSource> { type Item: 'static; // Required method fn flatten<'a>( &self, solution: &'a S, view: O::View<'a>, ) -> &'a [Self::Item]; } stream::relational::operator::FlattenSource: type Item: 'static @@ -642,7 +652,7 @@ fn stream::collector::collect_vec: pub fn collect_vec(mapper: F) -> Collec fn stream::collector::consecutive_runs: pub fn consecutive_runs(index_fn: F) -> RunsCollector where F: Send + Sync, fn stream::collector::count: pub const fn count() -> CountCollector fn stream::collector::indexed_presence: pub fn indexed_presence(index_fn: F) -> IndexedPresenceCollector where F: Send + Sync, -fn stream::collector::load_balance: pub fn load_balance( key_fn: F, metric_fn: M, ) -> LoadBalanceCollector where K: Clone + Eq + Hash + Send + Sync, F: Send + Sync, M: Send + Sync, +fn stream::collector::load_balance: pub fn load_balance( key_fn: F, metric_fn: M, ) -> LoadBalanceCollector where K: Eq + Hash + Send + Sync, F: Send + Sync, M: Send + Sync, fn stream::collector::sum: pub fn sum(mapper: F) -> SumCollector where T: Default + Copy + AddAssign + SubAssign + Send + Sync + 'static, F: Send + Sync + 'static, fn stream::fixed_weight: pub const fn fixed_weight(score: Sc) -> FixedWeight fn stream::hard_weight: pub const fn hard_weight(weight: W) -> HardWeight diff --git a/crates/solverforge-scoring/src/constraint/balance.rs b/crates/solverforge-scoring/src/constraint/balance.rs index 35efe62aa..2a9426455 100644 --- a/crates/solverforge-scoring/src/constraint/balance.rs +++ b/crates/solverforge-scoring/src/constraint/balance.rs @@ -17,6 +17,7 @@ use solverforge_core::{ConstraintRef, ImpactType}; use crate::api::constraint_set::IncrementalConstraint; use crate::stream::collection_extract::ChangeSource; use crate::stream::filter::UniFilter; +use crate::stream::relational::KeyTable; /// Zero-erasure balance constraint that penalizes uneven load distribution. /// @@ -114,10 +115,10 @@ where // Base score representing 1 unit of standard deviation base_score: Sc, is_hard: bool, - // Group key → count of entities in that group - counts: HashMap, - // Entity index → group key (for tracking assignments) - entity_keys: HashMap, + // Group key → count of entities in that group; each key stored once + counts: KeyTable, + // Entity index → its group's slot in `counts` + entity_keys: HashMap, // Cached statistics for incremental updates // Number of groups (employees with at least one shift) group_count: i64, @@ -135,7 +136,7 @@ impl BalanceConstraint where S: Send + Sync + 'static, A: Send + Sync + 'static, - K: Clone + Eq + Hash + Send + Sync + 'static, + K: Eq + Hash + Send + Sync + 'static, E: crate::stream::collection_extract::CollectionExtract, F: UniFilter, KF: Fn(&A) -> Option + Send + Sync, @@ -171,7 +172,7 @@ where change_source, base_score, is_hard, - counts: HashMap::new(), + counts: KeyTable::new(), entity_keys: HashMap::new(), group_count: 0, total_count: 0, @@ -181,6 +182,22 @@ where } } + /// Counts one entity into its key's group, taking ownership of the key + /// when the group is new. + fn add_to_group(&mut self, entity_index: usize, key: K) { + let group = self.counts.find_or_insert(key, || 0); + let count = self.counts.get_mut(group); + let old_count = *count; + *count += 1; + let new_count = *count; + self.entity_keys.insert(entity_index, group); + if old_count == 0 { + self.group_count += 1; + } + self.total_count += 1; + self.sum_squared += new_count * new_count - old_count * old_count; + } + /// Computes standard deviation from cached statistics. fn compute_std_dev(&self) -> f64 { if self.group_count == 0 { @@ -242,7 +259,7 @@ impl IncrementalConstraint where S: Send + Sync + 'static, A: Send + Sync + 'static, - K: Clone + Eq + Hash + Send + Sync + 'static, + K: Eq + Hash + Send + Sync + 'static, E: crate::stream::collection_extract::CollectionExtract, F: UniFilter, KF: Fn(&A) -> Option + Send + Sync, @@ -311,21 +328,7 @@ where continue; } if let Some(key) = (self.key_fn)(entity) { - let old_count = *self.counts.get(&key).unwrap_or(&0); - let new_count = old_count + 1; - match self.counts.get_mut(&key) { - Some(slot) => *slot = new_count, - None => { - self.counts.insert(key.clone(), new_count); - } - } - self.entity_keys.insert(idx, key); - - if old_count == 0 { - self.group_count += 1; - } - self.total_count += 1; - self.sum_squared += new_count * new_count - old_count * old_count; + self.add_to_group(idx, key); } } @@ -363,22 +366,7 @@ where }; let old_score = self.score; - - let old_count = *self.counts.get(&key).unwrap_or(&0); - let new_count = old_count + 1; - match self.counts.get_mut(&key) { - Some(slot) => *slot = new_count, - None => { - self.counts.insert(key.clone(), new_count); - } - } - self.entity_keys.insert(entity_index, key); - - if old_count == 0 { - self.group_count += 1; - } - self.total_count += 1; - self.sum_squared += new_count * new_count - old_count * old_count; + self.add_to_group(entity_index, key); let (new_score, overflowed) = self.score_parts(); self.score = new_score; @@ -407,23 +395,19 @@ where } // Check if this entity was tracked - let Some(key) = self.entity_keys.remove(&entity_index) else { + let Some(group) = self.entity_keys.remove(&entity_index) else { return (Sc::zero(), false); }; let old_score = self.score; - let old_count = *self.counts.get(&key).unwrap_or(&0); - if old_count == 0 { - return (Sc::zero(), false); - } - + let old_count = *self.counts.get(group); let new_count = old_count - 1; if new_count == 0 { - self.counts.remove(&key); + self.counts.remove(group); self.group_count -= 1; } else { - self.counts.insert(key, new_count); + *self.counts.get_mut(group) = new_count; } self.total_count -= 1; self.sum_squared += new_count * new_count - old_count * old_count; @@ -464,7 +448,7 @@ where f.debug_struct("BalanceConstraint") .field("name", &self.constraint_ref.name) .field("impact_type", &self.impact_type) - .field("groups", &self.counts.len()) + .field("groups", &self.group_count) .finish() } } diff --git a/crates/solverforge-scoring/src/constraint/list_precedence.rs b/crates/solverforge-scoring/src/constraint/list_precedence.rs index 332519b18..6df262f55 100644 --- a/crates/solverforge-scoring/src/constraint/list_precedence.rs +++ b/crates/solverforge-scoring/src/constraint/list_precedence.rs @@ -185,7 +185,7 @@ where let mut change = state.take_route_change_scratch(); state.flush_pending_retractions(&mut change, entity_index); state.replace_owner_route_scratch_with(&mut change, solution, entity_index, access); - let after = state.refresh_score_after_route_change(&change); + let after = state.refresh_score_after_route_change(&mut change); state.restore_route_change_scratch(change); after - before } diff --git a/crates/solverforge-scoring/src/constraint/list_precedence/graph.rs b/crates/solverforge-scoring/src/constraint/list_precedence/graph.rs index 8a31cea0e..6cad48fe4 100644 --- a/crates/solverforge-scoring/src/constraint/list_precedence/graph.rs +++ b/crates/solverforge-scoring/src/constraint/list_precedence/graph.rs @@ -8,7 +8,7 @@ impl ListPrecedenceState { pub(super) fn refresh_score_after_route_change( &mut self, - change: &RouteChange, + change: &mut RouteChange, ) -> HardSoftScore { self.refresh_graph_after_route_change(change); self.refresh_score_from_cached_graph() @@ -25,9 +25,12 @@ impl ListPrecedenceState { self.score } + /// Refreshes the cached graph for one route change. A change that closes + /// a cycle hands its added edges to the cycle cache, leaving `change` + /// with stale edges its next use clears. pub(super) fn refresh_graph_after_route_change( &mut self, - change: &RouteChange, + change: &mut RouteChange, ) -> GraphRefreshKind { if change.is_empty() && self.deferred_seeds.is_empty() { return GraphRefreshKind::Skipped; @@ -156,9 +159,9 @@ impl ListPrecedenceState { } } - fn mark_cyclic_from_route_change(&mut self, change: &RouteChange) { + fn mark_cyclic_from_route_change(&mut self, change: &mut RouteChange) { self.clear_deferred_seeds(); - self.cycle_added_edges = change.added_edges.clone(); + std::mem::swap(&mut self.cycle_added_edges, &mut change.added_edges); self.cycle_penalty = self.node_count; self.makespan = 0; self.max_finish_nodes = self.node_count; diff --git a/crates/solverforge-scoring/src/constraint/list_precedence/tests/graph.rs b/crates/solverforge-scoring/src/constraint/list_precedence/tests/graph.rs index 22373450a..3b91ebe10 100644 --- a/crates/solverforge-scoring/src/constraint/list_precedence/tests/graph.rs +++ b/crates/solverforge-scoring/src/constraint/list_precedence/tests/graph.rs @@ -12,7 +12,7 @@ fn acyclic_graph_route_change_uses_incremental_descendant_refresh() { } assert_eq!( - state.refresh_graph_after_route_change(&change), + state.refresh_graph_after_route_change(&mut change), GraphRefreshKind::Incremental { visited: 1 } ); assert_eq!(state.cycle_penalty, 0); @@ -33,7 +33,7 @@ fn cycle_introducing_route_change_marks_cyclic_without_graph_rebuild() { } assert_eq!( - state.refresh_graph_after_route_change(&change), + state.refresh_graph_after_route_change(&mut change), GraphRefreshKind::CycleDetected ); assert_eq!(state.cycle_penalty, 3); @@ -49,7 +49,7 @@ fn cycle_retraction_recovers_cached_acyclic_state_without_graph_rebuild() { cycle_change.added_edges.push((2, 0)); } assert_eq!( - state.refresh_graph_after_route_change(&cycle_change), + state.refresh_graph_after_route_change(&mut cycle_change), GraphRefreshKind::CycleDetected ); assert_eq!(state.cycle_penalty, 3); @@ -60,7 +60,7 @@ fn cycle_retraction_recovers_cached_acyclic_state_without_graph_rebuild() { undo_change.removed_edges.push((2, 0)); } assert_eq!( - state.refresh_graph_after_route_change(&undo_change), + state.refresh_graph_after_route_change(&mut undo_change), GraphRefreshKind::CycleRecovered ); assert_eq!(state.cycle_penalty, 0); @@ -81,7 +81,7 @@ fn cycle_introduced_with_removed_edges_recovers_by_full_rebuild() { cycle_change.added_edges.push((2, 1)); } assert_eq!( - state.refresh_graph_after_route_change(&cycle_change), + state.refresh_graph_after_route_change(&mut cycle_change), GraphRefreshKind::CycleDetected ); assert_eq!(state.cycle_penalty, 3); @@ -92,7 +92,7 @@ fn cycle_introduced_with_removed_edges_recovers_by_full_rebuild() { undo_change.removed_edges.push((2, 1)); } assert_eq!( - state.refresh_graph_after_route_change(&undo_change), + state.refresh_graph_after_route_change(&mut undo_change), GraphRefreshKind::Full ); assert_eq!(state.cycle_penalty, 0); @@ -217,7 +217,7 @@ fn cyclic_state_with_unmatched_change_uses_full_graph_refresh() { cycle_change.added_edges.push((2, 0)); } assert_eq!( - state.refresh_graph_after_route_change(&cycle_change), + state.refresh_graph_after_route_change(&mut cycle_change), GraphRefreshKind::CycleDetected ); @@ -226,7 +226,7 @@ fn cyclic_state_with_unmatched_change_uses_full_graph_refresh() { unrelated_change.added_edges.push((2, 3)); } assert_eq!( - state.refresh_graph_after_route_change(&unrelated_change), + state.refresh_graph_after_route_change(&mut unrelated_change), GraphRefreshKind::Full ); assert_eq!(state.cycle_penalty, 4); diff --git a/crates/solverforge-scoring/src/constraint/relational/grouped_weights.rs b/crates/solverforge-scoring/src/constraint/relational/grouped_weights.rs index 3577c4be1..f3d54794a 100644 --- a/crates/solverforge-scoring/src/constraint/relational/grouped_weights.rs +++ b/crates/solverforge-scoring/src/constraint/relational/grouped_weights.rs @@ -238,11 +238,7 @@ macro_rules! impl_complement_weight { R: Send + Sync + 'static, B: Send + Sync + 'static, EB: crate::stream::collection_extract::CollectionExtract + 'static, - P: crate::stream::joiner::plan::IndexedPlan - + crate::stream::relational::keyed_plan::KeyOf - + crate::stream::relational::keyed_plan::RightKeyOf< - Key =

::Key, - > + 'static, + P: crate::stream::relational::keyed_plan::KeyedRegain + 'static, for<'a> P: crate::stream::joiner::plan::ExecutablePlan< Leaf<'a, B>, GroupView<'a, S, I, $group_key, Acc, V, R>, @@ -301,11 +297,7 @@ macro_rules! impl_complement_weight { R: Send + Sync + 'static, B: Send + Sync + 'static, EB: crate::stream::collection_extract::CollectionExtract + 'static, - P: crate::stream::joiner::plan::IndexedPlan - + crate::stream::relational::keyed_plan::KeyOf - + crate::stream::relational::keyed_plan::RightKeyOf< - Key =

::Key, - > + 'static, + P: crate::stream::relational::keyed_plan::KeyedRegain + 'static, for<'a> P: crate::stream::joiner::plan::ExecutablePlan< Leaf<'a, B>, GroupView<'a, S, I, $group_key, Acc, V, R>, diff --git a/crates/solverforge-scoring/src/constraint/tests/relational/complement_producer.rs b/crates/solverforge-scoring/src/constraint/tests/relational/complement_producer.rs index 1c69c16fd..4b2ff4008 100644 --- a/crates/solverforge-scoring/src/constraint/tests/relational/complement_producer.rs +++ b/crates/solverforge-scoring/src/constraint/tests/relational/complement_producer.rs @@ -206,3 +206,78 @@ fn complemented_rows_remain_joinable_through_repeated_target_descriptor_churn() ); } } + +struct Keys { + keys: Vec, +} +fn keys(m: &Keys) -> &[u32] { + &m.keys +} +fn own_key(row: &Leaf<'_, u32>) -> u32 { + *row.entity +} +fn keys_group_key>( + row: &GroupView<'_, Keys, O, u32, CountAccumulator, (), usize>, +) -> u32 { + *row.key +} +fn keys_default(_: &Keys, _: &Leaf<'_, u32>) -> Payload { + Payload(-1000) +} +fn keys_weight>( + _: &Keys, + row: &ComplementView< + '_, + Leaf<'_, u32>, + GroupView<'_, Keys, O, u32, CountAccumulator, (), usize>, + Payload, + >, +) -> SoftScore { + match row { + ComplementView::Real(pair) => pair + .right + .with_result(|r| SoftScore::of(*r as i64 * 7 + *pair.left.entity as i64)), + ComplementView::Default(projected) => SoftScore::of(projected.value.0), + } +} + +#[test] +fn one_change_inserting_a_target_and_its_result_emits_the_pair_once() { + let rows = || { + CollectionNode::new( + source(keys as fn(&Keys) -> &[u32], ChangeSource::Descriptor(0)), + 0, + ) + }; + let group = GroupNode::new(rows(), own_key, count()); + let tree = ComplementNode::new( + rows(), + group, + equal_bi(own_key, keys_group_key), + keys_default, + ); + let mut c = OperatorTerminal::new( + ConstraintRef::new("test", "self_complement"), + ImpactType::Reward, + tree, + keys_weight, + false, + ); + let mut m = Keys { + keys: vec![1, 1, 2, 3, 3, 3], + }; + let mut score = c.initialize(&m); + assert_eq!(score, c.evaluate(&m)); + let mut state = 0x2545_f491_u32; + for _ in 0..200 { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + let index = (state % 6) as usize; + score = score + c.on_retract(&m, index, 0); + m.keys[index] = (state >> 8) % 4; + score = score + c.on_insert(&m, index, 0); + assert_eq!(score, c.evaluate(&m)); + assert_eq!(c.get_matches(&m).len(), c.match_count(&m)); + } +} diff --git a/crates/solverforge-scoring/src/constraint/tests/relational/group_plan.rs b/crates/solverforge-scoring/src/constraint/tests/relational/group_plan.rs new file mode 100644 index 000000000..03e7cacb2 --- /dev/null +++ b/crates/solverforge-scoring/src/constraint/tests/relational/group_plan.rs @@ -0,0 +1,174 @@ +//! Group-keyed plans under colliding key hashes: the hash-only group index +//! must still pair each group with exactly the rows of its own key. + +use std::hash::{Hash, Hasher}; + +use crate::api::constraint_set::IncrementalConstraint; +use crate::constraint::relational::OperatorTerminal; +use crate::stream::collection_extract::{source, ChangeSource}; +use crate::stream::collector::{count, CountAccumulator}; +use crate::stream::relational::{ + operator::{ + CollectionNode, ComplementNode, ComplementView, GroupNode, GroupView, JoinNode, Operator, + Pair, + }, + EntityKey, GroupEqualPlan, GroupLeft, GroupRight, Leaf, +}; +use solverforge_core::{score::SoftScore, ConstraintRef, ImpactType}; + +/// A key whose hash ignores its value, so every key shares one hash. +#[derive(Debug, PartialEq, Eq)] +struct Colliding(u32); +impl Hash for Colliding { + fn hash(&self, hasher: &mut H) { + 0u8.hash(hasher); + } +} + +struct Model { + entities: Vec, + targets: Vec, +} +fn entities(m: &Model) -> &[u32] { + &m.entities +} +fn targets(m: &Model) -> &[u32] { + &m.targets +} +fn row_key(row: &Leaf<'_, u32>) -> Colliding { + Colliding(*row.entity) +} +fn value_key(value: &u32) -> Colliding { + Colliding(*value) +} +fn default(_: &Model, row: &Leaf<'_, u32>) -> i64 { + -100 - *row.entity as i64 +} +type Group<'a, O> = GroupView<'a, Model, O, Colliding, CountAccumulator, (), usize>; +fn complement_weight>( + _: &Model, + row: &ComplementView<'_, Leaf<'_, u32>, Group<'_, O>, i64>, +) -> SoftScore { + match row { + ComplementView::Real(pair) => pair + .right + .with_result(|n| SoftScore::of(*n as i64 * 10 + pair.right.key.0 as i64)), + ComplementView::Default(projected) => SoftScore::of(*projected.value), + } +} +fn join_weight>( + _: &Model, + row: &Pair, Leaf<'_, u32>>, +) -> SoftScore { + row.left + .with_result(|n| SoftScore::of(*n as i64 * 10 + *row.right.entity as i64)) +} +fn group() -> GroupNode< + CollectionNode< + Model, + impl crate::stream::collection_extract::CollectionExtract, + >, + fn(&Leaf<'_, u32>) -> Colliding, + crate::stream::collector::CountCollector, + Colliding, + CountAccumulator, + (), + usize, +> { + GroupNode::new( + CollectionNode::new( + source( + entities as fn(&Model) -> &[u32], + ChangeSource::Descriptor(0), + ), + 0, + ), + row_key as fn(&Leaf<'_, u32>) -> Colliding, + count(), + ) +} +fn target_rows() -> CollectionNode< + Model, + impl crate::stream::collection_extract::CollectionExtract, +> { + CollectionNode::new( + source(targets as fn(&Model) -> &[u32], ChangeSource::Descriptor(1)), + 1, + ) +} + +/// Steps the model through seeded edits of both collections, checking the +/// incremental score against a full evaluation after every step. +fn churn(c: &mut impl IncrementalConstraint, m: &mut Model) { + let mut score = c.initialize(m); + assert_eq!(score, c.evaluate(m)); + let mut state = 0x9e37_79b9_u32; + for _ in 0..300 { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + let descriptor = (state & 1) as usize; + let len = if descriptor == 0 { + m.entities.len() + } else { + m.targets.len() + }; + let index = (state >> 1) as usize % len; + let value = (state >> 9) % 5; + score = score + c.on_retract(m, index, descriptor); + if descriptor == 0 { + m.entities[index] = value; + } else { + m.targets[index] = value; + } + score = score + c.on_insert(m, index, descriptor); + assert_eq!(score, c.evaluate(m)); + assert_eq!(c.get_matches(m).len(), c.match_count(m)); + } +} + +#[test] +fn complement_pairs_each_target_with_its_own_group_under_colliding_hashes() { + let tree = ComplementNode::new( + target_rows(), + group(), + GroupEqualPlan::::new(EntityKey::new(value_key)), + default, + ); + let mut c = OperatorTerminal::new( + ConstraintRef::new("test", "colliding complement"), + ImpactType::Reward, + tree, + complement_weight, + false, + ); + let mut m = Model { + entities: vec![1, 1, 2, 3], + targets: vec![1, 2, 4, 4], + }; + // Targets 1 and 2 meet their groups; both 4s take the default. + assert_eq!(c.evaluate(&m), SoftScore::of(21 + 12 - 104 - 104)); + churn(&mut c, &mut m); +} + +#[test] +fn group_join_pairs_each_group_with_its_own_rows_under_colliding_hashes() { + let tree = JoinNode::new( + group(), + target_rows(), + GroupEqualPlan::::new(EntityKey::new(value_key)), + ); + let mut c = OperatorTerminal::new( + ConstraintRef::new("test", "colliding group join"), + ImpactType::Reward, + tree, + join_weight, + false, + ); + let mut m = Model { + entities: vec![1, 1, 2, 3], + targets: vec![1, 2, 2, 4], + }; + assert_eq!(c.evaluate(&m), SoftScore::of(21 + 12 + 12)); + churn(&mut c, &mut m); +} diff --git a/crates/solverforge-scoring/src/constraint/tests/relational/mod.rs b/crates/solverforge-scoring/src/constraint/tests/relational/mod.rs index 752f34f74..3ca100b1a 100644 --- a/crates/solverforge-scoring/src/constraint/tests/relational/mod.rs +++ b/crates/solverforge-scoring/src/constraint/tests/relational/mod.rs @@ -20,6 +20,7 @@ mod fixtures; mod flatten_producer; mod fluent_chain; mod fluent_deep_chain; +mod group_plan; mod group_producer; mod grouped_join_fluent; mod handle_map; diff --git a/crates/solverforge-scoring/src/constraint/tests/relational/self_join_node.rs b/crates/solverforge-scoring/src/constraint/tests/relational/self_join_node.rs index 8d9e4ecbc..5f4e5498c 100644 --- a/crates/solverforge-scoring/src/constraint/tests/relational/self_join_node.rs +++ b/crates/solverforge-scoring/src/constraint/tests/relational/self_join_node.rs @@ -150,3 +150,87 @@ fn triple_incremental_matches_full_evaluation() { assert_eq!(n.handles().len(), 1); // C(3,3)=1 remains assert_eq!(n.handles().len(), tri_rows(&n, &m)); } + +fn retained_indexes( + n: &SelfJoinNode< + Model, + Item, + CollectionNode, + u32, + fn(&Model, &Item, usize) -> u32, + N, + >, + m: &Model, +) -> Vec<[usize; N]> { + let mut out: Vec<[usize; N]> = n + .handles() + .into_iter() + .map(|h| n.resolve(m, h).expect("live row").map(|leaf| leaf.index)) + .collect(); + out.sort_unstable(); + out +} + +fn evaluated_indexes( + n: &SelfJoinNode< + Model, + Item, + CollectionNode, + u32, + fn(&Model, &Item, usize) -> u32, + N, + >, + m: &Model, +) -> Vec<[usize; N]> { + let mut out = Vec::new(); + n.visit_all(m, &mut |row: [Leaf<'_, Item>; N]| { + out.push(row.map(|leaf| leaf.index)) + }); + out.sort_unstable(); + out +} + +fn churn( + mut n: SelfJoinNode< + Model, + Item, + CollectionNode, + u32, + fn(&Model, &Item, usize) -> u32, + N, + >, +) { + let mut rm = Vec::new(); + let mut ins = Vec::new(); + let mut m = Model { + items: (0..12).map(|i| Item { key: i % 3 }).collect(), + }; + n.initialize(&m); + assert_eq!(retained_indexes(&n, &m), evaluated_indexes(&n, &m)); + let mut state = 0x9e37_79b9_u32; + for _ in 0..400 { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + let index = (state % 12) as usize; + let key = (state >> 8) % 4; + n.retract(&m, 0, index, &mut rm, &mut ins); + m.items[index].key = key; + n.insert(&m, 0, index, &mut rm, &mut ins); + let inserted = ins.len(); + n.insert(&m, 0, index, &mut rm, &mut ins); + assert!(ins.is_empty(), "repeated insertion is a no-op"); + assert_eq!(retained_indexes(&n, &m), evaluated_indexes(&n, &m)); + assert!(inserted <= n.handles().len()); + } +} + +#[test] +fn key_churn_keeps_pairs_equal_to_full_evaluation() { + churn(node()); +} + +#[test] +fn key_churn_keeps_triples_equal_to_full_evaluation() { + churn(tri_node()); +} diff --git a/crates/solverforge-scoring/src/stream/arity_stream_macros/nary_stream/shared.rs b/crates/solverforge-scoring/src/stream/arity_stream_macros/nary_stream/shared.rs index 936f8be74..4dda0e20f 100644 --- a/crates/solverforge-scoring/src/stream/arity_stream_macros/nary_stream/shared.rs +++ b/crates/solverforge-scoring/src/stream/arity_stream_macros/nary_stream/shared.rs @@ -55,6 +55,29 @@ macro_rules! impl_nary_arity_stream_common { weight_indices = [$($weight_idx:ident),+], filter_indices = [$($filter_idx:ident),*] ) => { + impl<'x, S, A, F> crate::stream::relational::operator::FilterPredicate< + S, + [crate::stream::relational::Leaf<'x, A>; $arity], + > for super::filter::SelfJoinRowFilter + where + F: super::filter::$filter_trait A)),+>, + { + const ACCEPTS_ALL: bool = F::ACCEPTS_ALL; + + #[inline(always)] + fn accepts( + &self, + s: &S, + row: &[crate::stream::relational::Leaf<'x, A>; $arity], + ) -> bool { + self.inner().test( + s, + $(row[repeat_nary_arity_position!($entity)].entity,)+ + $(row[repeat_nary_arity_position!($filter_idx)].index),+ + ) + } + } + /// Same-collection constraint stream over tuples of `A` entities whose keys are /// equal. /// @@ -188,10 +211,9 @@ macro_rules! impl_nary_arity_stream_common { /// Groups each matching tuple, preserving upstream filters. pub fn group_by(self, key: GF, collector: Co) -> super::JoinedGroupedStream, K, KE, $arity>, - impl Fn(&S, &[crate::stream::relational::Leaf<'_, A>; $arity]) -> bool + Send + Sync>, + crate::stream::relational::operator::SelfJoinNode, K, KE, $arity, + super::filter::SelfJoinRowFilter>, impl Fn(&[crate::stream::relational::Leaf<'_, A>; $arity]) -> GK + Send + Sync, crate::stream::relational::TupleCollector, GK, V, R, Acc, Sc> where @@ -209,17 +231,6 @@ macro_rules! impl_nary_arity_stream_common { for<'i> crate::stream::relational::TupleCollector: super::collector::Collector<[crate::stream::relational::Leaf<'i, A>; $arity], Value = V, Result = R, Accumulator = Acc>, { - fn narrow_filter( - filter: F, - ) -> impl Fn(&S, &[crate::stream::relational::Leaf<'_, A>; $arity]) -> bool + Send + Sync - where - F: super::filter::$filter_trait A)),+>, - { - move |s: &S, row: &[crate::stream::relational::Leaf<'_, A>; $arity]| { - filter.test(s, $(row[repeat_nary_arity_position!($entity)].entity,)+ - $(row[repeat_nary_arity_position!($filter_idx)].index),+) - } - } fn narrow_key( key: GF, ) -> impl Fn(&[crate::stream::relational::Leaf<'_, A>; $arity]) -> GK + Send + Sync @@ -230,10 +241,11 @@ macro_rules! impl_nary_arity_stream_common { key($(row[repeat_nary_arity_position!($entity)].entity),+) } } - let input = crate::stream::relational::operator::SelfJoinNode::new( - crate::stream::relational::operator::CollectionNode::new(self.extractor, 0), self.key_extractor); - let filtered = crate::stream::relational::operator::FilterNode::new(input, - narrow_filter::(self.filter)); + let filtered = crate::stream::relational::operator::SelfJoinNode::filtered( + crate::stream::relational::operator::CollectionNode::new(self.extractor, 0), + self.key_extractor, + super::filter::SelfJoinRowFilter::new(self.filter), + ); super::JoinedGroupedStream::new(filtered, narrow_key::(key), crate::stream::relational::TupleCollector::new(collector)) } @@ -373,21 +385,14 @@ macro_rules! impl_nary_arity_stream_common { name: &str, ) -> crate::constraint::relational::OperatorTerminal< S, - crate::stream::relational::operator::FilterNode< - crate::stream::relational::operator::SelfJoinNode< - S, - A, - crate::stream::relational::operator::CollectionNode, - K, - KE, - $arity, - >, - impl for<'a, 'b> Fn( - &'a S, - &[crate::stream::relational::Leaf<'b, A>; $arity], - ) -> bool - + Send - + Sync, + crate::stream::relational::operator::SelfJoinNode< + S, + A, + crate::stream::relational::operator::CollectionNode, + K, + KE, + $arity, + super::filter::SelfJoinRowFilter, >, impl for<'a, 'b> Fn( &'a S, @@ -397,21 +402,6 @@ macro_rules! impl_nary_arity_stream_common { + Sync, Sc, > { - fn narrow_filter( - filter: F, - ) -> impl for<'a, 'b> Fn(&'a S, &[crate::stream::relational::Leaf<'b, A>; $arity]) -> bool + Send + Sync - where - F: super::filter::$filter_trait A)),+>, - { - move |s: &S, view: &[crate::stream::relational::Leaf<'_, A>; $arity]| { - let arr = view; - filter.test( - s, - $(&arr[repeat_nary_arity_position!($entity)].entity,)+ - $(arr[repeat_nary_arity_position!($filter_idx)].index),+ - ) - } - } fn narrow_weight( user_weight: W, ) -> impl for<'a, 'b> Fn(&'a S, &[crate::stream::relational::Leaf<'b, A>; $arity]) -> Sc + Send + Sync @@ -423,14 +413,10 @@ macro_rules! impl_nary_arity_stream_common { user_weight($(&arr[repeat_nary_arity_position!($entity)].entity),+) } } - let input = crate::stream::relational::operator::CollectionNode::new(self.extractor, 0); - let node = crate::stream::relational::operator::SelfJoinNode::new( - input, + let scored = crate::stream::relational::operator::SelfJoinNode::filtered( + crate::stream::relational::operator::CollectionNode::new(self.extractor, 0), self.key_extractor, - ); - let scored = crate::stream::relational::operator::FilterNode::new( - node, - narrow_filter::(self.filter), + super::filter::SelfJoinRowFilter::new(self.filter), ); let weight_fn = narrow_weight::(self.weight); crate::constraint::relational::OperatorTerminal::new( diff --git a/crates/solverforge-scoring/src/stream/balance_stream.rs b/crates/solverforge-scoring/src/stream/balance_stream.rs index 30b6da84a..e1adc6a19 100644 --- a/crates/solverforge-scoring/src/stream/balance_stream.rs +++ b/crates/solverforge-scoring/src/stream/balance_stream.rs @@ -95,7 +95,7 @@ impl BalanceConstraintStream where S: Send + Sync + 'static, A: Send + Sync + 'static, - K: Clone + Eq + Hash + Send + Sync + 'static, + K: Eq + Hash + Send + Sync + 'static, E: CollectionExtract, F: UniFilter, KF: Fn(&A) -> Option + Send + Sync, @@ -168,7 +168,7 @@ impl BalanceConstraintBuilder where S: Send + Sync + 'static, A: Send + Sync + 'static, - K: Clone + Eq + Hash + Send + Sync + 'static, + K: Eq + Hash + Send + Sync + 'static, E: CollectionExtract, F: UniFilter, KF: Fn(&A) -> Option + Send + Sync, diff --git a/crates/solverforge-scoring/src/stream/closures.rs b/crates/solverforge-scoring/src/stream/closures.rs index 7a0e7a63d..4d6c17980 100644 --- a/crates/solverforge-scoring/src/stream/closures.rs +++ b/crates/solverforge-scoring/src/stream/closures.rs @@ -10,7 +10,7 @@ use solverforge_core::score::Score; -use super::filter::{BiFilter, PentaFilter, QuadFilter, TriFilter, UniFilter}; +use super::filter::{BiFilter, QuadFilter, TriFilter, UniFilter}; use super::joiner::Joiner; use super::relational::operator::{FlattenView, Pair}; use super::relational::Leaf; @@ -271,27 +271,6 @@ where } } -/// A tri filter tested on a joined triple row. -#[allow(clippy::type_complexity)] -pub(crate) fn triple_row_filter( - filter: F, -) -> impl Fn(&S, &Pair, Leaf<'_, B>>, Leaf<'_, C>>) -> bool + Send + Sync -where - F: TriFilter, -{ - move |s: &S, row: &Pair, Leaf<'_, B>>, Leaf<'_, C>>| { - filter.test( - s, - row.left.left.entity, - row.left.right.entity, - row.right.entity, - row.left.left.index, - row.left.right.index, - row.right.index, - ) - } -} - /// `key` applied to the three entities of a joined triple row. #[allow(clippy::type_complexity)] pub(crate) fn triple_row_key( @@ -309,31 +288,6 @@ where } } -/// A quad filter tested on a joined quadruple row. -#[allow(clippy::type_complexity)] -pub(crate) fn quad_row_filter( - filter: F, -) -> impl Fn(&S, &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>) -> bool - + Send - + Sync -where - F: QuadFilter, -{ - move |s: &S, row: &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>| { - filter.test( - s, - row.left.left.left.entity, - row.left.left.right.entity, - row.left.right.entity, - row.right.entity, - row.left.left.left.index, - row.left.left.right.index, - row.left.right.index, - row.right.index, - ) - } -} - /// `key` applied to the four entities of a joined quadruple row. #[allow(clippy::type_complexity)] pub(crate) fn quad_row_key( @@ -352,40 +306,6 @@ where } } -/// A penta filter tested on a joined quintuple row. -#[allow(clippy::type_complexity)] -pub(crate) fn penta_row_filter( - filter: F, -) -> impl Fn( - &S, - &Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, Leaf<'_, E>>, -) -> bool - + Send - + Sync -where - F: PentaFilter, -{ - move |s: &S, - row: &Pair< - Pair, Leaf<'_, B>>, Leaf<'_, C>>, Leaf<'_, D>>, - Leaf<'_, E>, - >| { - filter.test( - s, - row.left.left.left.left.entity, - row.left.left.left.right.entity, - row.left.left.right.entity, - row.left.right.entity, - row.right.entity, - row.left.left.left.left.index, - row.left.left.left.right.index, - row.left.left.right.index, - row.left.right.index, - row.right.index, - ) - } -} - /// `key` applied to the five entities of a joined quintuple row. #[allow(clippy::type_complexity)] pub(crate) fn penta_row_key( diff --git a/crates/solverforge-scoring/src/stream/collector/load_balance.rs b/crates/solverforge-scoring/src/stream/collector/load_balance.rs index b35a09184..b53285ce4 100644 --- a/crates/solverforge-scoring/src/stream/collector/load_balance.rs +++ b/crates/solverforge-scoring/src/stream/collector/load_balance.rs @@ -1,10 +1,10 @@ //! LoadBalance collector for computing unfairness (sqrt of variance). -use std::collections::HashMap; use std::hash::Hash; use std::marker::PhantomData; use super::{Accumulator, Collector}; +use crate::stream::relational::KeyTable; /// Result of load balancing - tracks loads per item and computes unfairness. /// @@ -12,15 +12,30 @@ use super::{Accumulator, Collector}; /// Lower values indicate fairer distribution. Zero means perfectly balanced. #[derive(Debug, Clone)] pub struct LoadBalance { - loads: HashMap, + /// Each balanced item, stored once, with its item count and total load. + loads: KeyTable, // Unfairness as integer (use with of_soft() for scoring) unfairness: i64, } +#[derive(Debug, Clone, Copy)] +struct ItemLoad { + items: usize, + load: i64, +} + impl LoadBalance { - /// Returns map of balanced items to their total load. - pub fn loads(&self) -> &HashMap { - &self.loads + /// Returns every balanced item with its total load. + pub fn loads(&self) -> impl Iterator { + self.loads.iter().map(|(key, item)| (key, item.load)) + } + + /// Returns the total load of one balanced item. + pub fn load(&self, key: &K) -> Option + where + K: Eq + Hash, + { + self.loads.find(key).map(|id| self.loads.get(id).load) } /// Returns unfairness as i64 for use with `of_soft()`. @@ -58,7 +73,7 @@ impl LoadBalance { /// ``` pub fn load_balance(key_fn: F, metric_fn: M) -> LoadBalanceCollector where - K: Clone + Eq + Hash + Send + Sync, + K: Eq + Hash + Send + Sync, F: Send + Sync, M: Send + Sync, { @@ -79,7 +94,7 @@ pub struct LoadBalanceCollector { impl Collector for LoadBalanceCollector where Input: Copy + Send + Sync, - K: Clone + Eq + Hash + Send + Sync, + K: Eq + Hash + Send + Sync, F: Fn(Input) -> K + Send + Sync, M: Fn(Input) -> i64 + Send + Sync, { @@ -99,10 +114,8 @@ where /// Accumulator for load balance with incremental variance computation (O(1) updates). pub struct LoadBalanceAccumulator { - // Count of items per balanced key (for duplicate tracking) - item_counts: HashMap, - // Cumulative load per balanced key - loads: HashMap, + /// The live result: per-item loads and the current unfairness. + result: LoadBalance, // Sum of all loads sum: i64, // Integral part of squared deviation @@ -111,39 +124,24 @@ pub struct LoadBalanceAccumulator { squared_deviation_fraction_numerator: i64, } -impl LoadBalanceAccumulator { +impl LoadBalanceAccumulator { fn new() -> Self { Self { - item_counts: HashMap::new(), - loads: HashMap::new(), + result: LoadBalance { + loads: KeyTable::new(), + unfairness: 0, + }, sum: 0, squared_deviation_integral: 0, squared_deviation_fraction_numerator: 0, } } - fn add_to_metric(&mut self, key: &K, diff: i64) { - let old_value = *self.loads.get(key).unwrap_or(&0); - let new_value = old_value + diff; - + /// Moves one item's load from `old_value` to `new_value`. + fn change_load(&mut self, old_value: i64, new_value: i64) { if old_value != new_value { - match self.loads.get_mut(key) { - Some(slot) => *slot = new_value, - None => { - self.loads.insert(key.clone(), new_value); - } - } self.update_squared_deviation(old_value, new_value); - self.sum += diff; - } - } - - fn reset_metric(&mut self, key: &K) { - if let Some(old_value) = self.loads.remove(key) { - if old_value != 0 { - self.update_squared_deviation(old_value, 0); - self.sum -= old_value; - } + self.sum += new_value - old_value; } } @@ -172,7 +170,7 @@ impl LoadBalanceAccumulator { /// Returns unfairness as i64 (no pre-scaling). /// Use with `of_soft()` which handles the decimal scaling. fn compute_unfairness(&self) -> i64 { - let n = self.item_counts.len(); + let n = self.result.loads.len(); match n { 0 => 0, 1 => { @@ -191,57 +189,59 @@ impl LoadBalanceAccumulator { } } -impl Accumulator<(K, i64), LoadBalance> +impl Accumulator<(K, i64), LoadBalance> for LoadBalanceAccumulator { - type Retraction = (K, i64); + /// The item's slot and the metric it added; `None` for a zero metric, + /// which contributes nothing. + type Retraction = Option<(u32, i64)>; #[inline] fn accumulate(&mut self, value: (K, i64)) -> Self::Retraction { let (key, metric) = value; if metric == 0 { - return (key, metric); // Skip zero-metric entries (e.g., unassigned shifts) - } - match self.item_counts.get_mut(&key) { - Some(count) => *count += 1, - None => { - self.item_counts.insert(key.clone(), 1); - } + return None; // Skip zero-metric entries (e.g., unassigned shifts) } - self.add_to_metric(&key, metric); - (key, metric) + let id = self + .result + .loads + .find_or_insert(key, || ItemLoad { items: 0, load: 0 }); + let item = self.result.loads.get_mut(id); + item.items += 1; + let old_value = item.load; + item.load += metric; + let new_value = item.load; + self.change_load(old_value, new_value); + self.result.unfairness = self.compute_unfairness(); + Some((id, metric)) } #[inline] fn retract(&mut self, value: Self::Retraction) { - let (key, metric) = value; - if metric == 0 { + let Some((id, metric)) = value else { return; // Skip zero-metric entries + }; + let item = self.result.loads.get_mut(id); + item.items -= 1; + let old_value = item.load; + if item.items == 0 { + self.result.loads.remove(id); + self.change_load(old_value, 0); + } else { + item.load -= metric; + let new_value = item.load; + self.change_load(old_value, new_value); } - if let Some(count) = self.item_counts.get_mut(&key) { - if *count > 0 { - *count -= 1; - if *count == 0 { - self.item_counts.remove(&key); - self.reset_metric(&key); - } else { - self.add_to_metric(&key, -metric); - } - } - } + self.result.unfairness = self.compute_unfairness(); } fn with_result(&self, f: impl FnOnce(&LoadBalance) -> T) -> T { - let result = LoadBalance { - loads: self.loads.clone(), - unfairness: self.compute_unfairness(), - }; - f(&result) + f(&self.result) } fn reset(&mut self) { - self.item_counts.clear(); - self.loads.clear(); + self.result.loads.clear(); + self.result.unfairness = 0; self.sum = 0; self.squared_deviation_integral = 0; self.squared_deviation_fraction_numerator = 0; diff --git a/crates/solverforge-scoring/src/stream/collector/tests/collector.rs b/crates/solverforge-scoring/src/stream/collector/tests/collector.rs index a9c5a4695..602f6b96a 100644 --- a/crates/solverforge-scoring/src/stream/collector/tests/collector.rs +++ b/crates/solverforge-scoring/src/stream/collector/tests/collector.rs @@ -176,11 +176,11 @@ fn test_retract() { let mut acc = collector.create_accumulator(); acc.accumulate(collector.extract(&0)); - acc.accumulate(collector.extract(&0)); + let zero = acc.accumulate(collector.extract(&0)); acc.accumulate(collector.extract(&1)); // Remove one from item 0 -> now balanced - acc.retract(collector.extract(&0)); + acc.retract(zero); let result = acc.finish(); assert_eq!(result.unfairness(), 0); @@ -206,7 +206,8 @@ fn test_single_item() { let result = acc.finish(); // Single item always has 0 variance from mean (it IS the mean) - assert_eq!(result.loads().get(&0), Some(&3)); + assert_eq!(result.load(&0), Some(3)); + assert_eq!(result.loads().collect::>(), vec![(&0, 3)]); } // Baseline load balance test: checks incremental add/retract correctness. @@ -229,7 +230,7 @@ fn test_load_balance_standard_deviation() { value: "A", metric: 2, }; - acc.accumulate(collector.extract(&a)); + let a_token = acc.accumulate(collector.extract(&a)); assert_eq!(acc.finish().unfairness(), 0); // Single item // Add B with metric 1 -> A=2, B=1 @@ -237,24 +238,24 @@ fn test_load_balance_standard_deviation() { value: "B", metric: 1, }; - acc.accumulate(collector.extract(&b)); + let b_first = acc.accumulate(collector.extract(&b)); // sqrt((2-1.5)^2 + (1-1.5)^2) = sqrt(0.5) ~ 0.707 -> rounds to 1 assert_eq!(acc.finish().unfairness(), 1); // Add another B -> A=2, B=2 -> perfectly balanced - acc.accumulate(collector.extract(&b)); + let b_second = acc.accumulate(collector.extract(&b)); assert_eq!(acc.finish().unfairness(), 0); // Retract B -> A=2, B=1 again - acc.retract(collector.extract(&b)); + acc.retract(b_second); assert_eq!(acc.finish().unfairness(), 1); // Retract B completely -> only A left - acc.retract(collector.extract(&b)); + acc.retract(b_first); assert_eq!(acc.finish().unfairness(), 0); // Retract A -> empty - acc.retract(collector.extract(&a)); + acc.retract(a_token); assert_eq!(acc.finish().unfairness(), 0); } diff --git a/crates/solverforge-scoring/src/stream/complemented_stream.rs b/crates/solverforge-scoring/src/stream/complemented_stream.rs index aad69d4cf..0910ac750 100644 --- a/crates/solverforge-scoring/src/stream/complemented_stream.rs +++ b/crates/solverforge-scoring/src/stream/complemented_stream.rs @@ -14,7 +14,7 @@ use super::collector::{Accumulator, Collector}; use super::filter::UniFilter; use super::relational::leaf_collector::{leaf_key, LeafCollector, LeafFilter, OptionalEntityKey}; use super::relational::operator::{CollectionNode, ComplementNode, FilterNode, GroupNode}; -use super::relational::view_plan::{GroupKey, ViewEqualPlan}; +use super::relational::view_plan::{GroupEqualPlan, GroupRight}; use super::relational::Leaf; use super::weighting_support::ConstraintWeight; use crate::constraint::relational::{ @@ -349,7 +349,7 @@ where V, R, >, - ViewEqualPlan, OptionalEntityKey, GroupKey>, + GroupEqualPlan, OptionalEntityKey, GroupRight>, impl for<'l> Fn(&S, &Leaf<'l, B>) -> R + Send + Sync, R, >, @@ -372,7 +372,7 @@ where let tree = ComplementNode::new( targets, group, - ViewEqualPlan::new(OptionalEntityKey::new(key_b.clone()), GroupKey), + GroupEqualPlan::new(OptionalEntityKey::new(key_b.clone())), crate::stream::closures::leaf_default::(default_fn), ); SharedOperatorBuilder::first_with_hard( diff --git a/crates/solverforge-scoring/src/stream/cross_bi_stream/complemented_grouped.rs b/crates/solverforge-scoring/src/stream/cross_bi_stream/complemented_grouped.rs index c68bca064..212baaaec 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/complemented_grouped.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/complemented_grouped.rs @@ -14,14 +14,19 @@ use crate::stream::filter::BiFilter; use crate::stream::relational::operator::{ CollectionNode, ComplementNode, GroupNode, JoinNode, Pair, }; -use crate::stream::relational::view_plan::{EntityKey, GroupKey, ViewEqualPlan}; +use crate::stream::relational::view_plan::{EntityKey, GroupEqualPlan, GroupRight}; use crate::stream::relational::{Leaf, TupleCollector}; use crate::stream::weighting_support::ConstraintWeight; -use super::scored::{BiScored, BiUnaryPlan}; +use super::scored::{BiRowFilter, BiUnaryPlan}; -type BiInput = - BiScored, F>; +type BiInput = JoinNode< + S, + CollectionNode, + CollectionNode, + BiUnaryPlan, + BiRowFilter, +>; /// Grouped cross-join stream complemented with target entities `T`. /// @@ -360,7 +365,7 @@ where V, R, >, - ViewEqualPlan, GroupKey>, + GroupEqualPlan, GroupRight>, impl Fn(&S, &Leaf<'_, T>) -> R + Send + Sync, R, >, @@ -368,13 +373,11 @@ where OperatorScorer, Sc>, Sc, > { - let input = BiScored::new( - JoinNode::new( - CollectionNode::new(self.extractor_a, 0), - CollectionNode::new(self.extractor_b, 1), - BiUnaryPlan::new(self.key_a, self.key_b), - ), - self.filter, + let input = JoinNode::filtered( + CollectionNode::new(self.extractor_a, 0), + CollectionNode::new(self.extractor_b, 1), + BiUnaryPlan::new(self.key_a, self.key_b), + BiRowFilter::new(self.filter), ); let group_key = self.group_key_fn; let group = GroupNode::new( @@ -387,7 +390,7 @@ where let tree = ComplementNode::new( CollectionNode::new(self.extractor_t, 2), group, - ViewEqualPlan::new(EntityKey::new(key_t.clone()), GroupKey), + GroupEqualPlan::new(EntityKey::new(key_t.clone())), crate::stream::closures::leaf_default::(default_fn), ); SharedOperatorBuilder::first_with_hard( diff --git a/crates/solverforge-scoring/src/stream/cross_bi_stream/grouped.rs b/crates/solverforge-scoring/src/stream/cross_bi_stream/grouped.rs index b268e8f97..22f44051c 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/grouped.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/grouped.rs @@ -15,10 +15,15 @@ use crate::stream::relational::{Leaf, TupleCollector}; use crate::stream::weighting_support::ConstraintWeight; use super::complemented_grouped::ComplementedGrouped; -use super::scored::{BiScored, BiUnaryPlan}; +use super::scored::{BiRowFilter, BiUnaryPlan}; -type BiInput = - BiScored, F>; +type BiInput = JoinNode< + S, + CollectionNode, + CollectionNode, + BiUnaryPlan, + BiRowFilter, +>; /// Keyed cross join whose pairs are grouped by a key `GK` and aggregated by a /// collector. @@ -274,13 +279,11 @@ where OperatorScorer, Sc>, Sc, > { - let input = BiScored::new( - JoinNode::new( - CollectionNode::new(self.extractor_a, 0), - CollectionNode::new(self.extractor_b, 1), - BiUnaryPlan::new(self.key_a, self.key_b), - ), - self.filter, + let input = JoinNode::filtered( + CollectionNode::new(self.extractor_a, 0), + CollectionNode::new(self.extractor_b, 1), + BiUnaryPlan::new(self.key_a, self.key_b), + BiRowFilter::new(self.filter), ); let group_key = self.group_key_fn; let tree = GroupNode::new( diff --git a/crates/solverforge-scoring/src/stream/cross_bi_stream/scored.rs b/crates/solverforge-scoring/src/stream/cross_bi_stream/scored.rs index 40b81a940..90bce9c7e 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/scored.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/scored.rs @@ -11,15 +11,12 @@ use std::borrow::Cow; use std::hash::Hash; use std::marker::PhantomData; -use super::super::collection_extract::CollectionExtract; use super::super::filter::BiFilter; use super::super::joiner::plan::{CompileCondition, EqualityKind, ExecutablePlan, IndexedPlan}; use super::super::joiner::Joiner; use super::super::relational::index::HashIndex; -use super::super::relational::operator::{CollectionNode, JoinNode, Operator, Pair}; -use super::super::relational::{HandleMap, Leaf, RowHandle}; -use crate::api::analysis::EntityRef; -use crate::stream::relational::operator::{ExplainOperator, RowOrigin}; +use super::super::relational::operator::{FilterPredicate, Pair}; +use super::super::relational::{Leaf, RowHandle}; /// The predicate first-join plan: an explicit opposite-input scan. /// @@ -180,259 +177,37 @@ where } } -/// Borrowed (A, B) entity pair off a bi row view. -pub(super) trait BiEntities<'a, A, B> { - fn entities(&self) -> (&'a A, &'a B); - fn indexes(&self) -> (usize, usize); -} - -impl<'a, A, B> BiEntities<'a, A, B> for Pair, Leaf<'a, B>> { - #[inline] - fn entities(&self) -> (&'a A, &'a B) { - (self.left.entity, self.right.entity) - } - #[inline] - fn indexes(&self) -> (usize, usize) { - (self.left.index, self.right.index) - } -} - -/// Scored bi operator: the join tree plus the authored filter as one row producer. -/// -/// The terminal's weight closure receives filtered rows only. Filters never run -/// twice: stateless evaluation applies them here, and retained mutations publish -/// post-filter deltas through the same predicate. -pub struct BiScored -where - P: IndexedPlan, - JoinNode, CollectionNode, P>: Operator, -{ - inner: JoinNode, CollectionNode, P>, +/// The authored bi filter as a join's row filter: it runs when the join finds +/// a pair, so a rejected pair is never retained, and evaluate, match_count, +/// initialize, and mutations all honor it exactly once. +pub struct BiRowFilter { filter: F, - accepted: HandleMap<()>, - /// Child notification scratch, reused across events. - child_removed: Vec, - child_inserted: Vec, marker: PhantomData (A, B)>, } -impl BiScored -where - P: IndexedPlan, - JoinNode, CollectionNode, P>: Operator, -{ - pub(super) fn new( - inner: JoinNode, CollectionNode, P>, - filter: F, - ) -> Self { +impl BiRowFilter { + pub(super) fn new(filter: F) -> Self { Self { - inner, filter, - accepted: HandleMap::new(), - child_removed: Vec::new(), - child_inserted: Vec::new(), marker: PhantomData, } } } -impl Operator for BiScored +impl<'x, S, A, B, F> FilterPredicate, Leaf<'x, B>>> for BiRowFilter where - S: Send + Sync + 'static, - A: Send + Sync + 'static, - B: Send + Sync + 'static, - P: IndexedPlan + 'static, - EA: CollectionExtract, - EB: CollectionExtract, - for<'a> P: ExecutablePlan, Leaf<'a, B>>, - for<'a> JoinNode, CollectionNode, P>: - Operator = Pair, Leaf<'a, B>>>, - F: BiFilter + 'static, + F: BiFilter, { - type View<'a> = Pair, Leaf<'a, B>>; - type Evaluation = - , CollectionNode, P> as Operator>::Evaluation; - - #[inline] - fn prepare_evaluation(&self, solution: &S) -> Self::Evaluation { - self.inner.prepare_evaluation(solution) - } - - #[inline] - fn visit_evaluation<'a>( - &'a self, - solution: &'a S, - evaluation: &'a Self::Evaluation, - visitor: &mut impl FnMut(Self::View<'a>), - ) { - self.inner - .visit_evaluation(solution, evaluation, &mut |row| { - let (a, b) = row.entities(); - let (ai, bi) = row.indexes(); - if self.filter.test(solution, a, b, ai, bi) { - visitor(row); - } - }); - } - - fn clear(&mut self) { - self.inner.clear(); - self.accepted.clear(); - self.child_removed.clear(); - self.child_inserted.clear(); - } - - #[inline(always)] - fn initialize(&mut self, solution: &S) { - self.inner.initialize(solution); - self.accepted.clear(); - self.child_removed.clear(); - self.child_inserted.clear(); - for handle in self.inner.handles() { - let row = self.inner.resolve(solution, handle).expect("live bi row"); - if self.test(solution, row) { - self.accepted.insert(handle, ()); - } - } - } - - fn handles(&self) -> Vec { - self.inner - .handles() - .into_iter() - .filter(|h| self.accepted.get(*h).is_some()) - .collect() - } - - fn resolve<'a>(&'a self, solution: &'a S, handle: RowHandle) -> Option> { - self.accepted.get(handle)?; - self.inner.resolve(solution, handle) - } - - fn visit_provenance(&self, handle: RowHandle, visitor: &mut impl FnMut(u32, usize, usize)) { - if self.accepted.get(handle).is_some() { - self.inner.visit_provenance(handle, visitor); - } - } + const ACCEPTS_ALL: bool = F::ACCEPTS_ALL; #[inline(always)] - fn retract( - &mut self, - solution: &S, - descriptor: usize, - index: usize, - removed: &mut Vec, - _inserted: &mut Vec, - ) { - removed.clear(); - let inner_removed = std::mem::take(&mut self.child_removed); - let inner_inserted = std::mem::take(&mut self.child_inserted); - let mut inner_removed = inner_removed; - let mut inner_inserted = inner_inserted; - inner_removed.clear(); - inner_inserted.clear(); - self.inner.retract( + fn accepts(&self, solution: &S, row: &Pair, Leaf<'x, B>>) -> bool { + self.filter.test( solution, - descriptor, - index, - &mut inner_removed, - &mut inner_inserted, - ); - for h in inner_removed.drain(..) { - if self.accepted.remove(h).is_some() { - removed.push(h); - } - } - self.child_removed = inner_removed; - self.child_inserted = inner_inserted; - } - - #[inline(always)] - fn insert( - &mut self, - solution: &S, - descriptor: usize, - index: usize, - _removed: &mut Vec, - inserted: &mut Vec, - ) { - let mut inner_removed = std::mem::take(&mut self.child_removed); - let mut inner_inserted = std::mem::take(&mut self.child_inserted); - inner_removed.clear(); - inner_inserted.clear(); - self.inner.insert( - solution, - descriptor, - index, - &mut inner_removed, - &mut inner_inserted, - ); - for handle in inner_inserted.drain(..) { - let row = self - .inner - .resolve(solution, handle) - .expect("live scored row"); - if self.test(solution, row) { - self.accepted.insert(handle, ()); - inserted.push(handle); - } - } - self.child_removed = inner_removed; - self.child_inserted = inner_inserted; - } -} - -impl BiScored -where - S: Send + Sync + 'static, - A: Send + Sync + 'static, - B: Send + Sync + 'static, - P: IndexedPlan, - F: BiFilter, - JoinNode, CollectionNode, P>: Operator, -{ - #[inline] - fn test<'a>(&self, solution: &S, row: Pair, Leaf<'a, B>>) -> bool - where - A: 'a, - B: 'a, - { - let (a, b) = row.entities(); - let (ai, bi) = row.indexes(); - self.filter.test(solution, a, b, ai, bi) - } -} - -impl std::fmt::Debug for BiScored -where - P: IndexedPlan, - JoinNode, CollectionNode, P>: Operator, -{ - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("BiScored").finish() - } -} - -impl ExplainOperator for BiScored -where - S: Send + Sync + 'static, - A: Send + Sync + 'static, - B: Send + Sync + 'static, - P: IndexedPlan + 'static, - EA: CollectionExtract, - EB: CollectionExtract, - for<'a> P: ExecutablePlan, Leaf<'a, B>>, - for<'a> JoinNode, CollectionNode, P>: - ExplainOperator = Pair, Leaf<'a, B>>>, - F: BiFilter + 'static, -{ - fn explain( - &self, - solution: &S, - row: &Self::View<'_>, - origin: RowOrigin<'_, Self::Evaluation>, - entities: &mut Vec, - ) { - self.inner.explain(solution, row, origin, entities); + row.left.entity, + row.right.entity, + row.left.index, + row.right.index, + ) } } diff --git a/crates/solverforge-scoring/src/stream/cross_bi_stream/view_comparison.rs b/crates/solverforge-scoring/src/stream/cross_bi_stream/view_comparison.rs index b4e0c0a2e..990e5f49f 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/view_comparison.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/view_comparison.rs @@ -45,7 +45,7 @@ impl CompileCondition } } -impl IndexedPlan +impl IndexedPlan for ViewComparisonPlan where KA: Send + Sync, @@ -91,7 +91,7 @@ where impl<'x, A, B, K, KA, KB, const LESS: bool, const INCLUSIVE: bool> ExecutablePlan, Leaf<'x, B>> for ViewComparisonPlan where - K: Ord + Clone, + K: Ord, KA: Fn(&A) -> K + Send + Sync, KB: Fn(&B) -> K + Send + Sync, { @@ -158,7 +158,7 @@ impl CompileCondition for ViewOverlapPlan } } -impl IndexedPlan for ViewOverlapPlan +impl IndexedPlan for ViewOverlapPlan where SA: Send + Sync, EA: Send + Sync, @@ -199,7 +199,7 @@ where impl<'x, A, B, K, SA, EA, SB, EB> ExecutablePlan, Leaf<'x, B>> for ViewOverlapPlan where - K: Ord + Clone, + K: Ord, SA: Fn(&A) -> K + Send + Sync, EA: Fn(&A) -> K + Send + Sync, SB: Fn(&B) -> K + Send + Sync, diff --git a/crates/solverforge-scoring/src/stream/cross_bi_stream/weighting.rs b/crates/solverforge-scoring/src/stream/cross_bi_stream/weighting.rs index 50e1e9208..cd25b9e6c 100644 --- a/crates/solverforge-scoring/src/stream/cross_bi_stream/weighting.rs +++ b/crates/solverforge-scoring/src/stream/cross_bi_stream/weighting.rs @@ -10,7 +10,7 @@ use super::super::relational::operator::{CollectionNode, JoinNode, Operator, Pai use super::super::relational::Leaf; use super::super::weighting_support::ConstraintWeight; use super::base::Bi; -use super::scored::BiScored; +use super::scored::BiRowFilter; use crate::constraint::relational::OperatorTerminal; impl Bi @@ -128,7 +128,7 @@ where name: &str, ) -> OperatorTerminal< S, - BiScored, + JoinNode, CollectionNode, P::Plan, BiRowFilter>, impl Fn(&S, &Pair, Leaf<'_, B>>) -> Sc + Send + Sync, Sc, > @@ -136,12 +136,12 @@ where for<'a> JoinNode, CollectionNode, P::Plan>: Operator = Pair, Leaf<'a, B>>>, { - let tree = JoinNode::new( + let scored = JoinNode::filtered( CollectionNode::new(self.extractor_a, 1), CollectionNode::new(self.extractor_b, 0), self.plan, + BiRowFilter::new(self.filter), ); - let scored = BiScored::new(tree, self.filter); let weight = self.weight; let weight_fn = crate::stream::closures::pair_row_weight::(weight); OperatorTerminal::new( diff --git a/crates/solverforge-scoring/src/stream/cross_penta_stream.rs b/crates/solverforge-scoring/src/stream/cross_penta_stream.rs index da3e1ae1d..5cdb57c10 100644 --- a/crates/solverforge-scoring/src/stream/cross_penta_stream.rs +++ b/crates/solverforge-scoring/src/stream/cross_penta_stream.rs @@ -1,5 +1,5 @@ mod scored; -pub(super) use scored::PentaScored; +pub(crate) use scored::{PentaRowFilter, PentaScored}; /* Canonical five-source fluent join: one operator tree, no per-arity engine. @@ -18,7 +18,7 @@ use solverforge_core::{ConstraintRef, ImpactType}; use super::filter::{AndPentaFilter, FnPentaFilter, PentaFilter}; use super::joiner::plan::{CompileCondition, IndexedPlan}; use super::relational::operator::{CollectionNode, ExplainOperator, JoinNode, Operator, Pair}; -use super::relational::{HandleMap, Leaf, RowHandle}; +use super::relational::Leaf; use super::weighting_support::ConstraintWeight; use crate::constraint::relational::OperatorTerminal; @@ -50,37 +50,6 @@ pub(super) type BuiltPenta = JoinNode< pub(super) type PentaRow<'a, S, EA, EB, EC, ED, EE, P1, P2, P3, P4> = as Operator>::View<'a>; -/// Borrowed (A, B, C, D, E) entity quintuple off a penta row view. -pub(super) trait PentaEntities<'a, A, B, C, D, E> { - fn entities(&self) -> (&'a A, &'a B, &'a C, &'a D, &'a E); - fn indexes(&self) -> (usize, usize, usize, usize, usize); -} - -impl<'a, A, B, C, D, E> PentaEntities<'a, A, B, C, D, E> - for Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, Leaf<'a, E>> -{ - #[inline] - fn entities(&self) -> (&'a A, &'a B, &'a C, &'a D, &'a E) { - ( - self.left.left.left.left.entity, - self.left.left.left.right.entity, - self.left.left.right.entity, - self.left.right.entity, - self.right.entity, - ) - } - #[inline] - fn indexes(&self) -> (usize, usize, usize, usize, usize) { - ( - self.left.left.left.left.index, - self.left.left.left.right.index, - self.left.left.right.index, - self.left.right.index, - self.right.index, - ) - } -} - /// Five-collection join stream: the tri join extended with `D` through `P3` and /// then `E` through `P4`, each step compiled into its own plan over the row /// before it. @@ -341,8 +310,19 @@ where CollectionNode, ::Plan, >: Operator, + for<'a> PentaScored: Operator< + S, + View<'a> = Pair< + Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, + Leaf<'a, E>, + >, + >, + PentaScored: Send + Sync, { - let chain = super::chain_stream::Chain::new(PentaScored::new(self.tree, self.filter), 5); + let chain = super::chain_stream::Chain::new( + self.tree.with_filter(PentaRowFilter::new(self.filter)), + 5, + ); chain.join(target) } } @@ -411,7 +391,7 @@ where let weight = self.weight; let is_hard = self.is_hard; let constraint_ref = ConstraintRef::new("", name); - let scored = PentaScored::new(self.tree, self.filter); + let scored = self.tree.with_filter(PentaRowFilter::new(self.filter)); let weight_fn = crate::stream::closures::penta_row_weight::(weight); OperatorTerminal::new(constraint_ref, self.impact_type, scored, weight_fn, is_hard) diff --git a/crates/solverforge-scoring/src/stream/cross_penta_stream/scored.rs b/crates/solverforge-scoring/src/stream/cross_penta_stream/scored.rs index 5e8f61c07..5f978856e 100644 --- a/crates/solverforge-scoring/src/stream/cross_penta_stream/scored.rs +++ b/crates/solverforge-scoring/src/stream/cross_penta_stream/scored.rs @@ -1,320 +1,79 @@ use super::*; -use crate::api::analysis::EntityRef; -use crate::stream::relational::operator::{ExplainOperator, RowOrigin}; +use crate::stream::relational::operator::FilterPredicate; -/// Scored penta operator: the tree plus the authored filter as one row producer. -pub struct PentaScored< - S, - A, - B, - C, - D, - E, - EA, - EB, - EC, - ED, - EE, - P1: CompileCondition, - P2: CompileCondition, - P3: CompileCondition, - P4: CompileCondition, - F, -> where - BuiltPenta: Operator, - F: PentaFilter, -{ - inner: BuiltPenta, +/// The authored penta filter as the top join's row filter: it runs when the +/// join finds a row, so a rejected row is never retained, and evaluate, +/// match_count, initialize, and mutations all honor it exactly once. +pub struct PentaRowFilter { filter: F, - accepted: HandleMap<()>, - /// Child notification scratch, reused across events. - child_removed: Vec, - child_inserted: Vec, - marker: PhantomData (S, A, B, C, D, E)>, + marker: PhantomData (A, B, C, D, E)>, } -impl - PentaScored -where - P1: CompileCondition, - P2: CompileCondition, - P3: CompileCondition, - P4: CompileCondition, - BuiltPenta: Operator, - F: PentaFilter, -{ - /// The penta tree with its authored filter applied at this boundary, - /// whether the stream is scored here or continues into a `Chain`. - pub(super) fn new(inner: BuiltPenta, filter: F) -> Self { +impl PentaRowFilter { + pub(crate) fn new(filter: F) -> Self { Self { - inner, filter, - accepted: HandleMap::new(), - child_removed: Vec::new(), - child_inserted: Vec::new(), marker: PhantomData, } } } -impl Operator - for PentaScored -where - S: Send + Sync + 'static, - A: Send + Sync + 'static, - B: Send + Sync + 'static, - C: Send + Sync + 'static, - D: Send + Sync + 'static, - E: Send + Sync + 'static, - P1: CompileCondition + 'static, - P2: CompileCondition + 'static, - P3: CompileCondition + 'static, - P4: CompileCondition + 'static, - for<'a> BuiltPenta: Operator< +impl<'x, S, A, B, C, D, E, F> + FilterPredicate< S, - View<'a> = Pair< - Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, - Leaf<'a, E>, - >, - >, - F: PentaFilter + 'static, -{ - type View<'a> = PentaRow<'a, S, EA, EB, EC, ED, EE, P1, P2, P3, P4>; - type Evaluation = - as Operator>::Evaluation; - - #[inline] - fn prepare_evaluation(&self, solution: &S) -> Self::Evaluation { - self.inner.prepare_evaluation(solution) - } - - #[inline] - fn visit_evaluation<'a>( - &'a self, - solution: &'a S, - evaluation: &'a Self::Evaluation, - visitor: &mut impl FnMut(Self::View<'a>), - ) { - if F::ACCEPTS_ALL { - self.inner.visit_evaluation(solution, evaluation, visitor); - return; - } - self.inner - .visit_evaluation(solution, evaluation, &mut |row| { - let (a, b, c, d, e) = row.entities(); - let (ai, bi, ci, di, ei) = row.indexes(); - if self - .filter - .test(solution, a, b, c, d, e, ai, bi, ci, di, ei) - { - visitor(row); - } - }); - } - - fn clear(&mut self) { - self.inner.clear(); - self.accepted.clear(); - self.child_removed.clear(); - self.child_inserted.clear(); - } - - #[inline(always)] - fn initialize(&mut self, solution: &S) { - self.inner.initialize(solution); - self.accepted.clear(); - self.child_removed.clear(); - self.child_inserted.clear(); - if F::ACCEPTS_ALL { - return; - } - for handle in self.inner.handles() { - let row = self - .inner - .resolve(solution, handle) - .expect("live penta row"); - if self.test(solution, row) { - self.accepted.insert(handle, ()); - } - } - } - - fn handles(&self) -> Vec { - if F::ACCEPTS_ALL { - return self.inner.handles(); - } - self.inner - .handles() - .into_iter() - .filter(|h| self.accepted.get(*h).is_some()) - .collect() - } - - #[inline] - fn resolve<'a>(&'a self, solution: &'a S, handle: RowHandle) -> Option> { - if !F::ACCEPTS_ALL { - self.accepted.get(handle)?; - } - self.inner.resolve(solution, handle) - } - - fn visit_provenance(&self, handle: RowHandle, visitor: &mut impl FnMut(u32, usize, usize)) { - if F::ACCEPTS_ALL || self.accepted.get(handle).is_some() { - self.inner.visit_provenance(handle, visitor); - } - } - - #[inline(always)] - fn retract( - &mut self, - solution: &S, - descriptor: usize, - index: usize, - removed: &mut Vec, - _inserted: &mut Vec, - ) { - removed.clear(); - if F::ACCEPTS_ALL { - self.inner.retract( - solution, - descriptor, - index, - removed, - &mut self.child_inserted, - ); - return; - } - let inner_removed = std::mem::take(&mut self.child_removed); - let inner_inserted = std::mem::take(&mut self.child_inserted); - let mut inner_removed = inner_removed; - let mut inner_inserted = inner_inserted; - inner_removed.clear(); - inner_inserted.clear(); - self.inner.retract( - solution, - descriptor, - index, - &mut inner_removed, - &mut inner_inserted, - ); - for h in inner_removed.drain(..) { - if self.accepted.remove(h).is_some() { - removed.push(h); - } - } - self.child_removed = inner_removed; - self.child_inserted = inner_inserted; - } - - #[inline(always)] - fn insert( - &mut self, - solution: &S, - descriptor: usize, - index: usize, - _removed: &mut Vec, - inserted: &mut Vec, - ) { - if F::ACCEPTS_ALL { - inserted.clear(); - self.inner.insert( - solution, - descriptor, - index, - &mut self.child_removed, - inserted, - ); - return; - } - let mut inner_removed = std::mem::take(&mut self.child_removed); - let mut inner_inserted = std::mem::take(&mut self.child_inserted); - inner_removed.clear(); - inner_inserted.clear(); - self.inner.insert( - solution, - descriptor, - index, - &mut inner_removed, - &mut inner_inserted, - ); - for handle in inner_inserted.drain(..) { - let row = self - .inner - .resolve(solution, handle) - .expect("live scored row"); - if self.test(solution, row) { - self.accepted.insert(handle, ()); - inserted.push(handle); - } - } - self.child_removed = inner_removed; - self.child_inserted = inner_inserted; - } -} - -impl - PentaScored + Pair, Leaf<'x, B>>, Leaf<'x, C>>, Leaf<'x, D>>, Leaf<'x, E>>, + > for PentaRowFilter where - S: Send + Sync + 'static, - P1: CompileCondition, - P2: CompileCondition, - P3: CompileCondition, - P4: CompileCondition, - BuiltPenta: Operator, F: PentaFilter, { - #[inline] - #[allow(clippy::too_many_arguments)] - fn test<'a>( + const ACCEPTS_ALL: bool = F::ACCEPTS_ALL; + + #[inline(always)] + fn accepts( &self, solution: &S, - row: as Operator>::View<'a>, - ) -> bool - where - A: 'a, - B: 'a, - C: 'a, - D: 'a, - E: 'a, - as Operator>::View<'a>: - PentaEntities<'a, A, B, C, D, E>, - { - let (a, b, c, d, e) = row.entities(); - let (ai, bi, ci, di, ei) = row.indexes(); - self.filter - .test(solution, a, b, c, d, e, ai, bi, ci, di, ei) + row: &Pair< + Pair, Leaf<'x, B>>, Leaf<'x, C>>, Leaf<'x, D>>, + Leaf<'x, E>, + >, + ) -> bool { + self.filter.test( + solution, + row.left.left.left.left.entity, + row.left.left.left.right.entity, + row.left.left.right.entity, + row.left.right.entity, + row.right.entity, + row.left.left.left.left.index, + row.left.left.left.right.index, + row.left.left.right.index, + row.left.right.index, + row.right.index, + ) } } -impl ExplainOperator - for PentaScored -where - S: Send + Sync + 'static, - A: Send + Sync + 'static, - B: Send + Sync + 'static, - C: Send + Sync + 'static, - D: Send + Sync + 'static, - E: Send + Sync + 'static, - P1: CompileCondition + 'static, - P2: CompileCondition + 'static, - P3: CompileCondition + 'static, - P4: CompileCondition + 'static, - for<'a> BuiltPenta: ExplainOperator< +/// The scored penta tree: its top join retains only the rows the authored +/// filter accepts. +pub(crate) type PentaScored = JoinNode< + S, + JoinNode< S, - View<'a> = Pair< - Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, - Leaf<'a, E>, + JoinNode< + S, + JoinNode< + S, + CollectionNode, + CollectionNode, + ::Plan, + >, + CollectionNode, + ::Plan, >, + CollectionNode, + ::Plan, >, - F: PentaFilter + 'static, -{ - fn explain( - &self, - solution: &S, - row: &Self::View<'_>, - origin: RowOrigin<'_, Self::Evaluation>, - entities: &mut Vec, - ) { - self.inner.explain(solution, row, origin, entities); - } -} + CollectionNode, + ::Plan, + PentaRowFilter, +>; diff --git a/crates/solverforge-scoring/src/stream/cross_quad_stream.rs b/crates/solverforge-scoring/src/stream/cross_quad_stream.rs index 2420823a9..41cca6457 100644 --- a/crates/solverforge-scoring/src/stream/cross_quad_stream.rs +++ b/crates/solverforge-scoring/src/stream/cross_quad_stream.rs @@ -1,5 +1,5 @@ mod scored; -pub(crate) use scored::QuadScored; +pub(crate) use scored::{QuadRowFilter, QuadScored}; /* Canonical four-source fluent join: one operator tree, no per-arity engine. @@ -18,7 +18,7 @@ use solverforge_core::{ConstraintRef, ImpactType}; use super::filter::{AndQuadFilter, FnQuadFilter, QuadAsPentaFilter, QuadFilter}; use super::joiner::plan::{CompileCondition, IndexedPlan}; use super::relational::operator::{CollectionNode, ExplainOperator, JoinNode, Operator, Pair}; -use super::relational::{HandleMap, Leaf, RowHandle}; +use super::relational::Leaf; use super::weighting_support::ConstraintWeight; use crate::constraint::relational::OperatorTerminal; @@ -39,35 +39,6 @@ pub(crate) type BuiltQuad = JoinNode< pub(crate) type QuadRow<'a, S, EA, EB, EC, ED, P1, P2, P3> = as Operator>::View<'a>; -/// Borrowed (A, B, C, D) entity quadruple off a quad row view. -pub(crate) trait QuadEntities<'a, A, B, C, D> { - fn entities(&self) -> (&'a A, &'a B, &'a C, &'a D); - fn indexes(&self) -> (usize, usize, usize, usize); -} - -impl<'a, A, B, C, D> QuadEntities<'a, A, B, C, D> - for Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>> -{ - #[inline] - fn entities(&self) -> (&'a A, &'a B, &'a C, &'a D) { - ( - self.left.left.left.entity, - self.left.left.right.entity, - self.left.right.entity, - self.right.entity, - ) - } - #[inline] - fn indexes(&self) -> (usize, usize, usize, usize) { - ( - self.left.left.left.index, - self.left.left.right.index, - self.left.right.index, - self.right.index, - ) - } -} - /// Four-collection join stream: `((A ⋈ B) ⋈ C) ⋈ D`, each relationship /// compiled from its own joiner (`P1`, `P2`, `P3`), so each left key reads the /// whole row joined so far. @@ -355,14 +326,7 @@ where let weight = self.weight; let is_hard = self.is_hard; let constraint_ref = ConstraintRef::new("", name); - let scored = QuadScored { - inner: self.tree, - filter: self.filter, - accepted: HandleMap::new(), - child_removed: Vec::new(), - child_inserted: Vec::new(), - marker: PhantomData, - }; + let scored = self.tree.with_filter(QuadRowFilter::new(self.filter)); let weight_fn = crate::stream::closures::quad_row_weight::(weight); OperatorTerminal::new(constraint_ref, self.impact_type, scored, weight_fn, is_hard) } diff --git a/crates/solverforge-scoring/src/stream/cross_quad_stream/scored.rs b/crates/solverforge-scoring/src/stream/cross_quad_stream/scored.rs index e2a4ccc1f..8ff79bd26 100644 --- a/crates/solverforge-scoring/src/stream/cross_quad_stream/scored.rs +++ b/crates/solverforge-scoring/src/stream/cross_quad_stream/scored.rs @@ -1,235 +1,62 @@ use super::*; -use crate::api::analysis::EntityRef; -use crate::stream::relational::operator::{ExplainOperator, RowOrigin}; - -/// Scored quad operator: the tree plus the authored filter as one row producer. -pub struct QuadScored< - S, - A, - B, - C, - D, - EA, - EB, - EC, - ED, - P1: CompileCondition, - P2: CompileCondition, - P3: CompileCondition, - F, -> where - BuiltQuad: Operator, - F: QuadFilter, -{ - pub(super) inner: BuiltQuad, - pub(super) filter: F, - pub(super) accepted: HandleMap<()>, - /// Child notification scratch, reused across events. - pub(super) child_removed: Vec, - pub(super) child_inserted: Vec, - pub(super) marker: PhantomData (S, A, B, C, D)>, +use crate::stream::relational::operator::FilterPredicate; + +/// The authored quad filter as the top join's row filter: it runs when the +/// join finds a row, so a rejected row is never retained, and evaluate, +/// match_count, initialize, and mutations all honor it exactly once. +pub struct QuadRowFilter { + filter: F, + marker: PhantomData (A, B, C, D)>, } -impl Operator - for QuadScored -where - S: Send + Sync + 'static, - A: Send + Sync + 'static, - B: Send + Sync + 'static, - C: Send + Sync + 'static, - D: Send + Sync + 'static, - P1: CompileCondition + 'static, - P2: CompileCondition + 'static, - P3: CompileCondition + 'static, - for<'a> BuiltQuad: Operator< - S, - View<'a> = Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, - >, - F: QuadFilter + 'static, -{ - type View<'a> = QuadRow<'a, S, EA, EB, EC, ED, P1, P2, P3>; - type Evaluation = as Operator>::Evaluation; - - #[inline] - fn prepare_evaluation(&self, solution: &S) -> Self::Evaluation { - self.inner.prepare_evaluation(solution) - } - - #[inline] - fn visit_evaluation<'a>( - &'a self, - solution: &'a S, - evaluation: &'a Self::Evaluation, - visitor: &mut impl FnMut(Self::View<'a>), - ) { - self.inner - .visit_evaluation(solution, evaluation, &mut |row| { - let (a, b, c, d) = row.entities(); - let (ai, bi, ci, di) = row.indexes(); - if self.filter.test(solution, a, b, c, d, ai, bi, ci, di) { - visitor(row); - } - }); - } - - fn clear(&mut self) { - self.inner.clear(); - self.accepted.clear(); - self.child_removed.clear(); - self.child_inserted.clear(); - } - - fn initialize(&mut self, solution: &S) { - self.inner.initialize(solution); - self.accepted.clear(); - self.child_removed.clear(); - self.child_inserted.clear(); - for handle in self.inner.handles() { - let row = self.inner.resolve(solution, handle).expect("live quad row"); - if self.test(solution, row) { - self.accepted.insert(handle, ()); - } +impl QuadRowFilter { + pub(crate) fn new(filter: F) -> Self { + Self { + filter, + marker: PhantomData, } } - - fn handles(&self) -> Vec { - self.inner - .handles() - .into_iter() - .filter(|h| self.accepted.get(*h).is_some()) - .collect() - } - - fn resolve<'a>(&'a self, solution: &'a S, handle: RowHandle) -> Option> { - self.accepted.get(handle)?; - self.inner.resolve(solution, handle) - } - - fn visit_provenance(&self, handle: RowHandle, visitor: &mut impl FnMut(u32, usize, usize)) { - if self.accepted.get(handle).is_some() { - self.inner.visit_provenance(handle, visitor); - } - } - - fn retract( - &mut self, - solution: &S, - descriptor: usize, - index: usize, - removed: &mut Vec, - _inserted: &mut Vec, - ) { - removed.clear(); - let inner_removed = std::mem::take(&mut self.child_removed); - let inner_inserted = std::mem::take(&mut self.child_inserted); - let mut inner_removed = inner_removed; - let mut inner_inserted = inner_inserted; - inner_removed.clear(); - inner_inserted.clear(); - self.inner.retract( - solution, - descriptor, - index, - &mut inner_removed, - &mut inner_inserted, - ); - for h in inner_removed.drain(..) { - if self.accepted.remove(h).is_some() { - removed.push(h); - } - } - self.child_removed = inner_removed; - self.child_inserted = inner_inserted; - } - - fn insert( - &mut self, - solution: &S, - descriptor: usize, - index: usize, - _removed: &mut Vec, - inserted: &mut Vec, - ) { - let mut inner_removed = std::mem::take(&mut self.child_removed); - let mut inner_inserted = std::mem::take(&mut self.child_inserted); - inner_removed.clear(); - inner_inserted.clear(); - self.inner.insert( - solution, - descriptor, - index, - &mut inner_removed, - &mut inner_inserted, - ); - for handle in inner_inserted.drain(..) { - let row = self - .inner - .resolve(solution, handle) - .expect("live scored row"); - if self.test(solution, row) { - self.accepted.insert(handle, ()); - inserted.push(handle); - } - } - self.child_removed = inner_removed; - self.child_inserted = inner_inserted; - } } -impl - QuadScored +impl<'x, S, A, B, C, D, F> + FilterPredicate, Leaf<'x, B>>, Leaf<'x, C>>, Leaf<'x, D>>> + for QuadRowFilter where - S: Send + Sync + 'static, - P1: CompileCondition, - P2: CompileCondition, - P3: CompileCondition, - BuiltQuad: Operator, F: QuadFilter, { - #[inline] - fn test<'a>( + const ACCEPTS_ALL: bool = F::ACCEPTS_ALL; + + #[inline(always)] + fn accepts( &self, solution: &S, - row: as Operator>::View<'a>, - ) -> bool - where - A: 'a, - B: 'a, - C: 'a, - D: 'a, - as Operator>::View<'a>: - QuadEntities<'a, A, B, C, D>, - { - let (a, b, c, d) = row.entities(); - let (ai, bi, ci, di) = row.indexes(); - self.filter.test(solution, a, b, c, d, ai, bi, ci, di) + row: &Pair, Leaf<'x, B>>, Leaf<'x, C>>, Leaf<'x, D>>, + ) -> bool { + self.filter.test( + solution, + row.left.left.left.entity, + row.left.left.right.entity, + row.left.right.entity, + row.right.entity, + row.left.left.left.index, + row.left.left.right.index, + row.left.right.index, + row.right.index, + ) } } -impl ExplainOperator - for QuadScored -where - S: Send + Sync + 'static, - A: Send + Sync + 'static, - B: Send + Sync + 'static, - C: Send + Sync + 'static, - D: Send + Sync + 'static, - P1: CompileCondition + 'static, - P2: CompileCondition + 'static, - P3: CompileCondition + 'static, - for<'a> BuiltQuad: ExplainOperator< +/// The scored quad tree: its top join retains only the rows the authored +/// filter accepts. +pub(crate) type QuadScored = JoinNode< + S, + JoinNode< S, - View<'a> = Pair, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>, + JoinNode, CollectionNode, ::Plan>, + CollectionNode, + ::Plan, >, - F: QuadFilter + 'static, -{ - fn explain( - &self, - solution: &S, - row: &Self::View<'_>, - origin: RowOrigin<'_, Self::Evaluation>, - entities: &mut Vec, - ) { - self.inner.explain(solution, row, origin, entities); - } -} + CollectionNode, + ::Plan, + QuadRowFilter, +>; diff --git a/crates/solverforge-scoring/src/stream/cross_tri_stream/base.rs b/crates/solverforge-scoring/src/stream/cross_tri_stream/base.rs index e56665e0f..89b31f902 100644 --- a/crates/solverforge-scoring/src/stream/cross_tri_stream/base.rs +++ b/crates/solverforge-scoring/src/stream/cross_tri_stream/base.rs @@ -1,5 +1,5 @@ mod scored; -pub(crate) use scored::TriScored; +pub(crate) use scored::{TriRowFilter, TriScored}; /* Canonical three-source fluent join: one operator tree, no per-arity engine. @@ -22,7 +22,7 @@ use super::super::joiner::plan::{CompileCondition, ExecutablePlan, IndexedPlan}; use super::super::relational::operator::{ CollectionNode, ExplainOperator, JoinNode, Operator, Pair, }; -use super::super::relational::{HandleMap, Leaf, RowHandle}; +use super::super::relational::Leaf; use super::super::weighting_support::ConstraintWeight; use crate::constraint::relational::OperatorTerminal; @@ -368,40 +368,8 @@ where let weight = self.weight; let is_hard = self.is_hard; let constraint_ref = ConstraintRef::new("", name); - let scored = TriScored { - inner: self.tree, - filter: self.filter, - accepted: HandleMap::new(), - child_removed: Vec::new(), - child_inserted: Vec::new(), - marker: PhantomData, - }; + let scored = self.tree.with_filter(TriRowFilter::new(self.filter)); let weight_fn = crate::stream::closures::triple_row_weight::(weight); OperatorTerminal::new(constraint_ref, self.impact_type, scored, weight_fn, is_hard) } } - -/// Borrowed (A, B, C) entity triple off a tri row view. -pub(crate) trait TriEntities<'a, A, B, C> { - fn entities(&self) -> (&'a A, &'a B, &'a C); - fn indexes(&self) -> (usize, usize, usize); -} - -impl<'a, A, B, C> TriEntities<'a, A, B, C> for Pair, Leaf<'a, B>>, Leaf<'a, C>> { - #[inline] - fn entities(&self) -> (&'a A, &'a B, &'a C) { - ( - self.left.left.entity, - self.left.right.entity, - self.right.entity, - ) - } - #[inline] - fn indexes(&self) -> (usize, usize, usize) { - ( - self.left.left.index, - self.left.right.index, - self.right.index, - ) - } -} diff --git a/crates/solverforge-scoring/src/stream/cross_tri_stream/base/scored.rs b/crates/solverforge-scoring/src/stream/cross_tri_stream/base/scored.rs index 1a8c6593f..692045579 100644 --- a/crates/solverforge-scoring/src/stream/cross_tri_stream/base/scored.rs +++ b/crates/solverforge-scoring/src/stream/cross_tri_stream/base/scored.rs @@ -1,227 +1,54 @@ use super::*; -use crate::api::analysis::EntityRef; -use crate::stream::relational::operator::{ExplainOperator, RowOrigin}; - -/// Scored tri operator: the tree plus the authored filter as one row producer. -/// -/// The terminal's weight closure receives filtered rows only. Filters never -/// run twice: stateless evaluation applies them here, and retained mutations -/// publish post-filter deltas through the same predicate. -pub struct TriScored< - S, - A, - B, - C, - EA, - EB, - EC, - P1: CompileCondition, - P2: CompileCondition, - F, -> where - BuiltTri: Operator, - F: TriFilter, -{ - pub(super) inner: BuiltTri, - pub(super) filter: F, - pub(super) accepted: HandleMap<()>, - /// Child notification scratch, reused across events. - pub(super) child_removed: Vec, - pub(super) child_inserted: Vec, - pub(super) marker: PhantomData (S, A, B, C)>, +use crate::stream::relational::operator::FilterPredicate; + +/// The authored tri filter as the top join's row filter: it runs when the +/// join finds a row, so a rejected row is never retained, and evaluate, +/// match_count, initialize, and mutations all honor it exactly once. +pub struct TriRowFilter { + filter: F, + marker: PhantomData (A, B, C)>, } -impl Operator for TriScored -where - S: Send + Sync + 'static, - A: Send + Sync + 'static, - B: Send + Sync + 'static, - C: Send + Sync + 'static, - P1: CompileCondition + 'static, - P2: CompileCondition + 'static, - for<'a> JoinNode, CollectionNode, ::Plan>: - Operator = Pair, Leaf<'a, B>>>, - for<'a> BuiltTri: - Operator = Pair, Leaf<'a, B>>, Leaf<'a, C>>>, - F: TriFilter + 'static, -{ - type View<'a> = TriRow<'a, S, EA, EB, EC, P1, P2>; - type Evaluation = as Operator>::Evaluation; - - #[inline] - fn prepare_evaluation(&self, solution: &S) -> Self::Evaluation { - self.inner.prepare_evaluation(solution) - } - - #[inline] - fn visit_evaluation<'a>( - &'a self, - solution: &'a S, - evaluation: &'a Self::Evaluation, - visitor: &mut impl FnMut(Self::View<'a>), - ) { - self.inner - .visit_evaluation(solution, evaluation, &mut |row| { - let (a, b, c) = row.entities(); - let (ai, bi, ci) = row.indexes(); - if self.filter.test(solution, a, b, c, ai, bi, ci) { - visitor(row); - } - }); - } - - fn clear(&mut self) { - self.inner.clear(); - self.accepted.clear(); - self.child_removed.clear(); - self.child_inserted.clear(); - } - - fn initialize(&mut self, solution: &S) { - self.inner.initialize(solution); - self.accepted.clear(); - self.child_removed.clear(); - self.child_inserted.clear(); - for handle in self.inner.handles() { - let row = self.inner.resolve(solution, handle).expect("live tri row"); - if self.test(solution, row) { - self.accepted.insert(handle, ()); - } - } - } - - fn handles(&self) -> Vec { - self.inner - .handles() - .into_iter() - .filter(|h| self.accepted.get(*h).is_some()) - .collect() - } - - fn resolve<'a>(&'a self, solution: &'a S, handle: RowHandle) -> Option> { - self.accepted.get(handle)?; - self.inner.resolve(solution, handle) - } - - fn visit_provenance(&self, handle: RowHandle, visitor: &mut impl FnMut(u32, usize, usize)) { - if self.accepted.get(handle).is_some() { - self.inner.visit_provenance(handle, visitor); +impl TriRowFilter { + pub(crate) fn new(filter: F) -> Self { + Self { + filter, + marker: PhantomData, } } - - fn retract( - &mut self, - solution: &S, - descriptor: usize, - index: usize, - removed: &mut Vec, - _inserted: &mut Vec, - ) { - removed.clear(); - let inner_removed = std::mem::take(&mut self.child_removed); - let inner_inserted = std::mem::take(&mut self.child_inserted); - let mut inner_removed = inner_removed; - let mut inner_inserted = inner_inserted; - inner_removed.clear(); - inner_inserted.clear(); - self.inner.retract( - solution, - descriptor, - index, - &mut inner_removed, - &mut inner_inserted, - ); - for h in inner_removed.drain(..) { - if self.accepted.remove(h).is_some() { - removed.push(h); - } - } - self.child_removed = inner_removed; - self.child_inserted = inner_inserted; - } - - fn insert( - &mut self, - solution: &S, - descriptor: usize, - index: usize, - _removed: &mut Vec, - inserted: &mut Vec, - ) { - let mut inner_removed = std::mem::take(&mut self.child_removed); - let mut inner_inserted = std::mem::take(&mut self.child_inserted); - inner_removed.clear(); - inner_inserted.clear(); - self.inner.insert( - solution, - descriptor, - index, - &mut inner_removed, - &mut inner_inserted, - ); - for handle in inner_inserted.drain(..) { - let row = self - .inner - .resolve(solution, handle) - .expect("live scored row"); - if self.test(solution, row) { - self.accepted.insert(handle, ()); - inserted.push(handle); - } - } - self.child_removed = inner_removed; - self.child_inserted = inner_inserted; - } } -impl TriScored +impl<'x, S, A, B, C, F> FilterPredicate, Leaf<'x, B>>, Leaf<'x, C>>> + for TriRowFilter where - S: Send + Sync + 'static, - P1: CompileCondition, - P2: CompileCondition, - BuiltTri: Operator, F: TriFilter, { - #[inline] - fn test<'a>( - &self, - solution: &S, - row: as Operator>::View<'a>, - ) -> bool - where - A: 'a, - B: 'a, - C: 'a, - as Operator>::View<'a>: TriEntities<'a, A, B, C>, - { - let (a, b, c) = row.entities(); - let (ai, bi, ci) = row.indexes(); - self.filter.test(solution, a, b, c, ai, bi, ci) - } -} + const ACCEPTS_ALL: bool = F::ACCEPTS_ALL; -impl ExplainOperator - for TriScored -where - S: Send + Sync + 'static, - A: Send + Sync + 'static, - B: Send + Sync + 'static, - C: Send + Sync + 'static, - P1: CompileCondition + 'static, - P2: CompileCondition + 'static, - for<'a> JoinNode, CollectionNode, ::Plan>: - Operator = Pair, Leaf<'a, B>>>, - for<'a> BuiltTri: - ExplainOperator = Pair, Leaf<'a, B>>, Leaf<'a, C>>>, - F: TriFilter + 'static, -{ - fn explain( + #[inline(always)] + fn accepts( &self, solution: &S, - row: &Self::View<'_>, - origin: RowOrigin<'_, Self::Evaluation>, - entities: &mut Vec, - ) { - self.inner.explain(solution, row, origin, entities); + row: &Pair, Leaf<'x, B>>, Leaf<'x, C>>, + ) -> bool { + self.filter.test( + solution, + row.left.left.entity, + row.left.right.entity, + row.right.entity, + row.left.left.index, + row.left.right.index, + row.right.index, + ) } } + +/// The scored tri tree: its top join retains only the rows the authored +/// filter accepts. +pub(crate) type TriScored = JoinNode< + S, + JoinNode, CollectionNode, ::Plan>, + CollectionNode, + ::Plan, + TriRowFilter, +>; diff --git a/crates/solverforge-scoring/src/stream/filter/adapters.rs b/crates/solverforge-scoring/src/stream/filter/adapters.rs index 34c0a3567..c79d9db76 100644 --- a/crates/solverforge-scoring/src/stream/filter/adapters.rs +++ b/crates/solverforge-scoring/src/stream/filter/adapters.rs @@ -4,6 +4,31 @@ use std::marker::PhantomData; use super::traits::{BiFilter, TriFilter, UniFilter}; +/// A same-collection stream's authored filter as its self-join's row filter: +/// it runs when the join finds a combination, so a rejected combination is +/// never retained. +pub struct SelfJoinRowFilter { + filter: F, + _phantom: PhantomData A>, +} + +impl SelfJoinRowFilter { + /// Wraps the authored filter. + #[inline] + pub fn new(filter: F) -> Self { + Self { + filter, + _phantom: PhantomData, + } + } + + /// The authored filter. + #[inline] + pub(crate) fn inner(&self) -> &F { + &self.filter + } +} + /// Applies a uni-filter to both elements of a pair (for self-joins). pub struct UniBiFilter { filter: F, diff --git a/crates/solverforge-scoring/src/stream/filter/mod.rs b/crates/solverforge-scoring/src/stream/filter/mod.rs index a52c817a1..ab7794cb3 100644 --- a/crates/solverforge-scoring/src/stream/filter/mod.rs +++ b/crates/solverforge-scoring/src/stream/filter/mod.rs @@ -9,8 +9,8 @@ mod traits; mod wrappers; pub use adapters::{ - PairFilter, QuadAsPentaFilter, TriAsBiFilter, TriAsQuadFilter, UniBiFilter, UniLeftBiFilter, - UniPairFilter, + PairFilter, QuadAsPentaFilter, SelfJoinRowFilter, TriAsBiFilter, TriAsQuadFilter, UniBiFilter, + UniLeftBiFilter, UniPairFilter, }; pub use composition::{AndBiFilter, AndPentaFilter, AndQuadFilter, AndTriFilter, AndUniFilter}; pub use traits::{BiFilter, PentaFilter, QuadFilter, TriFilter, UniFilter}; diff --git a/crates/solverforge-scoring/src/stream/flattened_bi_stream/builder.rs b/crates/solverforge-scoring/src/stream/flattened_bi_stream/builder.rs index ea106fdfe..b909ca397 100644 --- a/crates/solverforge-scoring/src/stream/flattened_bi_stream/builder.rs +++ b/crates/solverforge-scoring/src/stream/flattened_bi_stream/builder.rs @@ -10,7 +10,7 @@ use super::super::relational::operator::FlattenView; use super::super::relational::operator::{CollectionNode, FlattenNode, Pair}; use super::super::relational::view_plan::{EntityKey, FlattenedPairKey, PairKey, ViewEqualPlan}; use super::super::relational::Leaf; -use super::scored::FlattenedBiScored; +use super::scored::FlattenedBiRowFilter; use crate::constraint::relational::OperatorTerminal; /// Finalizes a flattened bi-constraint onto the shared operator tree: a @@ -102,25 +102,19 @@ where name: &str, ) -> OperatorTerminal< S, - FlattenedBiScored< + super::super::relational::operator::JoinNode< S, - A, - B, - C, - super::super::relational::operator::JoinNode< - S, - CollectionNode, - FlattenNode< - CollectionNode, - super::super::relational::operator::ParentFlatten, - >, - ViewEqualPlan< - (K, CK), - PairKey, EntityKey>, - FlattenedPairKey, - >, + CollectionNode, + FlattenNode< + CollectionNode, + super::super::relational::operator::ParentFlatten, >, - F, + ViewEqualPlan< + (K, CK), + PairKey, EntityKey>, + FlattenedPairKey, + >, + FlattenedBiRowFilter, >, impl for<'a> Fn(&S, &Pair, FlattenView<'a, Leaf<'a, B>, C>>) -> Sc + Send + Sync, Sc, @@ -134,8 +128,12 @@ where CollectionNode::new(self.extractor_b, 0), super::super::relational::operator::ParentFlatten::new(self.flatten), ); - let tree = super::super::relational::operator::JoinNode::new(left, right, plan); - let scored = FlattenedBiScored::new(tree, self.filter); + let scored = super::super::relational::operator::JoinNode::filtered( + left, + right, + plan, + FlattenedBiRowFilter::new(self.filter), + ); let weight = self.weight; let weight_fn = crate::stream::closures::flattened_row_weight::(weight); OperatorTerminal::new( diff --git a/crates/solverforge-scoring/src/stream/flattened_bi_stream/scored.rs b/crates/solverforge-scoring/src/stream/flattened_bi_stream/scored.rs index 47f0fa093..91eb02cc8 100644 --- a/crates/solverforge-scoring/src/stream/flattened_bi_stream/scored.rs +++ b/crates/solverforge-scoring/src/stream/flattened_bi_stream/scored.rs @@ -1,239 +1,51 @@ -//! Scoring operator for the flattened bi-constraint. +//! Row filter of the flattened bi-constraint. //! //! The join tree publishes `Pair, FlattenView, C>>`: the left //! entity plus the flattened child with its owning B row. The authored bi filter -//! runs inside this operator on `(A, C)` with the A and owning-B source indexes, -//! so evaluate, match_count, initialize, and mutations honor it exactly once and -//! scoring is the generic `OperatorTerminal`. +//! runs on `(A, C)` with the A and owning-B source indexes as the join's row +//! filter, so a rejected row is never retained and evaluate, match_count, +//! initialize, and mutations honor it exactly once. use std::marker::PhantomData; use super::super::filter::BiFilter; -use super::super::relational::operator::{FlattenView, Operator, Pair}; -use super::super::relational::{HandleMap, Leaf, RowHandle}; -use crate::api::analysis::EntityRef; -use crate::stream::relational::operator::{ExplainOperator, RowOrigin}; +use super::super::relational::operator::{FilterPredicate, FlattenView, Pair}; +use super::super::relational::Leaf; -/// Borrowed (A, C) pair plus the A and owning-B source indexes. -pub(super) trait FlattenedBiEntities<'a, A, B, C> { - fn entities(&self) -> (&'a A, &'a C); - fn indexes(&self) -> (usize, usize); -} - -impl<'a, A, B, C> FlattenedBiEntities<'a, A, B, C> - for Pair, FlattenView<'a, Leaf<'a, B>, C>> -{ - #[inline] - fn entities(&self) -> (&'a A, &'a C) { - (self.left.entity, self.right.value) - } - #[inline] - fn indexes(&self) -> (usize, usize) { - (self.left.index, self.right.input.index) - } -} - -pub struct FlattenedBiScored { - inner: O, +/// The authored flattened-bi filter as the join's row filter. +pub struct FlattenedBiRowFilter { filter: F, - accepted: HandleMap<()>, - /// Child notification scratch, reused across events. - child_removed: Vec, - child_inserted: Vec, - marker: PhantomData (S, A, B, C)>, + marker: PhantomData (A, B, C)>, } -impl FlattenedBiScored { - pub(super) fn new(inner: O, filter: F) -> Self { +impl FlattenedBiRowFilter { + pub(super) fn new(filter: F) -> Self { Self { - inner, filter, - accepted: HandleMap::new(), - child_removed: Vec::new(), - child_inserted: Vec::new(), marker: PhantomData, } } - - #[inline] - fn test<'a>( - &self, - solution: &S, - row: &Pair, FlattenView<'a, Leaf<'a, B>, C>>, - ) -> bool - where - S: 'static, - F: BiFilter, - { - let (a, c) = row.entities(); - let (a_idx, b_idx) = row.indexes(); - self.filter.test(solution, a, c, a_idx, b_idx) - } } -impl Operator for FlattenedBiScored +impl<'x, S, A, B, C, F> FilterPredicate, FlattenView<'x, Leaf<'x, B>, C>>> + for FlattenedBiRowFilter where - S: Send + Sync + 'static, - A: 'static, - B: 'static, - C: 'static, - O: Operator, - for<'a> O: Operator = Pair, FlattenView<'a, Leaf<'a, B>, C>>>, - F: BiFilter + 'static, + F: BiFilter, { - type View<'a> = O::View<'a>; - type Evaluation = O::Evaluation; - - #[inline] - fn prepare_evaluation(&self, solution: &S) -> Self::Evaluation { - self.inner.prepare_evaluation(solution) - } - - #[inline] - fn visit_evaluation<'a>( - &'a self, - solution: &'a S, - evaluation: &'a Self::Evaluation, - visitor: &mut impl FnMut(Self::View<'a>), - ) { - self.inner - .visit_evaluation(solution, evaluation, &mut |row| { - if self.test(solution, &row) { - visitor(row); - } - }); - } - - fn clear(&mut self) { - self.inner.clear(); - self.accepted.clear(); - self.child_removed.clear(); - self.child_inserted.clear(); - } - - fn initialize(&mut self, solution: &S) { - self.inner.initialize(solution); - self.accepted.clear(); - self.child_removed.clear(); - self.child_inserted.clear(); - for handle in self.inner.handles() { - let row = self - .inner - .resolve(solution, handle) - .expect("live flattened row"); - if self.test(solution, &row) { - self.accepted.insert(handle, ()); - } - } - } - - fn handles(&self) -> Vec { - self.inner - .handles() - .into_iter() - .filter(|h| self.accepted.get(*h).is_some()) - .collect() - } + const ACCEPTS_ALL: bool = F::ACCEPTS_ALL; - fn resolve<'a>(&'a self, solution: &'a S, handle: RowHandle) -> Option> { - self.accepted.get(handle)?; - self.inner.resolve(solution, handle) - } - - fn visit_provenance(&self, handle: RowHandle, visitor: &mut impl FnMut(u32, usize, usize)) { - if self.accepted.get(handle).is_some() { - self.inner.visit_provenance(handle, visitor); - } - } - - fn retract( - &mut self, - solution: &S, - descriptor: usize, - index: usize, - removed: &mut Vec, - _inserted: &mut Vec, - ) { - removed.clear(); - let inner_removed = std::mem::take(&mut self.child_removed); - let inner_inserted = std::mem::take(&mut self.child_inserted); - let mut inner_removed = inner_removed; - let mut inner_inserted = inner_inserted; - inner_removed.clear(); - inner_inserted.clear(); - self.inner.retract( - solution, - descriptor, - index, - &mut inner_removed, - &mut inner_inserted, - ); - for h in inner_removed.drain(..) { - if self.accepted.remove(h).is_some() { - removed.push(h); - } - } - self.child_removed = inner_removed; - self.child_inserted = inner_inserted; - } - - fn insert( - &mut self, - solution: &S, - descriptor: usize, - index: usize, - _removed: &mut Vec, - inserted: &mut Vec, - ) { - let mut inner_removed = std::mem::take(&mut self.child_removed); - let mut inner_inserted = std::mem::take(&mut self.child_inserted); - inner_removed.clear(); - inner_inserted.clear(); - self.inner.insert( - solution, - descriptor, - index, - &mut inner_removed, - &mut inner_inserted, - ); - for handle in inner_inserted.drain(..) { - let row = self - .inner - .resolve(solution, handle) - .expect("live scored row"); - if self.test(solution, &row) { - self.accepted.insert(handle, ()); - inserted.push(handle); - } - } - self.child_removed = inner_removed; - self.child_inserted = inner_inserted; - } -} - -impl std::fmt::Debug for FlattenedBiScored { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("FlattenedBiScored").finish() - } -} - -impl ExplainOperator for FlattenedBiScored -where - S: Send + Sync + 'static, - A: 'static, - B: 'static, - C: 'static, - O: ExplainOperator, - for<'a> O: Operator = Pair, FlattenView<'a, Leaf<'a, B>, C>>>, - F: BiFilter + 'static, -{ - fn explain( + #[inline(always)] + fn accepts( &self, solution: &S, - row: &Self::View<'_>, - origin: RowOrigin<'_, Self::Evaluation>, - entities: &mut Vec, - ) { - self.inner.explain(solution, row, origin, entities); + row: &Pair, FlattenView<'x, Leaf<'x, B>, C>>, + ) -> bool { + self.filter.test( + solution, + row.left.entity, + row.right.value, + row.left.index, + row.right.input.index, + ) } } diff --git a/crates/solverforge-scoring/src/stream/group_by_penta.rs b/crates/solverforge-scoring/src/stream/group_by_penta.rs index 62ca3ef21..e889ecd8c 100644 --- a/crates/solverforge-scoring/src/stream/group_by_penta.rs +++ b/crates/solverforge-scoring/src/stream/group_by_penta.rs @@ -1,7 +1,7 @@ use super::collector::{Accumulator, Collector}; use super::filter::PentaFilter; use super::joiner::plan::{CompileCondition, IndexedPlan}; -use super::relational::operator::{FilterNode, Operator, Pair}; +use super::relational::operator::{Operator, Pair}; use super::relational::{Leaf, TupleCollector}; use super::JoinedGroupedStream; use solverforge_core::score::Score; @@ -40,9 +40,23 @@ where collector: Co, ) -> JoinedGroupedStream< S, - FilterNode< - super::cross_penta_stream::BuiltPenta, - impl Fn(&S, &Row<'_, A, B, C, D, E>) -> bool + Send + Sync, + super::cross_penta_stream::PentaScored< + S, + A, + B, + C, + D, + E, + EA, + EB, + EC, + ED, + EE, + P1, + P2, + P3, + P4, + F, >, impl Fn(&Row<'_, A, B, C, D, E>) -> GK + Send + Sync, TupleCollector, @@ -65,10 +79,9 @@ where R: Send + Sync + 'static, Acc: Accumulator + 'static, { - let input = FilterNode::new( - self.tree, - crate::stream::closures::penta_row_filter::(self.filter), - ); + let input = self + .tree + .with_filter(super::cross_penta_stream::PentaRowFilter::new(self.filter)); JoinedGroupedStream::new( input, crate::stream::closures::penta_row_key::(key), diff --git a/crates/solverforge-scoring/src/stream/group_by_quad.rs b/crates/solverforge-scoring/src/stream/group_by_quad.rs index cab47a944..4e86fcc36 100644 --- a/crates/solverforge-scoring/src/stream/group_by_quad.rs +++ b/crates/solverforge-scoring/src/stream/group_by_quad.rs @@ -1,7 +1,7 @@ use super::collector::{Accumulator, Collector}; use super::filter::QuadFilter; use super::joiner::plan::{CompileCondition, IndexedPlan}; -use super::relational::operator::{FilterNode, Operator, Pair}; +use super::relational::operator::{Operator, Pair}; use super::relational::{Leaf, TupleCollector}; use super::JoinedGroupedStream; use solverforge_core::score::Score; @@ -36,10 +36,7 @@ where collector: Co, ) -> JoinedGroupedStream< S, - FilterNode< - super::cross_quad_stream::BuiltQuad, - impl Fn(&S, &Row<'_, A, B, C, D>) -> bool + Send + Sync, - >, + super::cross_quad_stream::QuadScored, impl Fn(&Row<'_, A, B, C, D>) -> GK + Send + Sync, TupleCollector, GK, @@ -61,10 +58,9 @@ where R: Send + Sync + 'static, Acc: Accumulator + 'static, { - let input = FilterNode::new( - self.tree, - crate::stream::closures::quad_row_filter::(self.filter), - ); + let input = self + .tree + .with_filter(super::cross_quad_stream::QuadRowFilter::new(self.filter)); JoinedGroupedStream::new( input, crate::stream::closures::quad_row_key::(key), diff --git a/crates/solverforge-scoring/src/stream/group_by_tri.rs b/crates/solverforge-scoring/src/stream/group_by_tri.rs index 2a471ad65..46fbe5d87 100644 --- a/crates/solverforge-scoring/src/stream/group_by_tri.rs +++ b/crates/solverforge-scoring/src/stream/group_by_tri.rs @@ -1,7 +1,7 @@ use super::collector::{Accumulator, Collector}; use super::filter::TriFilter; use super::joiner::plan::{CompileCondition, IndexedPlan}; -use super::relational::operator::{FilterNode, Operator, Pair}; +use super::relational::operator::{Operator, Pair}; use super::relational::{Leaf, TupleCollector}; use super::JoinedGroupedStream; use solverforge_core::score::Score; @@ -32,10 +32,7 @@ where collector: Co, ) -> JoinedGroupedStream< S, - FilterNode< - super::cross_tri_stream::base::BuiltTri, - impl Fn(&S, &Row<'_, A, B, C>) -> bool + Send + Sync, - >, + super::cross_tri_stream::base::TriScored, impl Fn(&Row<'_, A, B, C>) -> GK + Send + Sync, TupleCollector, GK, @@ -53,10 +50,11 @@ where R: Send + Sync + 'static, Acc: Accumulator + 'static, { - let input = FilterNode::new( - self.tree, - crate::stream::closures::triple_row_filter::(self.filter), - ); + let input = self + .tree + .with_filter(super::cross_tri_stream::base::TriRowFilter::new( + self.filter, + )); JoinedGroupedStream::new( input, crate::stream::closures::triple_row_key::(key), diff --git a/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs b/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs index e04b37bb8..d3da185c0 100644 --- a/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs +++ b/crates/solverforge-scoring/src/stream/grouped_stream/joined.rs @@ -12,7 +12,7 @@ use super::super::relational::leaf_collector::{leaf_key, LeafCollector, LeafFilt use super::super::relational::operator::{ CollectionNode, FilterNode, GroupNode, GroupView, JoinNode, }; -use super::super::relational::view_plan::{EntityKey, GroupKey, ViewEqualPlan}; +use super::super::relational::view_plan::{EntityKey, GroupEqualPlan, GroupLeft}; use super::super::relational::Leaf; use super::super::weighting_support::ConstraintWeight; use crate::constraint::relational::{ @@ -97,10 +97,10 @@ where Acc: Accumulator + Send + Sync + 'static, KB: Fn(&B) -> K + Send + Sync + 'static, Sc: Score + 'static, - for<'x> ViewEqualPlan>: + for<'x> GroupEqualPlan, GroupLeft>: ExecutablePlan, K, Acc, V, R>, Leaf<'x, B>>, - ViewEqualPlan>: IndexedPlan - + CompileCondition>>, + GroupEqualPlan, GroupLeft>: IndexedPlan + + CompileCondition, GroupLeft>>, { fn into_weighted_builder( self, @@ -231,10 +231,10 @@ where KB: Fn(&B) -> K + Send + Sync + 'static, W: Fn(&K, &R, &B) -> Sc + Send + Sync, Sc: Score + 'static, - for<'x> ViewEqualPlan>: + for<'x> GroupEqualPlan, GroupLeft>: ExecutablePlan, K, Acc, V, R>, Leaf<'x, B>>, - ViewEqualPlan>: IndexedPlan - + CompileCondition>>, + GroupEqualPlan, GroupLeft>: IndexedPlan + + CompileCondition, GroupLeft>>, { pub fn named( self, @@ -253,7 +253,7 @@ where R, >, CollectionNode, - ViewEqualPlan>, + GroupEqualPlan, GroupLeft>, >, GroupedJoinAdapter, OperatorScorer, Sc>, @@ -270,7 +270,7 @@ where LeafCollector::new(self.collector), ), CollectionNode::new(self.extractor_b, 1), - ViewEqualPlan::new(GroupKey, EntityKey::new(right_key)), + GroupEqualPlan::new(EntityKey::new(right_key)), ); SharedOperatorBuilder::first_with_hard( tree, diff --git a/crates/solverforge-scoring/src/stream/joiner/plan/composite.rs b/crates/solverforge-scoring/src/stream/joiner/plan/composite.rs index 84f87fe67..0b87c2c16 100644 --- a/crates/solverforge-scoring/src/stream/joiner/plan/composite.rs +++ b/crates/solverforge-scoring/src/stream/joiner/plan/composite.rs @@ -44,7 +44,7 @@ impl ComposePlans for (ResidualKind, ResidualKind) { } pub trait EqualityPlan { - type Key: Eq + Hash + Clone; + type Key: Eq + Hash; } pub trait EqualityKeys: EqualityPlan { fn left_key(&self, row: &L) -> Self::Key; diff --git a/crates/solverforge-scoring/src/stream/joiner/plan/executable.rs b/crates/solverforge-scoring/src/stream/joiner/plan/executable.rs index b2d42924a..aca072c28 100644 --- a/crates/solverforge-scoring/src/stream/joiner/plan/executable.rs +++ b/crates/solverforge-scoring/src/stream/joiner/plan/executable.rs @@ -22,6 +22,16 @@ pub trait ExecutablePlan: IndexedPlan + Joiner { fn candidate_matches(&self, left: &L, right: &R) -> bool { self.matches(left, right) } + /// `candidate_matches` for a pair found by `right_candidates`. + #[inline] + fn right_candidate_matches(&self, left: &L, right: &R) -> bool { + self.candidate_matches(left, right) + } + /// `candidate_matches` for a pair found by `left_candidates`. + #[inline] + fn left_candidate_matches(&self, left: &L, right: &R) -> bool { + self.candidate_matches(left, right) + } fn insert_left(&self, indexes: &mut Self::Indexes, handle: RowHandle, row: &L); fn insert_right(&self, indexes: &mut Self::Indexes, handle: RowHandle, row: &R); fn insert_right_transient(&self, indexes: &mut Self::Indexes, handle: RowHandle, row: &R) { diff --git a/crates/solverforge-scoring/src/stream/joiner/plan/ordered_interval.rs b/crates/solverforge-scoring/src/stream/joiner/plan/ordered_interval.rs index e2a0103a5..7aa9341c8 100644 --- a/crates/solverforge-scoring/src/stream/joiner/plan/ordered_interval.rs +++ b/crates/solverforge-scoring/src/stream/joiner/plan/ordered_interval.rs @@ -14,7 +14,7 @@ macro_rules! ordered_plan { self } } - impl IndexedPlan for $ty { + impl IndexedPlan for $ty { type Kind = super::ResidualKind; type Indexes = (OrderedIndex, OrderedIndex); fn new_indexes(&self) -> Self::Indexes { @@ -29,7 +29,7 @@ macro_rules! ordered_plan { } impl ExecutablePlan for $ty where - K: Ord + Clone, + K: Ord, FA: Fn(&L) -> K + Send + Sync, FB: Fn(&R) -> K + Send + Sync, { @@ -59,7 +59,7 @@ impl CompileCondition for OverlappingJoiner IndexedPlan for OverlappingJoiner { +impl IndexedPlan for OverlappingJoiner { type Kind = super::ResidualKind; type Indexes = (IntervalIndex, IntervalIndex); fn new_indexes(&self) -> Self::Indexes { @@ -74,7 +74,7 @@ impl IndexedPlan for OverlappingJoiner ExecutablePlan for OverlappingJoiner where - K: Ord + Clone, + K: Ord, LS: Fn(&L) -> K + Send + Sync, LE: Fn(&L) -> K + Send + Sync, RS: Fn(&R) -> K + Send + Sync, diff --git a/crates/solverforge-scoring/src/stream/projected_stream/complemented_grouped.rs b/crates/solverforge-scoring/src/stream/projected_stream/complemented_grouped.rs index 3c01ae106..a331a27f0 100644 --- a/crates/solverforge-scoring/src/stream/projected_stream/complemented_grouped.rs +++ b/crates/solverforge-scoring/src/stream/projected_stream/complemented_grouped.rs @@ -13,7 +13,7 @@ use crate::stream::collector::{Accumulator, Collector}; use crate::stream::filter::UniFilter; use crate::stream::relational::leaf_collector::OptionalEntityKey; use crate::stream::relational::operator::{CollectionNode, ComplementNode, FilterNode, GroupNode}; -use crate::stream::relational::view_plan::{GroupKey, ViewEqualPlan}; +use crate::stream::relational::view_plan::{GroupEqualPlan, GroupRight}; use crate::stream::relational::Leaf; use crate::stream::weighting_support::ConstraintWeight; @@ -233,7 +233,7 @@ where V, R, >, - ViewEqualPlan, OptionalEntityKey, GroupKey>, + GroupEqualPlan, OptionalEntityKey, GroupRight>, impl Fn(&S, &Leaf<'_, B>) -> R + Send + Sync, R, >, @@ -258,7 +258,7 @@ where let tree = ComplementNode::new( CollectionNode::new(self.extractor_b, target_binding), group, - ViewEqualPlan::new(OptionalEntityKey::new(key_b.clone()), GroupKey), + GroupEqualPlan::new(OptionalEntityKey::new(key_b.clone())), crate::stream::closures::leaf_default::(default_fn), ); SharedOperatorBuilder::first_with_hard( diff --git a/crates/solverforge-scoring/src/stream/relational/count_state.rs b/crates/solverforge-scoring/src/stream/relational/count_state.rs index 244ed52b6..e719ab136 100644 --- a/crates/solverforge-scoring/src/stream/relational/count_state.rs +++ b/crates/solverforge-scoring/src/stream/relational/count_state.rs @@ -6,166 +6,173 @@ //! membership pass, so a key removed and re-added inside one event simply ends //! on its final count — no born/died sets, no direction tracking. //! -//! The dense shape stores counts and buckets indexed directly by `usize` keys -//! (planning ids), where hashing costs more than the index. Dispatch happens -//! once at construction; the event path calls one enum method per key and -//! nothing else branches. +//! Keys are addressed by a `KeyId`. The dense shape stores counts and buckets +//! indexed directly by `usize` keys (planning ids), where hashing costs more +//! than the index, and a key is its own id. The hashed shape stores every key +//! once, in a `KeyTable` slot, and the slot is the id: rows and the touched +//! list hold ids, never key copies. Dispatch happens once at construction; +//! the event path calls one enum method per key and nothing else branches. use std::any::Any; -use super::{FastMap, RowHandle}; +use super::{KeyTable, RowHandle}; -/// One key's count plus the epoch of its last touch, stamped against the -/// owning state's event counter. The epoch replaces a second keyed structure -/// (a marked set): first-touch detection is one map probe on the entry that -/// must be written anyway, and the touched list carries the only extra key. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) struct CountSlot { +/// A key's address in its `KeyState`: the key itself in the dense shape, its +/// table slot in the hashed shape. +pub(crate) type KeyId = usize; + +/// One hashed key's count, left rows and the epoch of its last touch, +/// stamped against the owning state's event counter. The epoch replaces a +/// marked set: first-touch detection reads the entry that must be written +/// anyway. +#[derive(Default)] +pub(crate) struct KeyEntry { count: usize, touched_epoch: u64, + left: Vec, } pub(crate) enum KeyState { Dense(DenseKeys), Hashed { - counts: FastMap, - left_buckets: FastMap>, + keys: KeyTable, /// Keys whose count changed in the current event, first-touch order. - touched: Vec, + touched: Vec, /// Monotonic event counter stamping `touched` epochs. epoch: u64, }, } -impl KeyState { +impl KeyState { /// Picks the dense shape exactly when the key is `usize`, the planning-id /// case where the table beats the hash. pub(crate) fn new() -> Self { if std::any::TypeId::of::() == std::any::TypeId::of::() { - // Safety of the cast pair below: every K-typed value stored in - // the dense shape is repr-transparent here because this arm only - // constructs when K IS usize. Methods uphold it by converting at - // the boundary. Self::Dense(DenseKeys::new()) } else { Self::Hashed { - counts: FastMap::default(), - left_buckets: FastMap::default(), + keys: KeyTable::new(), touched: Vec::new(), - epoch: 0, + // Entries start at epoch 0, so the first event must differ. + epoch: 1, } } } - /// Bump one key's count, marking it touched. Returns the fresh count. - pub(crate) fn add(&mut self, key: &K, n: usize) -> usize { + /// The id of `key`, taking ownership of it when the state holds it for + /// the first time. + #[inline] + pub(crate) fn intern(&mut self, key: K) -> KeyId { match self { - Self::Dense(state) => { - let raw = dense_raw(key); - state.add(raw, n) - } + Self::Dense(_) => dense_raw(&key), + Self::Hashed { keys, .. } => keys.find_or_insert(key, KeyEntry::default) as KeyId, + } + } + + /// Bump one key's count, marking it touched. + #[inline] + pub(crate) fn add(&mut self, id: KeyId, n: usize) { + match self { + Self::Dense(state) => state.add(id, n), Self::Hashed { - counts, + keys, touched, epoch, - .. } => { - // First-touch clone only: repeat touches within one epoch - // insert nothing and clone nothing. - let needs_touch = counts - .get(key) - .is_none_or(|slot| slot.touched_epoch != *epoch); - if needs_touch { - let entry = counts.entry(key.clone()).or_default(); + let entry = keys.get_mut(id as u32); + if entry.touched_epoch != *epoch { entry.touched_epoch = *epoch; - touched.push(key.clone()); + touched.push(id); } - if let Some(entry) = counts.get_mut(key) { - entry.count += n; - } - counts.get(key).map(|entry| entry.count).unwrap_or_default() + entry.count += n; } } } /// Drop one key's count by `n` (count must be at least `n`). - pub(crate) fn take(&mut self, key: &K, n: usize) { + #[inline] + pub(crate) fn take(&mut self, id: KeyId, n: usize) { match self { - Self::Dense(state) => state.take(dense_raw(key), n), + Self::Dense(state) => state.take(id, n), Self::Hashed { - counts, + keys, touched, epoch, - .. } => { - let needs_touch = counts - .get(key) - .is_none_or(|slot| slot.touched_epoch != *epoch); - if needs_touch { - let entry = counts.entry(key.clone()).or_default(); + let entry = keys.get_mut(id as u32); + if entry.touched_epoch != *epoch { entry.touched_epoch = *epoch; - touched.push(key.clone()); - } - if let Some(entry) = counts.get_mut(key) { - entry.count = entry.count.saturating_sub(n); - if entry.count == 0 { - counts.remove(key); - } + touched.push(id); } + debug_assert!(entry.count >= n, "count underflow"); + entry.count -= n; } } } /// Whether the key is currently alive (count > 0). - pub(crate) fn alive(&self, key: &K) -> bool { + #[inline] + pub(crate) fn alive(&self, id: KeyId) -> bool { match self { - Self::Dense(state) => state.alive(dense_raw(key)), - Self::Hashed { counts, .. } => counts.contains_key(key), + Self::Dense(state) => state.alive(id), + Self::Hashed { keys, .. } => keys.get(id as u32).count > 0, } } - /// Register one left row under its key's bucket. - pub(crate) fn left_insert(&mut self, key: &K, handle: RowHandle) { + /// Register one left row under its key's bucket; returns its position. + #[inline] + pub(crate) fn left_insert(&mut self, id: KeyId, handle: RowHandle) -> usize { match self { - Self::Dense(state) => state.left_insert(dense_raw(key), handle), - Self::Hashed { left_buckets, .. } => { - // Clone the key only when the bucket is new; repeat inserts - // into a live bucket clone nothing. - if let Some(bucket) = left_buckets.get_mut(key) { - bucket.push(handle); - } else { - left_buckets.entry(key.clone()).or_default().push(handle); - } + Self::Dense(state) => state.left_insert(id, handle), + Self::Hashed { keys, .. } => { + let left = &mut keys.get_mut(id as u32).left; + left.push(handle); + left.len() - 1 } } } - /// Remove one left row from its key's bucket (bucket empties are dropped). - pub(crate) fn left_remove(&mut self, key: &K, handle: RowHandle) { + /// Removes the left row at `position` of its key's bucket by swap removal + /// and returns the row moved into that position. Called between events, + /// when no key is pending in the touched list, so a hashed key left with + /// no rows and no count is released at once. + #[inline] + pub(crate) fn left_remove(&mut self, id: KeyId, position: usize) -> Option { match self { - Self::Dense(state) => state.left_remove(dense_raw(key), handle), - Self::Hashed { left_buckets, .. } => { - if let Some(bucket) = left_buckets.get_mut(key) { - if let Some(pos) = bucket.iter().position(|h| *h == handle) { - bucket.swap_remove(pos); - } - if bucket.is_empty() { - left_buckets.remove(key); - } + Self::Dense(state) => state.left_remove(id, position), + Self::Hashed { keys, .. } => { + let entry = keys.get_mut(id as u32); + entry.left.swap_remove(position); + let moved = entry.left.get(position).copied(); + if entry.left.is_empty() && entry.count == 0 { + keys.remove(id as u32); } + moved } } } /// The live left rows under one key. - pub(crate) fn left_bucket<'a>(&'a self, key: &'a K) -> Option<&'a [RowHandle]> { + #[inline] + pub(crate) fn left_bucket(&self, id: KeyId) -> &[RowHandle] { match self { - Self::Dense(state) => state.left_bucket(dense_raw(key)), - Self::Hashed { left_buckets, .. } => left_buckets.get(key).map(Vec::as_slice), + Self::Dense(state) => state.left_bucket(id), + Self::Hashed { keys, .. } => &keys.get(id as u32).left, } } - /// Begin a fresh event: clears the touched list only. + /// Releases a settled hashed key left with no rows and no count. + #[inline] + pub(crate) fn release_if_unused(&mut self, id: KeyId) { + if let Self::Hashed { keys, .. } = self { + let entry = keys.get(id as u32); + if entry.count == 0 && entry.left.is_empty() { + keys.remove(id as u32); + } + } + } + + /// Begin a fresh event: clears the touched marks only. pub(crate) fn begin_event(&mut self) { match self { Self::Dense(state) => state.begin_event(), @@ -175,30 +182,24 @@ impl KeyState { /// Every key whose count changed during the current event, in first-touch /// order. The list drains; the next event starts unmarked. - pub(crate) fn drain_touched(&mut self, out: &mut Vec) { + pub(crate) fn drain_touched(&mut self, out: &mut Vec) { match self { Self::Dense(state) => { for raw in state.touched.drain(..) { state.in_touched[raw] = false; - out.push(key_from_raw::(raw)); + out.push(raw); } } - Self::Hashed { touched, .. } => { - out.append(touched); - } + Self::Hashed { touched, .. } => out.append(touched), } } pub(crate) fn clear(&mut self) { match self { Self::Dense(state) => state.clear(), - Self::Hashed { - counts, - left_buckets, - .. - } => { - counts.clear(); - left_buckets.clear(); + Self::Hashed { keys, touched, .. } => { + keys.clear(); + touched.clear(); } } } @@ -234,7 +235,7 @@ impl DenseKeys { /// (no separate `touch` frame), and the grow branch is the cheap len compare /// — `grow` itself only runs during warmup, never again. #[inline] - pub(crate) fn add(&mut self, raw: usize, n: usize) -> usize { + pub(crate) fn add(&mut self, raw: usize, n: usize) { if self.counts.len() <= raw { self.grow(raw); } @@ -243,7 +244,6 @@ impl DenseKeys { self.in_touched[raw] = true; self.touched.push(raw); } - self.counts[raw] as usize } #[inline] pub(crate) fn take(&mut self, raw: usize, n: usize) { @@ -262,22 +262,20 @@ impl DenseKeys { self.counts.get(raw).copied().unwrap_or(0) > 0 } #[inline] - pub(crate) fn left_insert(&mut self, raw: usize, handle: RowHandle) { + pub(crate) fn left_insert(&mut self, raw: usize, handle: RowHandle) -> usize { self.grow(raw); self.left_buckets[raw].push(handle); + self.left_buckets[raw].len() - 1 } #[inline] - pub(crate) fn left_remove(&mut self, raw: usize, handle: RowHandle) { - if raw >= self.left_buckets.len() { - return; - } - if let Some(pos) = self.left_buckets[raw].iter().position(|h| *h == handle) { - self.left_buckets[raw].swap_remove(pos); - } + pub(crate) fn left_remove(&mut self, raw: usize, position: usize) -> Option { + let bucket = &mut self.left_buckets[raw]; + bucket.swap_remove(position); + bucket.get(position).copied() } #[inline] - pub(crate) fn left_bucket(&self, raw: usize) -> Option<&[RowHandle]> { - self.left_buckets.get(raw).map(Vec::as_slice) + pub(crate) fn left_bucket(&self, raw: usize) -> &[RowHandle] { + self.left_buckets.get(raw).map(Vec::as_slice).unwrap_or(&[]) } pub(crate) fn begin_event(&mut self) { for raw in self.touched.drain(..) { @@ -304,16 +302,3 @@ fn dense_raw(key: &K) -> usize { .downcast_ref::() .expect("dense counts are usize-keyed") } - -/// Inverse of `dense_raw`, same `K == usize` arm. -/// -/// # Panics -/// -/// When `K` is not `usize`. -fn key_from_raw(raw: usize) -> K { - let mut slot = Some(raw); - (&mut slot as &mut dyn Any) - .downcast_mut::>() - .and_then(Option::take) - .expect("dense counts are usize-keyed") -} diff --git a/crates/solverforge-scoring/src/stream/relational/index/hash.rs b/crates/solverforge-scoring/src/stream/relational/index/hash.rs index 110a61f19..b86f8b27d 100644 --- a/crates/solverforge-scoring/src/stream/relational/index/hash.rs +++ b/crates/solverforge-scoring/src/stream/relational/index/hash.rs @@ -8,132 +8,147 @@ use std::hash::Hash; -#[cfg(test)] -mod tests { - use super::*; - use std::cell::Cell; - use std::hash::{Hash, Hasher}; - - #[derive(Clone)] - struct Key<'a>(u32, &'a Cell); - impl PartialEq for Key<'_> { - fn eq(&self, other: &Self) -> bool { - self.0 == other.0 - } - } - impl Eq for Key<'_> {} - impl Hash for Key<'_> { - fn hash(&self, hasher: &mut H) { - self.1.set(self.1.get() + 1); - self.0.hash(hasher); - } - } - - #[test] - fn retract_from_surviving_bucket_probes_once() { - let calls = Cell::new(0); - let mut index = HashIndex::new(); - let first = RowHandle::new(0, 0); - let second = RowHandle::new(1, 0); - index.insert(first, Key(7, &calls)); - index.insert(second, Key(7, &calls)); - calls.set(0); - index.remove(first); - assert_eq!(calls.get(), 1, "a surviving bucket must stay in the table"); - assert_eq!(index.lookup(&Key(7, &calls)), &[second]); - index.remove(second); - assert!(index.lookup(&Key(7, &calls)).is_empty()); - index.insert(first, Key(9, &calls)); - index.insert(first, Key(10, &calls)); - assert!(index.lookup(&Key(9, &calls)).is_empty()); - assert_eq!(index.lookup(&Key(10, &calls)), &[first]); - } -} - -use super::super::{identity::RowHandle, FastMap, HandleMap}; +use super::super::{identity::RowHandle, HandleMap, KeyTable}; -#[derive(Clone, Debug)] +/// Each key is stored once, in its bucket's slot; a row keeps that slot's id +/// and its position in the bucket, so retraction reaches the bucket with no +/// hashing and no key. pub struct HashIndex { - by_key: FastMap>, - key_of: HandleMap<(K, usize)>, + buckets: KeyTable>, + members: HandleMap<(u32, usize)>, retired: Vec>, } impl HashIndex where - K: Eq + Hash + Clone, + K: Eq + Hash, { pub fn new() -> HashIndex { HashIndex { - by_key: FastMap::default(), - key_of: HandleMap::new(), + buckets: KeyTable::new(), + members: HandleMap::new(), retired: Vec::new(), } } - /// Keep occupied buckets in place. Only empty buckets relinquish their - /// allocation to the pool; entry access hashes the owned key once. - fn remove_from_bucket(&mut self, handle: RowHandle, key: K, position: usize) { - if let std::collections::hash_map::Entry::Occupied(mut entry) = self.by_key.entry(key) { - let bucket = entry.get_mut(); - debug_assert_eq!(bucket[position], handle); - bucket.swap_remove(position); - if let Some(&moved) = bucket.get(position) { - self.key_of.get_mut(moved).expect("moved index member").1 = position; - } - if bucket.is_empty() { - self.retired.push(entry.remove()); - } - } - } - pub fn insert(&mut self, handle: RowHandle, key: K) { - // Refresh path reinserts live handles: drop the stale reverse link - // first so a changed key leaves no ghost bucket entry. - if self.key_of.get(handle).is_some_and(|(old, _)| *old == key) { - return; + // Refresh path reinserts live handles: an unchanged key is a no-op, + // and a changed key leaves no ghost bucket entry. + if let Some(&(id, _)) = self.members.get(handle) { + if *self.buckets.key(id) == key { + return; + } + self.remove(handle); } - self.remove(handle); - let bucket = self - .by_key - .entry(key.clone()) - .or_insert_with(|| self.retired.pop().unwrap_or_default()); + let retired = &mut self.retired; + let id = self + .buckets + .find_or_insert(key, || retired.pop().unwrap_or_default()); + let bucket = self.buckets.get_mut(id); let position = bucket.len(); bucket.push(handle); - self.key_of.insert(handle, (key, position)); + self.members.insert(handle, (id, position)); } /// Insert a fresh transient row without reverse retention. /// Only use for traversal indexes whose rows are never retracted. pub(crate) fn insert_transient(&mut self, handle: RowHandle, key: K) { - self.by_key - .entry(key) - .or_insert_with(|| self.retired.pop().unwrap_or_default()) - .push(handle); + let retired = &mut self.retired; + let id = self + .buckets + .find_or_insert(key, || retired.pop().unwrap_or_default()); + self.buckets.get_mut(id).push(handle); } pub fn remove(&mut self, handle: RowHandle) { - let Some((key, position)) = self.key_of.remove(handle) else { + let Some((id, position)) = self.members.remove(handle) else { return; }; - self.remove_from_bucket(handle, key, position); + let bucket = self.buckets.get_mut(id); + debug_assert_eq!(bucket[position], handle); + bucket.swap_remove(position); + if let Some(&moved) = bucket.get(position) { + self.members.get_mut(moved).expect("moved index member").1 = position; + } + if bucket.is_empty() { + self.retired.push(self.buckets.remove(id)); + } } pub fn clear(&mut self) { - self.by_key.clear(); - self.key_of.clear(); + self.buckets.clear(); + self.members.clear(); self.retired.clear(); } #[inline] pub fn lookup(&self, key: &K) -> &[RowHandle] { - self.by_key.get(key).map(Vec::as_slice).unwrap_or(&[]) + self.buckets + .find(key) + .map(|id| self.buckets.get(id).as_slice()) + .unwrap_or(&[]) + } + + /// Appends every row whose key hashes to `hash`: the rows of each key on + /// that hash's chain. + pub fn extend_hash(&self, hash: u64, out: &mut Vec) { + for bucket in self.buckets.with_hash(hash) { + out.extend_from_slice(bucket); + } } /// The retained key of one live row, for code that needs the key domain - /// (not just candidates) after the row is gone from other state. + /// (not just candidates) while the row is live. #[inline] pub fn key_of(&self, handle: RowHandle) -> Option<&K> { - self.key_of.get(handle).map(|(key, _)| key) + self.members + .get(handle) + .map(|&(id, _)| self.buckets.key(id)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + use std::hash::{Hash, Hasher}; + + #[derive(Clone)] + struct Key<'a>(u32, &'a Cell); + impl PartialEq for Key<'_> { + fn eq(&self, other: &Self) -> bool { + self.0 == other.0 + } + } + impl Eq for Key<'_> {} + impl Hash for Key<'_> { + fn hash(&self, hasher: &mut H) { + self.1.set(self.1.get() + 1); + self.0.hash(hasher); + } + } + + #[test] + fn retract_from_surviving_bucket_does_not_hash() { + let calls = Cell::new(0); + let mut index = HashIndex::new(); + let first = RowHandle::new(0, 0); + let second = RowHandle::new(1, 0); + index.insert(first, Key(7, &calls)); + index.insert(second, Key(7, &calls)); + calls.set(0); + index.remove(first); + assert_eq!( + calls.get(), + 0, + "retraction reaches the bucket by id, without hashing" + ); + assert_eq!(index.lookup(&Key(7, &calls)), &[second]); + index.remove(second); + assert!(index.lookup(&Key(7, &calls)).is_empty()); + index.insert(first, Key(9, &calls)); + index.insert(first, Key(10, &calls)); + assert!(index.lookup(&Key(9, &calls)).is_empty()); + assert_eq!(index.lookup(&Key(10, &calls)), &[first]); } } diff --git a/crates/solverforge-scoring/src/stream/relational/index/hashed.rs b/crates/solverforge-scoring/src/stream/relational/index/hashed.rs new file mode 100644 index 000000000..31a790723 --- /dev/null +++ b/crates/solverforge-scoring/src/stream/relational/index/hashed.rs @@ -0,0 +1,92 @@ +//! Hash-only index for one join side whose rows already own their keys. +//! +//! A grouped row's key lives in its group; copying it into a join index would +//! store it twice. This index keeps each row under its key's hash only, so a +//! probe may return rows of a colliding key, and the plan that owns it checks +//! keys on that probe direction. + +use super::super::{hash_key, identity::RowHandle, FastMap, HandleMap}; + +pub struct HashedIndex { + buckets: FastMap>, + members: HandleMap<(u64, usize)>, + retired: Vec>, +} + +impl HashedIndex { + pub fn new() -> HashedIndex { + HashedIndex { + buckets: FastMap::default(), + members: HandleMap::new(), + retired: Vec::new(), + } + } + + pub fn insert(&mut self, handle: RowHandle, hash: u64) { + if let Some(&(current, _)) = self.members.get(handle) { + if current == hash { + return; + } + self.remove(handle); + } + let retired = &mut self.retired; + let bucket = self + .buckets + .entry(hash) + .or_insert_with(|| retired.pop().unwrap_or_default()); + bucket.push(handle); + self.members.insert(handle, (hash, bucket.len() - 1)); + } + + /// Insert a fresh transient row without reverse retention. + /// Only use for traversal indexes whose rows are never retracted. + pub(crate) fn insert_transient(&mut self, handle: RowHandle, hash: u64) { + let retired = &mut self.retired; + self.buckets + .entry(hash) + .or_insert_with(|| retired.pop().unwrap_or_default()) + .push(handle); + } + + pub fn remove(&mut self, handle: RowHandle) { + let Some((hash, position)) = self.members.remove(handle) else { + return; + }; + let std::collections::hash_map::Entry::Occupied(mut entry) = self.buckets.entry(hash) + else { + return; + }; + let bucket = entry.get_mut(); + debug_assert_eq!(bucket[position], handle); + bucket.swap_remove(position); + if let Some(&moved) = bucket.get(position) { + self.members.get_mut(moved).expect("moved index member").1 = position; + } + if bucket.is_empty() { + self.retired.push(entry.remove()); + } + } + + pub fn clear(&mut self) { + self.buckets.clear(); + self.members.clear(); + self.retired.clear(); + } + + /// Rows whose key hashes like `key`: a superset of the rows keyed `key`. + #[inline] + pub fn lookup(&self, key: &K) -> &[RowHandle] { + self.lookup_hash(hash_key(key)) + } + + #[inline] + pub fn lookup_hash(&self, hash: u64) -> &[RowHandle] { + self.buckets.get(&hash).map(Vec::as_slice).unwrap_or(&[]) + } + + /// The key hash of one live row. + #[inline] + pub fn hash_of(&self, handle: RowHandle) -> Option { + self.members.get(handle).map(|&(hash, _)| hash) + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/index/interval.rs b/crates/solverforge-scoring/src/stream/relational/index/interval.rs index c808cf370..1c1471a09 100644 --- a/crates/solverforge-scoring/src/stream/relational/index/interval.rs +++ b/crates/solverforge-scoring/src/stream/relational/index/interval.rs @@ -9,7 +9,7 @@ pub struct IntervalIndex { ends: HandleMap, } -impl IntervalIndex { +impl IntervalIndex { pub fn new() -> Self { Self { starts: OrderedIndex::new(), diff --git a/crates/solverforge-scoring/src/stream/relational/index/mod.rs b/crates/solverforge-scoring/src/stream/relational/index/mod.rs index 6d64c4679..5288a1fa1 100644 --- a/crates/solverforge-scoring/src/stream/relational/index/mod.rs +++ b/crates/solverforge-scoring/src/stream/relational/index/mod.rs @@ -6,9 +6,11 @@ //! overlap conditions. Predicate scans need no index and stay explicit. mod hash; +mod hashed; mod interval; mod ordered; pub(crate) use hash::HashIndex; +pub(crate) use hashed::HashedIndex; pub(crate) use interval::IntervalIndex; pub(crate) use ordered::OrderedIndex; diff --git a/crates/solverforge-scoring/src/stream/relational/index/ordered.rs b/crates/solverforge-scoring/src/stream/relational/index/ordered.rs index b54af53ac..82514e666 100644 --- a/crates/solverforge-scoring/src/stream/relational/index/ordered.rs +++ b/crates/solverforge-scoring/src/stream/relational/index/ordered.rs @@ -1,53 +1,100 @@ -// Ordered candidate buckets with retained old keys for exact retraction. +// Ordered candidate buckets. Each key is stored once, in the ordered map; a +// row keeps only its bucket's slot, so retraction needs no key. A bucket left +// empty keeps its map entry, so a key that returns (the common churn of local +// search) reuses it; empty buckets are swept once they outnumber live ones. use std::collections::BTreeMap; -use std::ops::Bound::{Excluded, Included, Unbounded}; +use std::ops::Bound::{self, Excluded, Included, Unbounded}; use super::super::{HandleMap, RowHandle}; +/// Sweep empty buckets once they exceed live buckets by this many. +const SWEEP_SLACK: usize = 64; + #[derive(Debug)] pub struct OrderedIndex { - buckets: BTreeMap>, - keys: HandleMap, + slots: BTreeMap, + buckets: Vec>, + members: HandleMap, + /// Map entries whose bucket is empty. + empty: usize, + free: Vec, } -impl OrderedIndex { +impl OrderedIndex { pub fn new() -> Self { Self { - buckets: BTreeMap::new(), - keys: HandleMap::new(), + slots: BTreeMap::new(), + buckets: Vec::new(), + members: HandleMap::new(), + empty: 0, + free: Vec::new(), } } pub fn insert(&mut self, handle: RowHandle, key: K) { - if self.keys.get(handle) == Some(&key) { + let existing = self.slots.get(&key).copied(); + if existing.is_some() && self.members.get(handle).copied() == existing { return; } self.remove(handle); - self.keys.insert(handle, key.clone()); - self.buckets.entry(key).or_default().push(handle); + let slot = match existing { + Some(slot) => { + if self.buckets[slot as usize].is_empty() { + self.empty -= 1; + } + slot + } + None => { + let slot = match self.free.pop() { + Some(slot) => slot, + None => { + self.buckets.push(Vec::new()); + (self.buckets.len() - 1) as u32 + } + }; + self.slots.insert(key, slot); + slot + } + }; + self.buckets[slot as usize].push(handle); + self.members.insert(handle, slot); } pub fn remove(&mut self, handle: RowHandle) { - if let Some(key) = self.keys.remove(handle) { - if let Some(bucket) = self.buckets.get_mut(&key) { - bucket.retain(|h| *h != handle); - if bucket.is_empty() { - self.buckets.remove(&key); - } + let Some(slot) = self.members.remove(handle) else { + return; + }; + let bucket = &mut self.buckets[slot as usize]; + bucket.retain(|h| *h != handle); + if bucket.is_empty() { + self.empty += 1; + if self.empty > self.slots.len() - self.empty + SWEEP_SLACK { + self.sweep(); } } } + /// Drops every empty bucket's map entry and frees its slot. + fn sweep(&mut self) { + let buckets = &self.buckets; + let free = &mut self.free; + self.slots.retain(|_, slot| { + let live = !buckets[*slot as usize].is_empty(); + if !live { + free.push(*slot); + } + live + }); + self.empty = 0; + } + pub fn less_than(&self, key: &K, inclusive: bool) -> Vec { let bound = if inclusive { Included(key) } else { Excluded(key) }; - self.buckets - .range((Unbounded, bound)) - .flat_map(|(_, b)| b.iter().copied()) - .collect() + self.collect((Unbounded, bound)) } pub fn greater_than(&self, key: &K, inclusive: bool) -> Vec { @@ -56,14 +103,21 @@ impl OrderedIndex { } else { Excluded(key) }; - self.buckets - .range((bound, Unbounded)) - .flat_map(|(_, b)| b.iter().copied()) + self.collect((bound, Unbounded)) + } + + fn collect(&self, range: (Bound<&K>, Bound<&K>)) -> Vec { + self.slots + .range::(range) + .flat_map(|(_, slot)| self.buckets[*slot as usize].iter().copied()) .collect() } pub fn clear(&mut self) { + self.slots.clear(); self.buckets.clear(); - self.keys.clear(); + self.members.clear(); + self.empty = 0; + self.free.clear(); } } diff --git a/crates/solverforge-scoring/src/stream/relational/key_table.rs b/crates/solverforge-scoring/src/stream/relational/key_table.rs new file mode 100644 index 000000000..6add5ad68 --- /dev/null +++ b/crates/solverforge-scoring/src/stream/relational/key_table.rs @@ -0,0 +1,273 @@ +//! Keys stored once, each in its own slot, addressed by a dense id. +//! +//! Relational state keyed by a join key (index buckets, existence counts) used +//! to keep the key twice: once in its map and once per row, for retraction. +//! A `KeyTable` owns every key exactly once: rows keep the slot id, insertion +//! moves a new key in instead of cloning it, and retraction reaches the slot +//! by id with no hashing at all. A vacated slot is reused by the next new key. + +use std::hash::{BuildHasher, BuildHasherDefault, Hash}; + +use solverforge_core::fast_hash::FastHasher; + +use super::FastMap; + +const END: u32 = u32::MAX; + +/// The hash every key table and hash-only index uses for a key. +#[inline] +pub(crate) fn hash_key(key: &K) -> u64 { + BuildHasherDefault::::default().hash_one(key) +} + +#[derive(Clone)] +struct Slot { + key: K, + value: V, + hash: u64, + /// The next slot whose key has the same hash, or `END`. + next: u32, +} + +/// A live slot, or a vacated one linking to the next vacated slot. +#[derive(Clone)] +enum Entry { + Live(Slot), + Vacant(u32), +} + +#[derive(Clone)] +pub(crate) struct KeyTable { + slots: Vec>, + /// First slot of each hash chain. + heads: FastMap, + /// First vacated slot, threaded through the vacated entries, or `END`. + free: u32, + live: usize, +} + +impl KeyTable { + pub(crate) fn new() -> Self { + Self { + slots: Vec::new(), + heads: FastMap::default(), + free: END, + live: 0, + } + } + + pub(crate) fn clear(&mut self) { + self.slots.clear(); + self.heads.clear(); + self.free = END; + self.live = 0; + } + + #[inline] + fn slot(&self, id: u32) -> &Slot { + match &self.slots[id as usize] { + Entry::Live(slot) => slot, + Entry::Vacant(_) => panic!("live key slot"), + } + } + + #[inline] + fn slot_mut(&mut self, id: u32) -> &mut Slot { + match &mut self.slots[id as usize] { + Entry::Live(slot) => slot, + Entry::Vacant(_) => panic!("live key slot"), + } + } + + /// Every stored key with its value, in slot order. + pub(crate) fn iter(&self) -> impl Iterator { + self.slots.iter().filter_map(|entry| match entry { + Entry::Live(slot) => Some((&slot.key, &slot.value)), + Entry::Vacant(_) => None, + }) + } + + /// Every value whose key hashes to `hash`. + pub(crate) fn with_hash(&self, hash: u64) -> impl Iterator { + let mut next = self.heads.get(&hash).copied().unwrap_or(END); + std::iter::from_fn(move || { + if next == END { + return None; + } + let slot = self.slot(next); + next = slot.next; + Some(&slot.value) + }) + } + + /// The number of stored keys. + pub(crate) fn len(&self) -> usize { + self.live + } +} + +impl std::fmt::Debug for KeyTable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_map().entries(self.iter()).finish() + } +} + +impl KeyTable { + #[inline] + fn hash(key: &K) -> u64 { + hash_key(key) + } + + /// The id of `key`'s slot, if the table holds it. + #[inline] + pub(crate) fn find(&self, key: &K) -> Option { + let mut id = *self.heads.get(&Self::hash(key))?; + loop { + let slot = self.slot(id); + if slot.key == *key { + return Some(id); + } + if slot.next == END { + return None; + } + id = slot.next; + } + } + + /// The id of `key`'s slot, moving `key` into a new slot holding + /// `make()` when the table does not hold it yet. + #[inline] + pub(crate) fn find_or_insert(&mut self, key: K, make: impl FnOnce() -> V) -> u32 { + let hash = Self::hash(&key); + let head = self.heads.get(&hash).copied(); + let mut id = head.unwrap_or(END); + while id != END { + let slot = self.slot(id); + if slot.key == key { + return id; + } + id = slot.next; + } + let slot = Slot { + key, + value: make(), + hash, + next: head.unwrap_or(END), + }; + let id = if self.free == END { + self.slots.push(Entry::Live(slot)); + (self.slots.len() - 1) as u32 + } else { + let id = self.free; + let Entry::Vacant(next_free) = + std::mem::replace(&mut self.slots[id as usize], Entry::Live(slot)) + else { + unreachable!("free list holds vacated slots") + }; + self.free = next_free; + id + }; + self.live += 1; + self.heads.insert(hash, id); + id + } + + #[inline] + pub(crate) fn key(&self, id: u32) -> &K { + &self.slot(id).key + } + + #[inline] + pub(crate) fn get(&self, id: u32) -> &V { + &self.slot(id).value + } + + #[inline] + pub(crate) fn get_mut(&mut self, id: u32) -> &mut V { + &mut self.slot_mut(id).value + } + + /// Vacates `id`'s slot, dropping its key and returning its value. + pub(crate) fn remove(&mut self, id: u32) -> V { + let Entry::Live(slot) = + std::mem::replace(&mut self.slots[id as usize], Entry::Vacant(self.free)) + else { + panic!("live key slot") + }; + self.free = id; + self.live -= 1; + let head = self.heads.get_mut(&slot.hash).expect("key hash chain"); + if *head == id { + if slot.next == END { + self.heads.remove(&slot.hash); + } else { + *head = slot.next; + } + } else { + let mut previous = *head; + loop { + let link = self.slot_mut(previous); + if link.next == id { + link.next = slot.next; + break; + } + previous = link.next; + } + } + slot.value + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::hash::Hasher; + + /// A key whose hash ignores its second field, to force shared chains. + #[derive(Debug, PartialEq, Eq)] + struct Colliding(u32, u32); + impl Hash for Colliding { + fn hash(&self, hasher: &mut H) { + self.0.hash(hasher); + } + } + + #[test] + fn colliding_keys_share_a_chain_and_unlink_from_any_position() { + let mut table = KeyTable::new(); + let ids: Vec = (0..4) + .map(|n| table.find_or_insert(Colliding(7, n), || n)) + .collect(); + for (n, id) in ids.iter().enumerate() { + assert_eq!(table.find(&Colliding(7, n as u32)), Some(*id)); + assert_eq!(*table.get(*id), n as u32); + } + assert_eq!(table.remove(ids[1]), 1); + assert_eq!(table.remove(ids[3]), 3); + assert_eq!(table.find(&Colliding(7, 1)), None); + assert_eq!(table.find(&Colliding(7, 3)), None); + assert_eq!(table.find(&Colliding(7, 0)), Some(ids[0])); + assert_eq!(table.find(&Colliding(7, 2)), Some(ids[2])); + let reused = table.find_or_insert(Colliding(9, 0), || 9); + assert!( + reused == ids[1] || reused == ids[3], + "a vacated slot is reused" + ); + assert_eq!(table.key(reused), &Colliding(9, 0)); + assert_eq!(table.remove(ids[0]), 0); + assert_eq!(table.remove(ids[2]), 2); + assert_eq!(table.find(&Colliding(7, 0)), None); + assert_eq!(table.find(&Colliding(9, 0)), Some(reused)); + } + + #[test] + fn a_present_key_is_found_not_inserted() { + let mut table = KeyTable::new(); + let first = table.find_or_insert(String::from("a"), || 1); + let again = table.find_or_insert(String::from("a"), || 2); + assert_eq!(first, again); + assert_eq!(*table.get(first), 1); + *table.get_mut(first) += 10; + assert_eq!(*table.get(first), 11); + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/keyed_plan.rs b/crates/solverforge-scoring/src/stream/relational/keyed_plan.rs index fe489dda3..2687f9751 100644 --- a/crates/solverforge-scoring/src/stream/relational/keyed_plan.rs +++ b/crates/solverforge-scoring/src/stream/relational/keyed_plan.rs @@ -1,101 +1,53 @@ -//! Keyed equality plans: keyed probes and key readback for retained joins. +//! Keyed regain probes for retained complements. //! -//! `JoinNode` probes by rows. A complement's restore pass needs the same probe -//! by KEY: when a result row is removed, the targets that may regain their +//! `JoinNode` probes by rows. A complement's restore pass needs the probe by +//! KEY: when a result row is removed, the targets that may regain their //! default are the live left rows still indexed under the removed row's key. //! Capturing row handles at index time instead would replay stale handles after //! a target retracts and re-inserts (new generation on the same slot), skipping //! their defaults — traced as a retained-vs-full-evaluation divergence. The key -//! is stable where handles are not, so the node reads the removed row's key back -//! from its index and re-derives current target handles from the left index. +//! is stable where handles are not, so the node reads the removed row's key +//! back from its index and re-derives current target handles from the left +//! index. use crate::stream::joiner::plan::{EqualityPlan, IndexedPlan}; use crate::stream::relational::index::HashIndex; use crate::stream::relational::RowHandle; -use std::borrow::Cow; -pub trait KeyOf: IndexedPlan { - type Key: Eq + std::hash::Hash + Clone; - - /// Live left rows whose key matches `key`, straight from the left index. - fn left_candidates_by_key<'i>( +pub trait KeyedRegain: IndexedPlan { + /// Appends the live left rows indexed under the key of one live right + /// row. May include rows of a colliding key: the regain pass re-checks + /// every row it is given. + fn extend_left_rows_sharing_key( &self, - indexes: &'i Self::Indexes, - key: &Self::Key, - ) -> Cow<'i, [RowHandle]>; -} - -pub trait RightKeyOf: IndexedPlan { - type Key: Eq + std::hash::Hash + Clone; - - /// The retained key of one live right row, read back from its index. - fn right_row_key<'i>( - &self, - indexes: &'i Self::Indexes, - handle: RowHandle, - ) -> Option<&'i Self::Key>; -} - -/// Blanket over hash-indexed equality plans: both indexes are keyed by the -/// plan's own `EqualityPlan::Key`, so both probes are member lookups on the -/// index pair. Implemented per side through the shape traits below. -impl

KeyOf for P -where - P: EqualityPlan + IndexedPlan, - P::Key: 'static, - P::Indexes: LeftHashIndex, -{ - type Key = P::Key; - - #[inline] - fn left_candidates_by_key<'i>( - &self, - indexes: &'i Self::Indexes, - key: &P::Key, - ) -> Cow<'i, [RowHandle]> { - Cow::Borrowed(indexes.left_hash().lookup(key)) - } + indexes: &Self::Indexes, + right: RowHandle, + out: &mut Vec, + ); } -impl

RightKeyOf for P +/// Hash-indexed equality plans: both indexes are keyed by the plan's own +/// `EqualityPlan::Key`, so the probe reads the right row's retained key and +/// looks it up on the left. +impl

KeyedRegain for P where - P: EqualityPlan + IndexedPlan, - P::Key: 'static, - P::Indexes: RightHashIndex, + P: EqualityPlan + + IndexedPlan< + Indexes = ( + HashIndex<

::Key>, + HashIndex<

::Key>, + ), + >, { - type Key = P::Key; - #[inline] - fn right_row_key<'i>( + fn extend_left_rows_sharing_key( &self, - indexes: &'i Self::Indexes, - handle: RowHandle, - ) -> Option<&'i P::Key> { - indexes.right_hash().key_of(handle) - } -} - -/// The left/right index of a plan's `Indexes` pair is a `HashIndex` keyed by -/// K. Implemented only where the shape actually holds, so no structural -/// guessing. -pub trait LeftHashIndex { - fn left_hash(&self) -> &HashIndex; -} - -pub trait RightHashIndex { - fn right_hash(&self) -> &HashIndex; -} - -impl LeftHashIndex for (HashIndex, HashIndex) { - #[inline] - fn left_hash(&self) -> &HashIndex { - &self.0 - } -} - -impl RightHashIndex for (HashIndex, HashIndex) { - #[inline] - fn right_hash(&self) -> &HashIndex { - &self.1 + indexes: &Self::Indexes, + right: RowHandle, + out: &mut Vec, + ) { + if let Some(key) = indexes.1.key_of(right) { + out.extend_from_slice(indexes.0.lookup(key)); + } } } diff --git a/crates/solverforge-scoring/src/stream/relational/mod.rs b/crates/solverforge-scoring/src/stream/relational/mod.rs index f95816021..7bffb4793 100644 --- a/crates/solverforge-scoring/src/stream/relational/mod.rs +++ b/crates/solverforge-scoring/src/stream/relational/mod.rs @@ -10,6 +10,7 @@ mod handle_map; pub(crate) mod hash; mod identity; pub(crate) mod index; +mod key_table; pub(crate) mod keyed_plan; pub(crate) mod leaf_collector; pub mod operator; @@ -26,8 +27,9 @@ pub(crate) use hash::{FastMap, FastSet}; pub use identity::RowHandle; pub(crate) use identity::{BindingId, JoinedIdentity}; pub(crate) use index::HashIndex; +pub(crate) use key_table::{hash_key, KeyTable}; #[allow(unused_imports)] pub(crate) use row::Row; pub use row::{Concat, Leaf}; pub(crate) use storage::DenseRowStore; -pub use view_plan::{EntityKey, GroupKey, ViewKey}; +pub use view_plan::{EntityKey, GroupEqualPlan, GroupLeft, GroupRight, ViewKey}; diff --git a/crates/solverforge-scoring/src/stream/relational/operator.rs b/crates/solverforge-scoring/src/stream/relational/operator.rs index 37a657af7..27a544a73 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator.rs @@ -26,7 +26,7 @@ pub use merge::MergeNode; pub use project::{ProjectEvaluation, ProjectNode, ProjectView}; mod join; mod links; -pub use filter::{FilterNode, FilterPredicate}; +pub use filter::{AcceptAll, FilterNode, FilterPredicate}; pub use self_join::SelfJoinNode; #[doc(hidden)] diff --git a/crates/solverforge-scoring/src/stream/relational/operator/complement.rs b/crates/solverforge-scoring/src/stream/relational/operator/complement.rs index df1e9f146..be9277531 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/complement.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/complement.rs @@ -1,8 +1,7 @@ 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; -use crate::stream::relational::keyed_plan::{KeyOf, RightKeyOf}; +use crate::stream::relational::keyed_plan::KeyedRegain; use crate::stream::relational::{DenseRowStore, HandleMap, JoinedIdentity, RowHandle}; use std::marker::PhantomData; @@ -33,24 +32,23 @@ pub struct ComplementEvaluation { /// the equality plan's indexes directly — the same retention shape as /// `JoinNode`. Membership per se lives in the count-backed `ExistenceNode`; /// this node never reuses that engine. -pub struct ComplementNode< - S, - L, - R, - P: IndexedPlan + KeyOf + RightKeyOf::Key>, - F, - T, -> { +pub struct ComplementNode { targets: L, results: R, plan: P, indexes: P::Indexes, default: F, rows: DenseRowStore>, - real_outputs: FastMap, + /// The change that inserted each live target. A result row inserted by + /// the same change skips those targets: their own probe already paired + /// them with every indexed result, this one included. + target_changes: HandleMap, + change: u64, default_outputs: HandleMap, left_outputs: Links, right_outputs: Links, + /// Targets that may regain their default in the current event. + regain: Vec, /// Child notification scratch, reused across events (targets/results). child_l_removed: Vec, child_l_inserted: Vec, @@ -60,7 +58,7 @@ pub struct ComplementNode< } impl, R: Operator, P, F, T> ComplementNode where - P: IndexedPlan + KeyOf::Key> + RightKeyOf + 'static, + P: IndexedPlan + KeyedRegain + 'static, for<'a> P: ExecutablePlan, R::View<'a>>, F: for<'a> Fn(&S, &L::View<'a>) -> T, { @@ -81,10 +79,12 @@ where indexes, default, rows: DenseRowStore::new(), - real_outputs: FastMap::default(), + target_changes: HandleMap::new(), + change: 0, default_outputs: HandleMap::new(), left_outputs: Links::new(), right_outputs: Links::new(), + regain: Vec::new(), child_l_removed: Vec::new(), child_l_inserted: Vec::new(), child_r_removed: Vec::new(), @@ -151,6 +151,7 @@ where } = delta; for handle in left.iter().copied() { self.plan.remove_left(&mut self.indexes, handle); + self.target_changes.remove(handle); if let Some(mut outputs) = self.left_outputs.take(handle) { for h in outputs.drain(..) { if self.rows.get(h).is_some() { @@ -161,14 +162,16 @@ where self.left_outputs.restore(handle, outputs); } } - // Keys of the result rows this event removes, read back from the - // index before it drops them; their targets may regain a default - // after the removals and re-probes below. - let removed_keys: Vec<

::Key> = right - .iter() - .copied() - .filter_map(|handle| self.plan.right_row_key(&self.indexes, handle).cloned()) - .collect(); + // Targets sharing a key with a result row this event removes, read + // from the live indexes before the row leaves them: such a target may + // regain its default below. Targets inserted later in this event take + // their default from their own probe. + let mut regain = std::mem::take(&mut self.regain); + regain.clear(); + for handle in right.iter().copied() { + self.plan + .extend_left_rows_sharing_key(&self.indexes, handle, &mut regain); + } for handle in right.iter().copied() { self.plan.remove_right(&mut self.indexes, handle); if let Some(mut outputs) = self.right_outputs.take(handle) { @@ -181,9 +184,12 @@ where self.right_outputs.restore(handle, outputs); } } + self.change += 1; + let change = self.change; for handle in left_inserted.iter().copied() { if let Some(row) = self.targets.resolve(solution, handle) { self.plan.insert_left(&mut self.indexes, handle, &row); + self.target_changes.insert(handle, change); } } for handle in right_inserted.iter().copied() { @@ -194,21 +200,16 @@ where for handle in left_inserted.iter().copied() { // New target: emit its matching real rows, or its default. let candidates = self.target_candidates(&handle, solution); - let mut emitted = false; + let emitted = !candidates.is_empty(); for right in candidates { - if Self::emit_real( + Self::emit_real( &mut self.rows, - &mut self.real_outputs, &mut self.left_outputs, &mut self.right_outputs, handle, right, inserted, - ) - .is_some() - { - emitted = true; - } + ); } if !emitted { self.emit_default(solution, handle, inserted); @@ -225,9 +226,11 @@ where .iter() .copied() .filter(|&left| { - self.targets - .resolve(solution, left) - .is_some_and(|lrow| self.plan.candidate_matches(&lrow, &row)) + self.target_changes.get(left) != Some(&change) + && self + .targets + .resolve(solution, left) + .is_some_and(|lrow| self.plan.left_candidate_matches(&lrow, &row)) }) .collect(); for left in matches { @@ -238,7 +241,6 @@ where } Self::emit_real( &mut self.rows, - &mut self.real_outputs, &mut self.left_outputs, &mut self.right_outputs, left, @@ -247,26 +249,17 @@ where ); } } - // A target that lost its last real row regains its default. The - // candidates are re-derived from the live left index under the removed - // result rows' keys, so every current target generation is seen. - for key in removed_keys { - let owned: Vec = self - .plan - .left_candidates_by_key(&self.indexes, &key) - .iter() - .copied() - .collect(); - for left in owned { - let has_output = self - .left_outputs - .get(left) - .is_some_and(|outs| !outs.is_empty()); - if !has_output && self.targets.resolve(solution, left).is_some() { - self.emit_default(solution, left, inserted); - } + // A target that lost its last real row regains its default. + for left in regain.drain(..) { + let has_output = self + .left_outputs + .get(left) + .is_some_and(|outs| !outs.is_empty()); + if !has_output && self.targets.resolve(solution, left).is_some() { + self.emit_default(solution, left, inserted); } } + self.regain = regain; } fn target_candidates(&self, handle: &RowHandle, solution: &S) -> Vec { let Some(row) = self.targets.resolve(solution, *handle) else { @@ -279,7 +272,7 @@ where .filter(|&right| { self.results .resolve(solution, right) - .is_some_and(|rrow| self.plan.candidate_matches(&row, &rrow)) + .is_some_and(|rrow| self.plan.right_candidate_matches(&row, &rrow)) }) .collect() } @@ -288,7 +281,7 @@ impl< S: 'static, L: Operator, R: Operator, - P: IndexedPlan + KeyOf + RightKeyOf::Key> + 'static, + P: IndexedPlan + KeyedRegain + 'static, F: 'static, T: 'static, > Operator for ComplementNode @@ -331,7 +324,7 @@ where let mut matched = false; for &h in self.plan.right_candidates(&indexes, &left).iter() { let right = result_rows[h.slot() as usize]; - if self.plan.candidate_matches(&left, &right) { + if self.plan.right_candidate_matches(&left, &right) { matched = true; visitor(ComplementView::Real(Pair { left, right })); } @@ -351,7 +344,8 @@ where self.results.clear(); self.indexes = self.plan.new_indexes(); self.rows.clear(); - self.real_outputs.clear(); + self.target_changes.clear(); + self.change = 0; self.default_outputs.clear(); self.left_outputs.clear(); self.right_outputs.clear(); @@ -373,21 +367,16 @@ where for handle in self.targets.handles() { let candidates = self.target_candidates(&handle, solution); let mut inserted = Vec::new(); - let mut emitted = false; + let emitted = !candidates.is_empty(); for right in candidates { - if Self::emit_real( + Self::emit_real( &mut self.rows, - &mut self.real_outputs, &mut self.left_outputs, &mut self.right_outputs, handle, right, &mut inserted, - ) - .is_some() - { - emitted = true; - } + ); } if !emitted { self.emit_default(solution, handle, &mut inserted); @@ -450,7 +439,7 @@ impl< S: 'static, L: Operator, R: GroupedOperator, - P: IndexedPlan + KeyOf + RightKeyOf::Key> + 'static, + P: IndexedPlan + KeyedRegain + 'static, F: 'static, T: 'static, > GroupedOperator for ComplementNode diff --git a/crates/solverforge-scoring/src/stream/relational/operator/complement/explain.rs b/crates/solverforge-scoring/src/stream/relational/operator/complement/explain.rs index 37d194949..85e98119e 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/complement/explain.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/complement/explain.rs @@ -4,13 +4,13 @@ use super::super::{ComplementView, ExplainOperator, RowOrigin}; use super::{ComplementNode, OutputValue}; use crate::api::analysis::EntityRef; use crate::stream::joiner::plan::{ExecutablePlan, IndexedPlan}; -use crate::stream::relational::keyed_plan::{KeyOf, RightKeyOf}; +use crate::stream::relational::keyed_plan::KeyedRegain; impl< S: 'static, L: ExplainOperator, R: ExplainOperator, - P: IndexedPlan + KeyOf + RightKeyOf::Key> + 'static, + P: IndexedPlan + KeyedRegain + 'static, F: 'static, T: 'static, > ExplainOperator for ComplementNode 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 054e66f73..edd0053a1 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/complement/outputs.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/complement/outputs.rs @@ -3,7 +3,7 @@ use crate::stream::relational::operator::links::Links; impl, R: Operator, P, F, T> ComplementNode where - P: IndexedPlan + KeyOf::Key> + RightKeyOf + 'static, + P: IndexedPlan + KeyedRegain + 'static, for<'a> P: ExecutablePlan, R::View<'a>>, F: for<'a> Fn(&S, &L::View<'a>) -> T, { @@ -11,7 +11,6 @@ where if let Some(row) = self.rows.retract(h) { match row.value { OutputValue::Real(id) => { - self.real_outputs.remove(&id); if let Some(moved) = self.left_outputs .remove_link(id.left(), h, row.left_position) @@ -47,17 +46,13 @@ where pub(super) fn emit_real( rows: &mut DenseRowStore>, - outputs: &mut FastMap, left_outputs: &mut Links, right_outputs: &mut Links, left: RowHandle, right: RowHandle, inserted: &mut Vec, - ) -> Option { + ) { let id = JoinedIdentity::new(left, right, 0); - if outputs.contains_key(&id) { - return None; - } let left_bucket = left_outputs.bucket(left); let right_bucket = right_outputs.bucket(right); let h = rows.insert(Output { @@ -65,11 +60,9 @@ where left_position: left_bucket.len(), right_position: right_bucket.len(), }); - outputs.insert(id, h); left_bucket.push(h); right_bucket.push(h); inserted.push(h); - Some(h) } pub(super) fn emit_default( diff --git a/crates/solverforge-scoring/src/stream/relational/operator/existence.rs b/crates/solverforge-scoring/src/stream/relational/operator/existence.rs index 21fbeb2e7..e368cfc68 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/existence.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/existence.rs @@ -4,7 +4,7 @@ use super::{Operator, PairDelta}; use crate::api::analysis::EntityRef; use crate::stream::collection_extract::FlattenExtract; use crate::stream::collector::Accumulator; -use crate::stream::relational::count_state::KeyState; +use crate::stream::relational::count_state::{KeyId, KeyState}; use crate::stream::relational::view_plan::ViewKey; use crate::stream::relational::{FastMap, HandleMap, Leaf, RowHandle}; use std::hash::Hash; @@ -35,7 +35,6 @@ impl UnitKeys { impl RightKeySet for UnitKeys where VK: ViewKey + Send + Sync, - K: Clone, { type Key = K; @@ -62,7 +61,6 @@ impl RightKeySet> for ParentChildKeys where KB: Fn(&B) -> K + Send + Sync, F: FlattenExtract + Send + Sync, - K: Clone, { type Key = K; @@ -89,7 +87,7 @@ impl<'a, S: 'static, O: Operator, K, A: Accumulator, V, R, RK> RightKeySet> for GroupRightKeys where RK: Fn(&GroupView<'a, S, O, K, A, V, R>) -> K + Send + Sync, - K: Clone + 'static, + K: 'static, { type Key = K; @@ -117,18 +115,18 @@ pub struct ExistenceNode { keys: KeyState, /// Per-event keys whose counts changed, in first-touch order. /// Emptied by the membership pass at the end of every event. - touched: Vec, - /// Each right row's stored key contribution, for retraction without - /// re-deriving keys from mutated values. - right_stored: HandleMap>, - /// Each left row's current key. - left_keys: HandleMap, + touched: Vec, + /// Each right row's stored key contribution, as key ids, for retraction + /// without re-deriving keys from mutated values. + right_stored: HandleMap>, + /// Each left row's key id and position in that key's bucket. + left_keys: HandleMap<(KeyId, usize)>, /// Whether each left row is published (its key alive matches `exists`), /// mirrored by membership in `accepted`. accepted: HandleMap<()>, /// Contribution buffers retired by a right retraction, reused by the next /// insert so each row keeps one buffer for the life of the search. - retired: Vec>, + retired: Vec>, /// Per-event scratch for reading one row's key contribution. key_scratch: Vec, /// Reused per-event notification buffers (left/right, removed/inserted) @@ -148,7 +146,7 @@ pub struct ExistenceNode { } impl, R: Operator, K, LK, RK> ExistenceNode where - K: Eq + Hash + Clone + 'static, + K: Eq + Hash + 'static, for<'a> LK: ViewKey, Key = K>, for<'a> RK: RightKeySet, Key = K>, { @@ -249,9 +247,9 @@ where /// that flip, so an unchanged key's bucket is never copied. /// Applies one key's membership deltas to `self.accepted` and appends the /// flipped handles to the polarity scratch (`flip_ins` / `flip_rem`). - fn settle_key(&mut self, key: &K) { + fn settle_key(&mut self, key: KeyId) { let should = self.keys.alive(key) == self.exists; - let bucket: &[RowHandle] = self.keys.left_bucket(key).unwrap_or(&[]); + let bucket: &[RowHandle] = self.keys.left_bucket(key); for &h in bucket.iter() { let settled = self.accepted.get(h).is_some() == should; if !settled { @@ -280,8 +278,13 @@ where } = delta; // Retract left rows first so the membership pass only touches live rows. for h in left_removed.iter().copied() { - if let Some(key) = self.left_keys.remove(h) { - self.keys.left_remove(&key, h); + if let Some((key, position)) = self.left_keys.remove(h) { + if let Some(moved) = self.keys.left_remove(key, position) { + self.left_keys + .get_mut(moved) + .expect("moved existence row") + .1 = position; + } } if self.accepted.remove(h).is_some() { removed.push(h); @@ -291,7 +294,7 @@ where for h in right_removed.iter().copied() { if let Some(mut keys) = self.right_stored.remove(h) { for k in keys.drain(..) { - self.keys.take(&k, 1); + self.keys.take(k, 1); } keys.clear(); self.retired.push(keys); @@ -303,9 +306,12 @@ where }; let mut slot = self.retired.pop().unwrap_or_default(); slot.clear(); - self.right_keys.push_keys(&row, &mut slot); - for k in slot.iter() { - self.keys.add(k, 1); + self.key_scratch.clear(); + self.right_keys.push_keys(&row, &mut self.key_scratch); + for k in self.key_scratch.drain(..) { + let id = self.keys.intern(k); + self.keys.add(id, 1); + slot.push(id); } self.right_stored.insert(h, slot); } @@ -318,7 +324,8 @@ where self.flip_ins.clear(); self.flip_rem.clear(); for k in touched.drain(..) { - self.settle_key(&k); + self.settle_key(k); + self.keys.release_if_unused(k); } self.touched = touched; removed.extend_from_slice(&self.flip_rem); @@ -327,10 +334,10 @@ where let Some(row) = self.left.resolve(solution, h) else { continue; }; - let key = self.left_key.key(&row); - self.keys.left_insert(&key, h); - self.left_keys.insert(h, key.clone()); - if self.keys.alive(&key) == self.exists { + let key = self.keys.intern(self.left_key.key(&row)); + let position = self.keys.left_insert(key, h); + self.left_keys.insert(h, (key, position)); + if self.keys.alive(key) == self.exists { self.accepted.insert(h, ()); inserted.push(h); } @@ -340,7 +347,7 @@ where impl, R: Operator, K, LK, RK> Operator for ExistenceNode where - K: Eq + Hash + Clone + 'static, + K: Eq + Hash + 'static, LK: Send + Sync + 'static, RK: Send + Sync + 'static, for<'a> LK: ViewKey, Key = K>, @@ -367,8 +374,8 @@ where .visit_evaluation(solution, &evaluation.1, &mut |row| { scratch.clear(); right_keys.push_keys(&row, &mut scratch); - for k in scratch.iter() { - *counts.entry(k.clone()).or_insert(0) += 1; + for k in scratch.drain(..) { + *counts.entry(k).or_insert(0) += 1; } }); let left_key = &self.left_key; @@ -463,7 +470,7 @@ where impl, R: Operator, K, LK, RK> ExplainOperator for ExistenceNode where - K: Eq + Hash + Clone + 'static, + K: Eq + Hash + 'static, LK: Send + Sync + 'static, RK: Send + Sync + 'static, for<'a> LK: ViewKey, Key = K>, diff --git a/crates/solverforge-scoring/src/stream/relational/operator/filter.rs b/crates/solverforge-scoring/src/stream/relational/operator/filter.rs index eecb74db3..aaf2937f6 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/filter.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/filter.rs @@ -3,10 +3,27 @@ use super::Operator; /// A row predicate over a borrowed operator view. Named as a trait so a filter /// node's predicate type need not be a bare closure in an operator's type. pub trait FilterPredicate: Send + Sync { + /// `true` only for a predicate that accepts every row. An operator over + /// such a predicate skips resolving rows just to test them. + const ACCEPTS_ALL: bool = false; + /// Returns `true` when `row` passes. fn accepts(&self, solution: &S, row: &V) -> bool; } +/// The row filter that accepts every row: an unfiltered join. +#[derive(Clone, Copy, Debug, Default)] +pub struct AcceptAll; + +impl FilterPredicate for AcceptAll { + const ACCEPTS_ALL: bool = true; + + #[inline(always)] + fn accepts(&self, _: &S, _: &V) -> bool { + true + } +} + impl FilterPredicate for F where F: Fn(&S, &V) -> bool + Send + Sync, diff --git a/crates/solverforge-scoring/src/stream/relational/operator/join.rs b/crates/solverforge-scoring/src/stream/relational/operator/join.rs index 0b72b289b..ef2f322a7 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/join.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/join.rs @@ -1,26 +1,48 @@ -use super::super::{DenseRowStore, JoinedIdentity, RowHandle}; -use super::{links::Links, GroupedOperator, Operator, Pair, PairDelta}; +use super::super::{DenseRowStore, HandleMap, JoinedIdentity, RowHandle}; +use super::{links::Links, AcceptAll, FilterPredicate, GroupedOperator, Operator, Pair, PairDelta}; use super::{ExplainOperator, RowOrigin}; use crate::api::analysis::EntityRef; use crate::stream::joiner::plan::{CompileCondition, ExecutablePlan, IndexedPlan}; -use crate::stream::relational::hash::FastMap; use std::marker::PhantomData; +mod incremental; + struct JoinedRow { identity: JoinedIdentity, left_position: usize, right_position: usize, } +/// The change that last inserted a live input row. +/// +/// A pair is emitted twice in one change only when both of its rows were +/// inserted by that change: the left probe already paired the left row with +/// every indexed right row, so the right probe skips left rows stamped with +/// the current change. A row already live when it is inserted again keeps its +/// older stamp and is neither indexed nor probed a second time. +#[derive(Clone, Copy)] +struct Inserted { + change: u64, + probed: bool, +} + /// Join of two operators under a compiled plan `P`: one row per left/right pair -/// the plan matches. -pub struct JoinNode { +/// the plan matches and the row filter `F` accepts. +/// +/// The filter runs when a pair is found, before the pair is retained, so a +/// rejected pair costs one predicate call and nothing else. A pair's filter +/// verdict is fixed while both of its input rows stay live, exactly as for a +/// `FilterNode` over the join. +pub struct JoinNode { left: L, right: R, plan: P, + filter: F, indexes: P::Indexes, rows: DenseRowStore, - outputs: FastMap, + left_live: HandleMap, + right_live: HandleMap, + change: u64, left_outputs: Links, right_outputs: Links, /// Child notification scratch, reused across events (L/R, removed/inserted). @@ -37,15 +59,36 @@ where { /// Creates the node, compiling `condition` into its plan and indexes. pub fn new>(left: L, right: R, condition: C) -> Self { + Self::filtered(left, right, condition, AcceptAll) + } +} + +impl, R: Operator, P: IndexedPlan + 'static, F> + JoinNode +where + for<'a> P: ExecutablePlan, R::View<'a>>, + F: for<'a> FilterPredicate, R::View<'a>>> + 'static, +{ + /// Creates the node, compiling `condition` into its plan and indexes, and + /// retaining only the pairs `filter` accepts. + pub fn filtered>( + left: L, + right: R, + condition: C, + filter: F, + ) -> Self { let plan = condition.compile(); let indexes = plan.new_indexes(); Self { left, right, plan, + filter, indexes, rows: DenseRowStore::new(), - outputs: FastMap::default(), + left_live: HandleMap::new(), + right_live: HandleMap::new(), + change: 0, left_outputs: Links::new(), right_outputs: Links::new(), child_l_removed: Vec::new(), @@ -55,181 +98,39 @@ where marker: PhantomData, } } - fn apply_changes( - &mut self, - solution: &S, - delta: PairDelta<'_>, - removed: &mut Vec, - inserted: &mut Vec, - ) { - let PairDelta { - left_removed, - left_inserted, - right_removed, - right_inserted, - } = delta; - for handle in left_removed.iter().copied() { - self.plan.remove_left(&mut self.indexes, handle); - 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.restore(handle, outputs); - } - } - for handle in right_removed.iter().copied() { - self.plan.remove_right(&mut self.indexes, handle); - 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.restore(handle, outputs); - } - } - for handle in left_inserted.iter().copied() { - let row = self - .left - .resolve(solution, handle) - .expect("inserted left row"); - self.plan.insert_left(&mut self.indexes, handle, &row); - } - for handle in right_inserted.iter().copied() { - let row = self - .right - .resolve(solution, handle) - .expect("inserted right row"); - self.plan.insert_right(&mut self.indexes, handle, &row); - } - for handle in left_inserted.iter().copied() { - self.probe_left(solution, handle, &mut |h| inserted.push(h)); - } - for handle in right_inserted.iter().copied() { - self.probe_right(solution, handle, &mut |h| inserted.push(h)); - } - } - fn remove_output(&mut self, handle: RowHandle) { - if let Some(row) = self.rows.retract(handle) { - self.outputs.remove(&row.identity); - 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) = - self.right_outputs - .remove_link(row.identity.right(), handle, row.right_position) - { - self.rows - .get_mut(moved) - .expect("moved right output") - .right_position = row.right_position; - } - } - } } -impl, R: Operator, P: IndexedPlan + 'static> JoinNode -where - for<'a> P: ExecutablePlan, R::View<'a>>, -{ - fn emit_output( - rows: &mut DenseRowStore, - outputs: &mut FastMap, - left_outputs: &mut Links, - right_outputs: &mut Links, - left: RowHandle, - right: RowHandle, - ) -> Option { - let identity = JoinedIdentity::new(left, right, 0); - if outputs.contains_key(&identity) { - return None; - } - 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(), - right_position: right_bucket.len(), - }); - outputs.insert(identity, handle); - left_bucket.push(handle); - right_bucket.push(handle); - Some(handle) - } - #[inline(always)] - fn probe_left(&mut self, solution: &S, left: RowHandle, deltas: &mut impl FnMut(RowHandle)) { - let candidates = { - let Some(row) = self.left.resolve(solution, left) else { - return; - }; - self.plan.right_candidates(&self.indexes, &row) - }; - for &right in candidates.iter() { - let lv = self.left.resolve(solution, left).expect("live probe row"); - let rv = self - .right - .resolve(solution, right) - .expect("live candidate row"); - if !self.plan.candidate_matches(&lv, &rv) { - continue; - } - if let Some(h) = Self::emit_output( - &mut self.rows, - &mut self.outputs, - &mut self.left_outputs, - &mut self.right_outputs, - left, - right, - ) { - deltas(h); - } - } - } - #[inline(always)] - fn probe_right(&mut self, solution: &S, right: RowHandle, deltas: &mut impl FnMut(RowHandle)) { - let candidates = { - let Some(row) = self.right.resolve(solution, right) else { - return; - }; - self.plan.left_candidates(&self.indexes, &row) - }; - for &left in candidates.iter() { - let lv = self - .left - .resolve(solution, left) - .expect("live candidate row"); - let rv = self.right.resolve(solution, right).expect("live probe row"); - if !self.plan.candidate_matches(&lv, &rv) { - continue; - } - if let Some(h) = Self::emit_output( - &mut self.rows, - &mut self.outputs, - &mut self.left_outputs, - &mut self.right_outputs, - left, - right, - ) { - deltas(h); - } +impl JoinNode { + /// Replaces the row filter of a node that holds no rows yet; fluent + /// streams add their authored filter after the join is built. + pub(crate) fn with_filter(self, filter: G) -> JoinNode { + debug_assert!(self.rows.iter().next().is_none(), "filter set after rows"); + JoinNode { + left: self.left, + right: self.right, + plan: self.plan, + filter, + indexes: self.indexes, + rows: self.rows, + left_live: self.left_live, + right_live: self.right_live, + change: self.change, + left_outputs: self.left_outputs, + right_outputs: self.right_outputs, + child_l_removed: self.child_l_removed, + child_l_inserted: self.child_l_inserted, + child_r_removed: self.child_r_removed, + child_r_inserted: self.child_r_inserted, + marker: PhantomData, } } } -impl, R: Operator, P: IndexedPlan + 'static> Operator - for JoinNode +impl, R: Operator, P: IndexedPlan + 'static, F> Operator + for JoinNode where for<'a> P: ExecutablePlan, R::View<'a>>, + F: for<'a> FilterPredicate, R::View<'a>>> + 'static, { type View<'a> = Pair, R::View<'a>>; type Evaluation = (L::Evaluation, R::Evaluation); @@ -262,8 +163,11 @@ where .visit_evaluation(solution, &evaluation.0, &mut |left| { for &handle in self.plan.right_candidates(&indexes, &left).iter() { let right = right_rows[handle.slot() as usize]; - if self.plan.candidate_matches(&left, &right) { - visitor(Pair { left, right }); + if self.plan.right_candidate_matches(&left, &right) { + let row = Pair { left, right }; + if self.filter.accepts(solution, &row) { + visitor(row); + } } } }); @@ -273,7 +177,9 @@ where self.right.clear(); self.indexes = self.plan.new_indexes(); self.rows.clear(); - self.outputs.clear(); + self.left_live.clear(); + self.right_live.clear(); + self.change = 0; self.left_outputs.clear(); self.right_outputs.clear(); self.child_l_removed.clear(); @@ -287,11 +193,18 @@ where self.right.initialize(solution); self.indexes = self.plan.new_indexes(); self.rows.clear(); - self.outputs.clear(); + self.left_live.clear(); + self.right_live.clear(); + self.change = 0; self.left_outputs.clear(); self.right_outputs.clear(); + let initial = Inserted { + change: 0, + probed: true, + }; for handle in self.left.handles() { let row = self.left.resolve(solution, handle).expect("live left row"); + self.left_live.insert(handle, initial); self.plan.insert_left(&mut self.indexes, handle, &row); } for handle in self.right.handles() { @@ -299,6 +212,7 @@ where .right .resolve(solution, handle) .expect("live right row"); + self.right_live.insert(handle, initial); self.plan.insert_right(&mut self.indexes, handle, &row); } for handle in self.left.handles() { @@ -402,20 +316,22 @@ where } } -impl, R: Operator, P: IndexedPlan + 'static> GroupedOperator - for JoinNode +impl, R: Operator, P: IndexedPlan + 'static, F> + GroupedOperator for JoinNode where for<'a> P: ExecutablePlan, R::View<'a>>, + F: for<'a> FilterPredicate, R::View<'a>>> + 'static, { fn changed_group_count(&self) -> usize { self.left.changed_group_count() } } -impl, R: ExplainOperator, P: IndexedPlan + 'static> - ExplainOperator for JoinNode +impl, R: ExplainOperator, P: IndexedPlan + 'static, F> + ExplainOperator for JoinNode where for<'a> P: ExecutablePlan, R::View<'a>>, + F: for<'a> FilterPredicate, R::View<'a>>> + 'static, { fn explain( &self, diff --git a/crates/solverforge-scoring/src/stream/relational/operator/join/incremental.rs b/crates/solverforge-scoring/src/stream/relational/operator/join/incremental.rs new file mode 100644 index 000000000..49ad7fbbb --- /dev/null +++ b/crates/solverforge-scoring/src/stream/relational/operator/join/incremental.rs @@ -0,0 +1,236 @@ +//! Incremental maintenance of a join's retained pairs. + +use super::{Inserted, JoinNode, JoinedRow}; +use crate::stream::joiner::plan::{ExecutablePlan, IndexedPlan}; +use crate::stream::relational::operator::{ + links::Links, FilterPredicate, Operator, Pair, PairDelta, +}; +use crate::stream::relational::{DenseRowStore, HandleMap, JoinedIdentity, RowHandle}; + +impl, R: Operator, P: IndexedPlan + 'static, F> + JoinNode +where + for<'a> P: ExecutablePlan, R::View<'a>>, + F: for<'a> FilterPredicate, R::View<'a>>> + 'static, +{ + pub(super) fn apply_changes( + &mut self, + solution: &S, + delta: PairDelta<'_>, + removed: &mut Vec, + inserted: &mut Vec, + ) { + let PairDelta { + left_removed, + left_inserted, + right_removed, + right_inserted, + } = delta; + for handle in left_removed.iter().copied() { + self.plan.remove_left(&mut self.indexes, handle); + self.left_live.remove(handle); + 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.restore(handle, outputs); + } + } + for handle in right_removed.iter().copied() { + self.plan.remove_right(&mut self.indexes, handle); + self.right_live.remove(handle); + 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.restore(handle, outputs); + } + } + if left_inserted.is_empty() && right_inserted.is_empty() { + return; + } + self.change += 1; + let change = self.change; + let fresh = Inserted { + change, + probed: false, + }; + for handle in left_inserted.iter().copied() { + if self.left_live.get(handle).is_some() { + continue; + } + self.left_live.insert(handle, fresh); + let row = self + .left + .resolve(solution, handle) + .expect("inserted left row"); + self.plan.insert_left(&mut self.indexes, handle, &row); + } + for handle in right_inserted.iter().copied() { + if self.right_live.get(handle).is_some() { + continue; + } + self.right_live.insert(handle, fresh); + let row = self + .right + .resolve(solution, handle) + .expect("inserted right row"); + self.plan.insert_right(&mut self.indexes, handle, &row); + } + for handle in left_inserted.iter().copied() { + if Self::take_probe(&mut self.left_live, handle, change) { + self.probe_left(solution, handle, &mut |h| inserted.push(h)); + } + } + for handle in right_inserted.iter().copied() { + if Self::take_probe(&mut self.right_live, handle, change) { + self.probe_right(solution, handle, change, &mut |h| inserted.push(h)); + } + } + } + /// Whether `handle` was inserted by `change` and not yet probed; marks it + /// probed so a handle listed twice in one change probes once. + #[inline] + fn take_probe(live: &mut HandleMap, handle: RowHandle, change: u64) -> bool { + match live.get_mut(handle) { + Some(stamp) if stamp.change == change && !stamp.probed => { + stamp.probed = true; + true + } + _ => false, + } + } + fn remove_output(&mut self, handle: RowHandle) { + if let Some(row) = self.rows.retract(handle) { + 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) = + self.right_outputs + .remove_link(row.identity.right(), handle, row.right_position) + { + self.rows + .get_mut(moved) + .expect("moved right output") + .right_position = row.right_position; + } + } + } + + fn emit_output( + rows: &mut DenseRowStore, + left_outputs: &mut Links, + right_outputs: &mut Links, + left: RowHandle, + right: RowHandle, + ) -> RowHandle { + let identity = JoinedIdentity::new(left, right, 0); + 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(), + right_position: right_bucket.len(), + }); + left_bucket.push(handle); + right_bucket.push(handle); + handle + } + #[inline(always)] + pub(super) fn probe_left( + &mut self, + solution: &S, + left: RowHandle, + deltas: &mut impl FnMut(RowHandle), + ) { + let candidates = { + let Some(row) = self.left.resolve(solution, left) else { + return; + }; + self.plan.right_candidates(&self.indexes, &row) + }; + for &right in candidates.iter() { + let lv = self.left.resolve(solution, left).expect("live probe row"); + let rv = self + .right + .resolve(solution, right) + .expect("live candidate row"); + if !self.plan.right_candidate_matches(&lv, &rv) { + continue; + } + let row = Pair { + left: lv, + right: rv, + }; + if !self.filter.accepts(solution, &row) { + continue; + } + deltas(Self::emit_output( + &mut self.rows, + &mut self.left_outputs, + &mut self.right_outputs, + left, + right, + )); + } + } + #[inline(always)] + fn probe_right( + &mut self, + solution: &S, + right: RowHandle, + change: u64, + deltas: &mut impl FnMut(RowHandle), + ) { + let candidates = { + let Some(row) = self.right.resolve(solution, right) else { + return; + }; + self.plan.left_candidates(&self.indexes, &row) + }; + for &left in candidates.iter() { + // The left probe of this change already emitted this pair. + if self + .left_live + .get(left) + .is_some_and(|stamp| stamp.change == change) + { + continue; + } + let lv = self + .left + .resolve(solution, left) + .expect("live candidate row"); + let rv = self.right.resolve(solution, right).expect("live probe row"); + if !self.plan.left_candidate_matches(&lv, &rv) { + continue; + } + let row = Pair { + left: lv, + right: rv, + }; + if !self.filter.accepts(solution, &row) { + continue; + } + deltas(Self::emit_output( + &mut self.rows, + &mut self.left_outputs, + &mut self.right_outputs, + left, + right, + )); + } + } +} diff --git a/crates/solverforge-scoring/src/stream/relational/operator/joiner_existence.rs b/crates/solverforge-scoring/src/stream/relational/operator/joiner_existence.rs index 4f88a7ee3..f2665a176 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/joiner_existence.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/joiner_existence.rs @@ -143,7 +143,7 @@ where .right .resolve(solution, right) .expect("live semi-join candidate"); - if self.plan.candidate_matches(&row, &r) { + if self.plan.right_candidate_matches(&row, &r) { matches.push(right); } } @@ -164,7 +164,7 @@ where .left .resolve(solution, left) .expect("live semi-join candidate"); - if self.plan.candidate_matches(&l, &row) { + if self.plan.left_candidate_matches(&l, &row) { matches.push(left); } } @@ -281,7 +281,7 @@ where .visit_evaluation(solution, &evaluation.0, &mut |left| { let matched = self.plan.right_candidates(&indexes, &left).iter().any(|h| { self.plan - .candidate_matches(&left, &right_rows[h.slot() as usize]) + .right_candidate_matches(&left, &right_rows[h.slot() as usize]) }); if matched == self.exists { visitor(left); diff --git a/crates/solverforge-scoring/src/stream/relational/operator/links.rs b/crates/solverforge-scoring/src/stream/relational/operator/links.rs index 7323554ba..29ee62533 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/links.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/links.rs @@ -1,5 +1,11 @@ +use smallvec::SmallVec; + use crate::stream::relational::{HandleMap, RowHandle}; +/// One input row's output links. Most rows link to one or two outputs, which +/// live inline, so a row's first links allocate nothing. +pub(super) type LinkBucket = SmallVec<[T; 2]>; + /// Output links of each input row, kept in place across notifications. /// /// A row that leaves and re-enters a node on every move would otherwise drop @@ -8,7 +14,7 @@ use crate::stream::relational::{HandleMap, RowHandle}; /// takes the bucket over, so steady-state notification allocates nothing and /// holds no memory beyond one bucket per slot. pub(super) struct Links { - buckets: HandleMap>, + buckets: HandleMap>, } impl Links { @@ -22,31 +28,28 @@ impl Links { self.buckets.clear(); } - pub(super) fn get(&self, input: RowHandle) -> Option<&Vec> { + pub(super) fn get(&self, input: RowHandle) -> Option<&LinkBucket> { 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`, taking over the bucket a stale handle of the /// same slot left behind. #[inline] - pub(super) fn bucket(&mut self, input: RowHandle) -> &mut Vec { - self.buckets.get_or_reuse(input, Vec::new, Vec::clear) + pub(super) fn bucket(&mut self, input: RowHandle) -> &mut LinkBucket { + self.buckets + .get_or_reuse(input, SmallVec::new, SmallVec::clear) } /// Detaches the links of `input`, leaving its slot empty until /// [`Links::restore`] hands the bucket back. #[inline] - pub(super) fn take(&mut self, input: RowHandle) -> Option> { + pub(super) fn take(&mut self, input: RowHandle) -> Option> { self.buckets.get_mut(input).map(std::mem::take) } /// Puts a detached bucket back into the slot of `input`, emptied. #[inline] - pub(super) fn restore(&mut self, input: RowHandle, mut bucket: Vec) { + pub(super) fn restore(&mut self, input: RowHandle, mut bucket: LinkBucket) { bucket.clear(); if let Some(slot) = self.buckets.get_mut(input) { *slot = bucket; 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 5c36581da..32e6cbd2b 100644 --- a/crates/solverforge-scoring/src/stream/relational/operator/self_join.rs +++ b/crates/solverforge-scoring/src/stream/relational/operator/self_join.rs @@ -10,11 +10,11 @@ //! each member's own provenance. use super::links::Links; -use super::Operator; +use super::{AcceptAll, FilterPredicate, Operator}; use super::{ExplainOperator, RowOrigin}; use crate::api::analysis::EntityRef; use crate::stream::key_extract::KeyExtract; -use crate::stream::relational::{DenseRowStore, FastMap, HandleMap, Leaf, RowHandle}; +use crate::stream::relational::{DenseRowStore, FastMap, HandleMap, KeyTable, Leaf, RowHandle}; use std::marker::PhantomData; /// Enumerates every increasing `N`-combination of `items` (already index-sorted). @@ -46,44 +46,72 @@ fn combinations_with( target: usize, mut emit: impl FnMut([T; N]), ) { - let others: Vec = (0..items.len()).filter(|p| *p != target).collect(); - let mut picks: [usize; N] = [0; N]; - picks[N - 1] = target; fn rec( items: &[T], - others: &[usize], + target: usize, start: usize, depth: usize, picks: &mut [usize; N], emit: &mut impl FnMut([T; N]), ) { - if depth == N - 1 { - let mut ordered = *picks; - ordered.sort_unstable(); + if depth + 1 == N { + let mut ordered = [target; N]; + let mut placed = false; + let mut at = 0; + for &pick in &picks[..N - 1] { + if !placed && target < pick { + ordered[at] = target; + at += 1; + placed = true; + } + ordered[at] = pick; + at += 1; + } emit(std::array::from_fn(|i| items[ordered[i]])); return; } - for i in start..others.len() { - picks[depth] = others[i]; - rec(items, others, i + 1, depth + 1, picks, emit); + for position in start..items.len() { + if position == target { + continue; + } + picks[depth] = position; + rec(items, target, position + 1, depth + 1, picks, emit); } } - rec(items, &others, 0, 0, &mut picks, &mut emit); + let mut picks = [0; N]; + rec(items, target, 0, 0, &mut picks, &mut emit); +} + +/// One retained combination: its member handles in index order, and the +/// position of this row in each member's link list. +struct SelfRow { + tuple: [RowHandle; N], + positions: [usize; N], } /// Same-collection join of arity `N`: one row per increasing index -/// combination of `N` input rows whose keys `KE` are equal. +/// combination of `N` input rows whose keys `KE` are equal and that the row +/// filter `F` accepts. /// -/// The view is `[Leaf<'a, A>; N]` in index order. -pub struct SelfJoinNode { +/// The view is `[Leaf<'a, A>; N]` in index order. The filter runs when a +/// combination is found, before it is retained, so a rejected combination is +/// never stored. +pub struct SelfJoinNode { input: O, key: KE, - /* Key bucket: source index plus handle, kept sorted by index. */ - by_key: FastMap>, - handle_index: HandleMap, - rows: DenseRowStore<[RowHandle; N]>, - combos: FastMap<[RowHandle; N], RowHandle>, - of_input: Links<[RowHandle; N]>, + filter: F, + /* Key bucket: source index plus handle, kept sorted by index. Each key + is stored once, in its bucket's slot. */ + by_key: KeyTable>, + /// Bucket slot and source index of each live input row, so retraction + /// reaches its bucket entry without re-deriving or hashing the key. + members: HandleMap<(u32, usize)>, + /// Emptied buckets, reused by the next new key. + retired: Vec>, + rows: DenseRowStore>, + of_input: Links, + /// Bucket handles of the row being inserted, reused across events. + bucket_scratch: Vec, /// Child notification scratch, reused across events. child_removed: Vec, child_inserted: Vec, @@ -93,14 +121,24 @@ pub struct SelfJoinNode { impl SelfJoinNode { /// Creates the node over `input`, keying rows with `key`. pub fn new(input: O, key: KE) -> Self { + Self::filtered(input, key, AcceptAll) + } +} + +impl SelfJoinNode { + /// Creates the node over `input`, keying rows with `key` and retaining + /// only the combinations `filter` accepts. + pub fn filtered(input: O, key: KE, filter: F) -> Self { Self { input, key, - by_key: FastMap::default(), - handle_index: HandleMap::new(), + filter, + by_key: KeyTable::new(), + members: HandleMap::new(), + retired: Vec::new(), rows: DenseRowStore::new(), - combos: FastMap::default(), of_input: Links::new(), + bucket_scratch: Vec::new(), child_removed: Vec::new(), child_inserted: Vec::new(), marker: PhantomData, @@ -108,14 +146,15 @@ impl SelfJoinNode { } } -impl Operator for SelfJoinNode +impl Operator for SelfJoinNode where S: Send + Sync + 'static, A: 'static, O: Operator, for<'a> O: Operator = Leaf<'a, A>>, - K: Eq + std::hash::Hash + Clone + Send + Sync + 'static, + K: Eq + std::hash::Hash + Send + Sync + 'static, KE: KeyExtract + 'static, + F: for<'a> FilterPredicate; N]> + 'static, { type View<'a> = [Leaf<'a, A>; N]; type Evaluation = O::Evaluation; @@ -143,7 +182,9 @@ where let mut found: Vec<[Leaf<'a, A>; N]> = Vec::new(); all_combinations(bucket, |tuple| found.push(tuple)); for tuple in found { - visitor(tuple); + if self.filter.accepts(solution, &tuple) { + visitor(tuple); + } } } } @@ -151,9 +192,9 @@ where fn clear(&mut self) { self.input.clear(); self.by_key.clear(); - self.handle_index.clear(); + self.members.clear(); + self.retired.clear(); self.rows.clear(); - self.combos.clear(); self.of_input.clear(); self.child_removed.clear(); self.child_inserted.clear(); @@ -163,7 +204,7 @@ where self.clear(); self.input.initialize(solution); for handle in self.input.handles() { - self.insert_row(solution, handle); + self.insert_row(solution, handle, &mut |_| {}); } } @@ -172,15 +213,15 @@ where } fn resolve<'a>(&'a self, solution: &'a S, handle: RowHandle) -> Option> { - let tuple = *self.rows.get(handle)?; + let tuple = self.rows.get(handle)?.tuple; self.view(solution, &tuple) } fn visit_provenance(&self, handle: RowHandle, visitor: &mut impl FnMut(u32, usize, usize)) { - let Some(tuple) = self.rows.get(handle) else { + let Some(row) = self.rows.get(handle) else { return; }; - for input in tuple { + for input in &row.tuple { self.input.visit_provenance(*input, visitor); } } @@ -206,7 +247,7 @@ where &mut in_inserted, ); for handle in in_removed.drain(..) { - removed.extend(self.retract_row(handle)); + self.retract_row(handle, removed); } self.child_removed = in_removed; self.child_inserted = in_inserted; @@ -233,21 +274,22 @@ where &mut in_inserted, ); for handle in in_inserted.drain(..) { - inserted.extend(self.insert_row(solution, handle)); + self.insert_row(solution, handle, &mut |h| inserted.push(h)); } self.child_removed = in_removed; self.child_inserted = in_inserted; } } -impl SelfJoinNode +impl SelfJoinNode where S: Send + Sync + 'static, A: 'static, O: Operator, for<'a> O: Operator = Leaf<'a, A>>, - K: Eq + std::hash::Hash + Clone + Send + Sync + 'static, + K: Eq + std::hash::Hash + Send + Sync + 'static, KE: KeyExtract + 'static, + F: for<'a> FilterPredicate; N]> + 'static, { fn view<'a>(&'a self, solution: &'a S, tuple: &[RowHandle; N]) -> Option<[Leaf<'a, A>; N]> { let mut out = Vec::with_capacity(N); @@ -257,86 +299,104 @@ where out.try_into().ok() } - /// Removes one input row's combinations, unlinks its tuples, and returns - /// the retracted handles. - fn retract_row(&mut self, handle: RowHandle) -> Vec { - let mut removed = Vec::new(); - 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 { - if member != handle { - if let Some(list) = self.of_input.get_mut(member) { - list.retain(|t| *t != tuple); - } + /// Removes one input row's combinations, unlinks them from their other + /// members, and records the retracted handles. + fn retract_row(&mut self, handle: RowHandle, removed: &mut Vec) { + let Some((id, index)) = self.members.remove(handle) else { + return; + }; + if let Some(mut outputs) = self.of_input.take(handle) { + for output in outputs.drain(..) { + let Some(row) = self.rows.retract(output) else { + continue; + }; + for (at, member) in row.tuple.iter().copied().enumerate() { + if member == handle { + continue; + } + if let Some(moved) = + self.of_input.remove_link(member, output, row.positions[at]) + { + let moved_row = self.rows.get_mut(moved).expect("moved self-join output"); + let slot = moved_row + .tuple + .iter() + .position(|m| *m == member) + .expect("moved output keeps its member"); + moved_row.positions[slot] = row.positions[at]; } } removed.push(output); } + self.of_input.restore(handle, outputs); } - self.of_input.restore(handle, tuples); - if let Some(index) = self.handle_index.remove(handle) { - if let Some(key) = self - .by_key - .keys() - .find(|k| { - self.by_key - .get(*k) - .is_some_and(|b| b.iter().any(|(i, _)| *i == index)) - }) - .cloned() - { - if let Some(bucket) = self.by_key.get_mut(&key) { - bucket.retain(|(i, _)| *i != index); - if bucket.is_empty() { - self.by_key.remove(&key); - } - } - } + let bucket = self.by_key.get_mut(id); + let at = bucket.partition_point(|(i, _)| *i < index); + debug_assert_eq!(bucket[at].1, handle); + bucket.remove(at); + if bucket.is_empty() { + self.retired.push(self.by_key.remove(id)); } - removed } - fn insert_row(&mut self, solution: &S, handle: RowHandle) -> Vec { + /// Indexes one input row and emits every combination it completes. Rows + /// inserted earlier in the same event are already in the bucket and rows + /// inserted later are not, so each combination is emitted exactly once; a + /// row that is already live is a no-op. + fn insert_row(&mut self, solution: &S, handle: RowHandle, emit: &mut impl FnMut(RowHandle)) { + if self.members.get(handle).is_some() { + return; + } let Some(leaf) = self.input.resolve(solution, handle) else { - return Vec::new(); + return; }; let index = leaf.index; let key = self.key.extract(solution, leaf.entity, index); - self.handle_index.insert(handle, index); - let bucket = self.by_key.entry(key).or_default(); - let at = bucket.partition_point(|(i, _)| *i < index); - bucket.insert(at, (index, handle)); - let handles: Vec = bucket.iter().map(|(_, h)| *h).collect(); - let target = at; - - let mut found: Vec<[RowHandle; N]> = Vec::new(); - combinations_with(&handles, target, |tuple| found.push(tuple)); - - let mut inserted = Vec::new(); - for tuple in found { - if self.combos.contains_key(&tuple) { - continue; + let retired = &mut self.retired; + let id = self + .by_key + .find_or_insert(key, || retired.pop().unwrap_or_default()); + let bucket = self.by_key.get_mut(id); + let target = bucket.partition_point(|(i, _)| *i < index); + bucket.insert(target, (index, handle)); + let mut handles = std::mem::take(&mut self.bucket_scratch); + handles.clear(); + handles.extend(bucket.iter().map(|(_, h)| *h)); + self.members.insert(handle, (id, index)); + let rows = &mut self.rows; + let links = &mut self.of_input; + let input = &self.input; + let filter = &self.filter; + combinations_with(&handles, target, |tuple: [RowHandle; N]| { + if !F::ACCEPTS_ALL { + let mut views = [None; N]; + for (view, member) in views.iter_mut().zip(tuple) { + *view = input.resolve(solution, member); + } + let views = views.map(|view| view.expect("live combination member")); + if !filter.accepts(solution, &views) { + return; + } } - let output = self.rows.insert(tuple); - self.combos.insert(tuple, output); + let positions = tuple.map(|member| links.bucket(member).len()); + let output = rows.insert(SelfRow { tuple, positions }); for member in tuple { - self.of_input.bucket(member).push(tuple); + links.bucket(member).push(output); } - inserted.push(output); - } - inserted + emit(output); + }); + self.bucket_scratch = handles; } } -impl ExplainOperator for SelfJoinNode +impl ExplainOperator for SelfJoinNode where + F: for<'a> FilterPredicate; N]> + 'static, S: Send + Sync + 'static, A: 'static, O: ExplainOperator, for<'a> O: Operator = Leaf<'a, A>>, - K: Eq + std::hash::Hash + Clone + Send + Sync + 'static, + K: Eq + std::hash::Hash + Send + Sync + 'static, KE: KeyExtract + 'static, { fn explain( @@ -348,7 +408,7 @@ where ) { let inputs = match origin { RowOrigin::Retained(handle) => match self.rows.get(handle) { - Some(inputs) => inputs.map(RowOrigin::Retained), + Some(row) => row.tuple.map(RowOrigin::Retained), None => return, }, RowOrigin::Evaluation(evaluation) => [RowOrigin::Evaluation(evaluation); N], diff --git a/crates/solverforge-scoring/src/stream/relational/view_plan.rs b/crates/solverforge-scoring/src/stream/relational/view_plan.rs index 594c9dc67..b9d2eef95 100644 --- a/crates/solverforge-scoring/src/stream/relational/view_plan.rs +++ b/crates/solverforge-scoring/src/stream/relational/view_plan.rs @@ -5,7 +5,8 @@ //! entity off a leaf, `ChildKey` reads a flattened child, `PairKey` composes two //! keys over one view, and `FlattenedPairKey` composes the owning entity's key //! with the flattened child's key. `ViewEqualPlan` is the typed-hash-equality -//! plan over any two such keys. +//! plan over any two such keys; `GroupEqualPlan` matches a grouped row's own +//! key without copying it. #![allow(dead_code)] // PairKey/FlattenedPairKey used by the flattened_bi port @@ -19,6 +20,9 @@ use super::{Leaf, RowHandle}; use crate::stream::joiner::plan::{CompileCondition, EqualityKind, ExecutablePlan, IndexedPlan}; use crate::stream::joiner::Joiner; +mod group; +pub use group::{GroupEqualPlan, GroupLeft, GroupRight}; + /// Reads a join key out of an operator view. pub trait ViewKey { /// The key type. @@ -120,24 +124,6 @@ where } } -/// Reads a grouped row's own key, for matching against a target domain. -pub struct GroupKey; - -impl ViewKey> for GroupKey -where - S: 'static, - O: super::operator::Operator, - K: Clone, - A: super::super::collector::Accumulator, -{ - type Key = K; - - #[inline] - fn key(&self, view: &super::operator::GroupView<'_, S, O, K, A, V, R>) -> K { - view.key.clone() - } -} - /// Typed hash-equality plan over two named view keys. pub struct ViewEqualPlan { key_a: KeyA, @@ -163,7 +149,7 @@ impl CompileCondition for ViewEqualPlan { } } -impl crate::stream::joiner::plan::EqualityPlan +impl crate::stream::joiner::plan::EqualityPlan for ViewEqualPlan { type Key = K; @@ -172,7 +158,7 @@ impl crate::stream::joiner::plan::EqualityPlan impl<'x, A, B, K, KeyA, KeyB> crate::stream::joiner::plan::EqualityKeys, Leaf<'x, B>> for ViewEqualPlan where - K: Eq + Hash + Clone, + K: Eq + Hash, KeyA: ViewKey, Key = K>, KeyB: ViewKey, Key = K>, { @@ -184,7 +170,7 @@ where } } -impl IndexedPlan for ViewEqualPlan { +impl IndexedPlan for ViewEqualPlan { type Kind = EqualityKind; type Indexes = (HashIndex, HashIndex); fn new_indexes(&self) -> Self::Indexes { @@ -211,7 +197,7 @@ where impl ExecutablePlan for ViewEqualPlan where - K: Eq + Hash + Clone, + K: Eq + Hash, KeyA: ViewKey + Send + Sync, KeyB: ViewKey + Send + Sync, { diff --git a/crates/solverforge-scoring/src/stream/relational/view_plan/group.rs b/crates/solverforge-scoring/src/stream/relational/view_plan/group.rs new file mode 100644 index 000000000..296fde075 --- /dev/null +++ b/crates/solverforge-scoring/src/stream/relational/view_plan/group.rs @@ -0,0 +1,209 @@ +//! Equality between a grouped row's own key and a key read off the other side. +//! +//! A group owns its key, so the group side is indexed by the key's hash only +//! (`HashedIndex`) and never copies it; the other side computes its key by +//! value and is indexed exactly (`HashIndex`). A probe into the hashed side may +//! return groups of a colliding key, so that probe direction compares keys; +//! the other direction is exact. + +use std::borrow::Cow; +use std::hash::Hash; +use std::marker::PhantomData; + +use super::ViewKey; +use crate::stream::joiner::plan::{CompileCondition, EqualityKind, ExecutablePlan, IndexedPlan}; +use crate::stream::joiner::Joiner; +use crate::stream::relational::index::{HashIndex, HashedIndex}; +use crate::stream::relational::keyed_plan::KeyedRegain; +use crate::stream::relational::operator::{GroupView, Operator}; +use crate::stream::relational::{hash_key, RowHandle}; + +/// The grouped rows are the join's left input. +pub struct GroupLeft; + +/// The grouped rows are the join's right input. +pub struct GroupRight; + +/// Matches a grouped row's key to `key` of the other input's rows. `Side` +/// says which input is grouped. +pub struct GroupEqualPlan { + key: KeyFn, + marker: PhantomData (K, Side)>, +} + +impl GroupEqualPlan { + /// Creates the plan reading the other input's key with `key`. + pub fn new(key: KeyFn) -> Self { + Self { + key, + marker: PhantomData, + } + } +} + +impl CompileCondition for GroupEqualPlan { + type Plan = Self; + fn compile(self) -> Self { + self + } +} + +impl IndexedPlan for GroupEqualPlan { + type Kind = EqualityKind; + type Indexes = (HashIndex, HashedIndex); + fn new_indexes(&self) -> Self::Indexes { + (HashIndex::new(), HashedIndex::new()) + } + fn remove_left(&self, i: &mut Self::Indexes, h: RowHandle) { + i.0.remove(h); + } + fn remove_right(&self, i: &mut Self::Indexes, h: RowHandle) { + i.1.remove(h); + } +} + +impl IndexedPlan for GroupEqualPlan { + type Kind = EqualityKind; + type Indexes = (HashedIndex, HashIndex); + fn new_indexes(&self) -> Self::Indexes { + (HashedIndex::new(), HashIndex::new()) + } + fn remove_left(&self, i: &mut Self::Indexes, h: RowHandle) { + i.0.remove(h); + } + fn remove_right(&self, i: &mut Self::Indexes, h: RowHandle) { + i.1.remove(h); + } +} + +impl Joiner> + for GroupEqualPlan +where + S: 'static, + O: Operator, + K: PartialEq, + KeyFn: ViewKey + Send + Sync, +{ + #[inline] + fn matches(&self, left: &L, right: &GroupView<'_, S, O, K, A, V, R>) -> bool { + self.key.key(left) == *right.key + } +} + +impl Joiner, RV> + for GroupEqualPlan +where + S: 'static, + O: Operator, + K: PartialEq, + KeyFn: ViewKey + Send + Sync, +{ + #[inline] + fn matches(&self, left: &GroupView<'_, S, O, K, A, V, R>, right: &RV) -> bool { + *left.key == self.key.key(right) + } +} + +impl ExecutablePlan> + for GroupEqualPlan +where + S: 'static, + O: Operator, + K: Eq + Hash, + KeyFn: ViewKey + Send + Sync, +{ + #[inline] + fn right_candidate_matches(&self, left: &L, right: &GroupView<'_, S, O, K, A, V, R>) -> bool { + self.matches(left, right) + } + #[inline] + fn left_candidate_matches(&self, _: &L, _: &GroupView<'_, S, O, K, A, V, R>) -> bool { + true + } + fn insert_left(&self, i: &mut Self::Indexes, h: RowHandle, row: &L) { + i.0.insert(h, self.key.key(row)); + } + fn insert_right( + &self, + i: &mut Self::Indexes, + h: RowHandle, + row: &GroupView<'_, S, O, K, A, V, R>, + ) { + i.1.insert(h, hash_key(row.key)); + } + fn insert_right_transient( + &self, + i: &mut Self::Indexes, + h: RowHandle, + row: &GroupView<'_, S, O, K, A, V, R>, + ) { + i.1.insert_transient(h, hash_key(row.key)); + } + fn right_candidates<'i>(&self, i: &'i Self::Indexes, row: &L) -> Cow<'i, [RowHandle]> { + Cow::Borrowed(i.1.lookup(&self.key.key(row))) + } + fn left_candidates<'i>( + &self, + i: &'i Self::Indexes, + row: &GroupView<'_, S, O, K, A, V, R>, + ) -> Cow<'i, [RowHandle]> { + Cow::Borrowed(i.0.lookup(row.key)) + } +} + +impl ExecutablePlan, RV> + for GroupEqualPlan +where + S: 'static, + O: Operator, + K: Eq + Hash, + KeyFn: ViewKey + Send + Sync, +{ + #[inline] + fn right_candidate_matches(&self, _: &GroupView<'_, S, O, K, A, V, R>, _: &RV) -> bool { + true + } + #[inline] + fn left_candidate_matches(&self, left: &GroupView<'_, S, O, K, A, V, R>, right: &RV) -> bool { + self.matches(left, right) + } + fn insert_left( + &self, + i: &mut Self::Indexes, + h: RowHandle, + row: &GroupView<'_, S, O, K, A, V, R>, + ) { + i.0.insert(h, hash_key(row.key)); + } + fn insert_right(&self, i: &mut Self::Indexes, h: RowHandle, row: &RV) { + i.1.insert(h, self.key.key(row)); + } + fn insert_right_transient(&self, i: &mut Self::Indexes, h: RowHandle, row: &RV) { + i.1.insert_transient(h, self.key.key(row)); + } + fn right_candidates<'i>( + &self, + i: &'i Self::Indexes, + row: &GroupView<'_, S, O, K, A, V, R>, + ) -> Cow<'i, [RowHandle]> { + Cow::Borrowed(i.1.lookup(row.key)) + } + fn left_candidates<'i>(&self, i: &'i Self::Indexes, row: &RV) -> Cow<'i, [RowHandle]> { + Cow::Borrowed(i.0.lookup(&self.key.key(row))) + } +} + +impl KeyedRegain for GroupEqualPlan { + /// Targets whose key hashes like the group's: a superset of the targets + /// sharing its key, which the regain pass tolerates. + fn extend_left_rows_sharing_key( + &self, + i: &Self::Indexes, + right: RowHandle, + out: &mut Vec, + ) { + if let Some(hash) = i.1.hash_of(right) { + i.0.extend_hash(hash, out); + } + } +} diff --git a/crates/solverforge-solver/benches/selector_cursor_gate.rs b/crates/solverforge-solver/benches/selector_cursor_gate.rs index c963fecb6..160d58830 100644 --- a/crates/solverforge-solver/benches/selector_cursor_gate.rs +++ b/crates/solverforge-solver/benches/selector_cursor_gate.rs @@ -62,7 +62,10 @@ const fn parse_data_pad(digits: &[u8]) -> usize { let mut value = 0; let mut position = 0; while position < digits.len() { - assert!(digits[position].is_ascii_digit(), "data pad is a decimal byte count"); + assert!( + digits[position].is_ascii_digit(), + "data pad is a decimal byte count" + ); value = value * 10 + (digits[position] - b'0') as usize; position += 1; } @@ -174,6 +177,7 @@ include!("selector_cursor_gate/scalar_cases.rs"); include!("selector_cursor_gate/construction_cases.rs"); include!("selector_cursor_gate/assignment_cases.rs"); include!("selector_cursor_gate/scoring_cases.rs"); +include!("selector_cursor_gate/scoring_join_cases.rs"); include!("selector_cursor_gate/route_model.rs"); include!("selector_cursor_gate/route_cases.rs"); @@ -224,6 +228,7 @@ fn main() { run_case!(case, matched, "route_rows", route_rows); run_case!(case, matched, "group_ruin", group_ruin); run_case!(case, matched, "scoring", scoring); + run_case!(case, matched, "scoring_joins", scoring_joins); run_case!(case, matched, "scoring_weights_one", scoring_weights_one); run_case!( case, diff --git a/crates/solverforge-solver/benches/selector_cursor_gate/scoring_join_cases.rs b/crates/solverforge-solver/benches/selector_cursor_gate/scoring_join_cases.rs new file mode 100644 index 000000000..a3232f744 --- /dev/null +++ b/crates/solverforge-solver/benches/selector_cursor_gate/scoring_join_cases.rs @@ -0,0 +1,171 @@ +/* Join scoring case: incremental score-director churn through the join +operators a fluent model builds for pairs of rows that share a key. + +- a same-collection self-join (`for_each(..).join(equal(..))`) whose authored + filter rejects nearly every pair, the `SelfJoinNode` path; +- a cross join of a filtered collection with its own unfiltered source + (`for_each(..).filter(..).join((source, equal_bi(..)))`), where one + notification inserts the changed row on both join sides at once; +- a cross join against a second collection whose filter rejects most pairs. + +Every change moves one shift to another employee or to none, so both join +sides retract and re-insert on each notification. Run with +`BENCH_CASES="scoring_joins"`. +*/ + +const JOIN_SHIFTS: usize = 2_048; +const JOIN_EMPLOYEES: usize = 128; +const JOIN_CHANGES: usize = 2_048; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +struct JoinShift { + index: usize, + employee: Option, + start: i64, + end: i64, +} + +#[derive(Clone, Debug)] +struct JoinEmployee { + id: usize, + unavailable_day: i64, +} + +#[derive(Clone, Debug)] +struct JoinPlan { + shifts: Vec, + employees: Vec, + score: Option, +} + +impl PlanningSolution for JoinPlan { + type Score = HardSoftScore; + + fn score(&self) -> Option { + self.score + } + + fn set_score(&mut self, score: Option) { + self.score = score; + } +} + +fn join_shifts(plan: &JoinPlan) -> &[JoinShift] { + plan.shifts.as_slice() +} + +fn join_employees(plan: &JoinPlan) -> &[JoinEmployee] { + plan.employees.as_slice() +} + +fn join_overlap(left: &JoinShift, right: &JoinShift) -> i64 { + (left.end.min(right.end) - left.start.max(right.start)).max(0) +} + +fn join_constraints() -> impl ConstraintSet { + let shifts = || { + solverforge_scoring::stream::collection_extract::source( + join_shifts as fn(&JoinPlan) -> &[JoinShift], + solverforge_scoring::stream::collection_extract::ChangeSource::Descriptor(0), + ) + }; + let factory = ConstraintFactory::::new; + ( + factory() + .for_each(shifts()) + .join(solverforge_scoring::stream::joiner::equal( + |shift: &JoinShift| shift.employee, + )) + .filter(|left: &JoinShift, right: &JoinShift| { + left.employee.is_some() && join_overlap(left, right) > 0 + }) + .penalize(|left: &JoinShift, right: &JoinShift| { + HardSoftScore::of_hard(join_overlap(left, right)) + }) + .named("Overlap"), + factory() + .for_each(shifts()) + .filter(|shift: &JoinShift| shift.employee.is_some()) + .join(( + shifts(), + equal_bi( + |left: &JoinShift| left.employee, + |right: &JoinShift| right.employee, + ), + )) + .filter(|left: &JoinShift, right: &JoinShift| { + left.index < right.index && right.start - left.end < 60 && left.end <= right.start + }) + .penalize(HardSoftScore::of_soft(1)) + .named("Short rest"), + factory() + .for_each(shifts()) + .join(( + solverforge_scoring::stream::collection_extract::source( + join_employees as fn(&JoinPlan) -> &[JoinEmployee], + solverforge_scoring::stream::collection_extract::ChangeSource::Static, + ), + equal_bi( + |shift: &JoinShift| shift.employee, + |employee: &JoinEmployee| Some(employee.id), + ), + )) + .filter(|shift: &JoinShift, employee: &JoinEmployee| { + shift.start / 1_440 == employee.unavailable_day + }) + .penalize(HardSoftScore::of_hard(10)) + .named("Unavailable"), + ) +} + +fn join_plan() -> JoinPlan { + JoinPlan { + shifts: (0..JOIN_SHIFTS) + .map(|index| { + let start = ((index * 37) % 28) as i64 * 1_440 + ((index % 3) as i64) * 480; + JoinShift { + index, + employee: (index % 29 != 0).then_some(index % JOIN_EMPLOYEES), + start, + end: start + 480, + } + }) + .collect(), + employees: (0..JOIN_EMPLOYEES) + .map(|id| JoinEmployee { + id, + unavailable_day: (id % 28) as i64, + }) + .collect(), + score: None, + } +} + +fn scoring_joins() { + let mut director = ScoreDirector::new(join_plan(), join_constraints()); + black_box(director.calculate_score()); + emit("scoring_joins", JOIN_CHANGES, || { + let mut count = 0; + let mut order = 0xCBF2_9CE4_8422_2325; + let mut scores = 0xCBF2_9CE4_8422_2325; + for _ in 0..iterations() { + for change in 0..JOIN_CHANGES { + let shift = change.wrapping_mul(193) % JOIN_SHIFTS; + director.before_variable_changed(0, shift); + let assigned = &mut director.working_solution_mut().shifts[shift].employee; + *assigned = match *assigned { + None => Some(change % JOIN_EMPLOYEES), + Some(employee) if employee + 1 == JOIN_EMPLOYEES => None, + Some(employee) => Some(employee + 1), + }; + director.after_variable_changed(0, shift); + let score = director.get_score(); + mix(&mut order, shift); + mix_u64(&mut scores, score.hard() as u64); + mix_u64(&mut scores, score.soft() as u64); + count += 1; + } + } + (count, order, scores) + }); +} diff --git a/docs/extend-scoring.md b/docs/extend-scoring.md index 4badd2a35..e1e379a5a 100644 --- a/docs/extend-scoring.md +++ b/docs/extend-scoring.md @@ -60,7 +60,12 @@ compiles to `EqualityWithResidual`, which is itself a compiled condition and composes into a single stream relationship. `candidate_matches` may omit only predicates already guaranteed by candidate -selection. `matches` remains the complete relationship. Preserve authored +selection; `right_candidate_matches` and `left_candidate_matches` narrow that +check to one probe direction, for plans whose two indexes are not equally +exact. `matches` remains the complete relationship. An index stores each key +it retains once and rows address it by slot, so retained state never clones a +key; a side whose rows already own their key, such as grouped rows under +`GroupEqualPlan`, is indexed by key hash and checked on the probe into it. Preserve authored short-circuit order for residual conditions. Key and predicate functions must be pure with respect to notified data. @@ -77,8 +82,12 @@ lifetimes for keys over nested pair rows — a closure annotated over a nested row fixes the borrow lifetime and fails the higher-ranked `ExecutablePlan` bound. `Chain::filter` wraps the tree in an identity-preserving `FilterNode`. Every filter authored on the cross `Bi`, `Tri`, `Quad` or `Penta` stream is -applied once by `PentaScored` at the penta boundary, and `Penta::join` builds -the `Chain` over that filtered producer. Same-source `PentaConstraintStream` is +the row filter of the stream's top `JoinNode`, applied once when a row is +found and before it is retained, and `Penta::join` builds the `Chain` over +that filtered producer. Put a stateless filter on the join it reads +(`JoinNode::filtered`, `SelfJoinNode::filtered`) rather than in a +`FilterNode` over it: the join then never stores the rows the filter +rejects. Same-source `PentaConstraintStream` is terminal. Fluent right-hand targets implement `CollectionExtract`, including filtered unary streams; arbitrary derived producers are inputs to low-level `JoinNode`, not interchangeable fluent targets. @@ -87,7 +96,9 @@ filtered unary streams; arbitrary derived producers are inputs to low-level Route each descriptor notification through every applicable binding. A binary join retracts affected outputs once, updates both input branches before insertion -probing, and deduplicates outputs by joined identity. Repeated insertion and +probing, and emits each pair once without an identity table: the right probe +skips left rows inserted by the same change, which the left probe already +paired. Repeated insertion and retraction are no-ops. A `Static` source ignores every descriptor notification, and a `Descriptor(idx)` source reacts only to its own descriptor; there is no unlocalized source and no rebuild fallback. diff --git a/scripts/bench-zero-regression.sh b/scripts/bench-zero-regression.sh index e6fabe411..6fb4c0755 100755 --- a/scripts/bench-zero-regression.sh +++ b/scripts/bench-zero-regression.sh @@ -101,9 +101,10 @@ ASSIGNMENT_NEIGHBORHOOD_MEASURE_ITERATIONS=${ASSIGNMENT_NEIGHBORHOOD_MEASURE_ITE TOOLCHAIN=${TOOLCHAIN:-1.95.0} RESULTS=${RESULTS:-"/tmp/solverforge-zero-regression-$(date +%Y%m%d-%H%M%S)"} # Opt-in scoring cases (not in the default selector set): BENCH_CASES="scoring -# scoring_weights_one scoring_weights_mixed" measures incremental score-director -# churn through uni, join, shared grouped, and balance constraints; see -# crates/solverforge-solver/benches/selector_cursor_gate/scoring_cases.rs. +# scoring_weights_one scoring_weights_mixed scoring_joins" measures incremental +# score-director churn through uni, join, self-join, shared grouped, and balance +# constraints; see crates/solverforge-solver/benches/selector_cursor_gate/ +# scoring_cases.rs and scoring_join_cases.rs. DEFAULT_CASES=(list_change list_swap nearby_change nearby_swap sublist_change sublist_swap union cartesian k_opt ruin scalar_change scalar_swap construction_full construction_first_fit assignment_required assignment_neighborhood route_rows group_ruin) if [[ -n ${BENCH_CASES:-} ]]; then read -r -a CASES <<<"$BENCH_CASES"