solverforge-scoring 0.26.1

Incremental constraint scoring for SolverForge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
mod scored;
pub(crate) use scored::TriScored;

/* Canonical three-source fluent join: one operator tree, no per-arity engine.

A `Tri` owns `JoinNode<JoinNode<A,B>, C>` over compiled condition plans.
The first relationship keeps the Bi stream's typed keys; the second
relationship is compiled fresh from its joiner, so the left closure
receives the whole borrowed (A, B) row (`Concat<Leaf<A>, B>`) and the
key domain is independent of the first. Terminal scoring is the generic
`OperatorTerminal`; explanations borrow the full row.
*/

use std::marker::PhantomData;

use solverforge_core::score::Score;
use solverforge_core::{ConstraintRef, ImpactType};

use super::super::collection_extract::CollectionExtract;
use super::super::filter::{AndTriFilter, FnTriFilter, TriAsQuadFilter, TriFilter};
use super::super::joiner::plan::{CompileCondition, ExecutablePlan, IndexedPlan};
use super::super::relational::operator::{CollectionNode, ExplainRow, JoinNode, Operator, Pair};
use super::super::relational::{HandleMap, Leaf, RowHandle};
use super::super::weighting_support::ConstraintWeight;
use crate::constraint::relational::OperatorTerminal;

/// The full tri tree: (A ⋈ B on the AB plan) ⋈ C on P2. Entity types ride
/// inside the extractors and the AB plan's key closures.
pub(crate) type BuiltTri<S, EA, EB, EC, P1, P2> = JoinNode<
    S,
    JoinNode<S, CollectionNode<S, EA>, CollectionNode<S, EB>, <P1 as CompileCondition>::Plan>,
    CollectionNode<S, EC>,
    <P2 as CompileCondition>::Plan,
>;

/// The tri tree's borrowed row: `Pair<Pair<Leaf<A>, Leaf<B>>, Leaf<C>>`.
pub(crate) type TriRow<'a, S, EA, EB, EC, P1, P2> =
    <BuiltTri<S, EA, EB, EC, P1, P2> as Operator<S>>::View<'a>;

/// Assembles the tri tree from extractors, unary first keys, and a compiled
/// second-relationship plan. Shared by `Bi::join` dispatch.
#[allow(clippy::too_many_arguments)]
pub(super) fn build_tree<S, A, B, C, EA, EB, EC, P1, P2>(
    extractor_a: EA,
    extractor_b: EB,
    extractor_c: EC,
    ab_plan: P1,
    second_plan: P2,
) -> BuiltTri<S, EA, EB, EC, P1, P2>
where
    S: Send + Sync + 'static,
    A: Clone + Send + Sync + 'static,
    B: Clone + Send + Sync + 'static,
    C: Clone + Send + Sync + 'static,
    EA: CollectionExtract<S, Item = A> + 'static,
    EB: CollectionExtract<S, Item = B> + 'static,
    EC: CollectionExtract<S, Item = C> + 'static,
    P1: CompileCondition<Plan: IndexedPlan> + 'static,
    P2: CompileCondition<Plan: IndexedPlan> + 'static,
    for<'a> <P1 as CompileCondition>::Plan: ExecutablePlan<Leaf<'a, A>, Leaf<'a, B>>,
    for<'a> <P2 as CompileCondition>::Plan:
        ExecutablePlan<
            <JoinNode<
                S,
                CollectionNode<S, EA>,
                CollectionNode<S, EB>,
                <P1 as CompileCondition>::Plan,
            > as Operator<S>>::View<'a>,
            Leaf<'a, C>,
        >,
    JoinNode<S, CollectionNode<S, EA>, CollectionNode<S, EB>, <P1 as CompileCondition>::Plan>:
        Operator<S>,
    BuiltTri<S, EA, EB, EC, P1, P2>: Operator<S>,
{
    let left = JoinNode::new(
        CollectionNode::new(extractor_a, 1),
        CollectionNode::new(extractor_b, 0),
        ab_plan,
    );
    JoinNode::new(left, CollectionNode::new(extractor_c, 2), second_plan)
}

/// Assembles a `Tri` from a Bi stream's parts plus the compiled second
/// condition. Single construction point for `Bi::join` dispatch.
#[allow(clippy::too_many_arguments)]
pub(crate) fn assemble_tri<S, A, B, C, EA, EB, EC, P1, P2, F, Sc>(
    extractor_a: EA,
    extractor_b: EB,
    extractor_c: EC,
    ab_plan: P1,
    second: P2,
    filter: F,
) -> Tri<S, A, B, C, EA, EB, EC, P1, P2, F, Sc>
where
    S: Send + Sync + 'static,
    A: Clone + Send + Sync + 'static,
    B: Clone + Send + Sync + 'static,
    C: Clone + Send + Sync + 'static,
    EA: CollectionExtract<S, Item = A> + 'static,
    EB: CollectionExtract<S, Item = B> + 'static,
    EC: CollectionExtract<S, Item = C> + 'static,
    P1: CompileCondition<Plan: IndexedPlan> + 'static,
    P2: CompileCondition<Plan: IndexedPlan> + 'static,
    for<'a> <P1 as CompileCondition>::Plan: ExecutablePlan<Leaf<'a, A>, Leaf<'a, B>>,
    for<'a> <P2 as CompileCondition>::Plan:
        ExecutablePlan<
            <JoinNode<
                S,
                CollectionNode<S, EA>,
                CollectionNode<S, EB>,
                <P1 as CompileCondition>::Plan,
            > as Operator<S>>::View<'a>,
            Leaf<'a, C>,
        >,
    JoinNode<S, CollectionNode<S, EA>, CollectionNode<S, EB>, <P1 as CompileCondition>::Plan>:
        Operator<S>,
    BuiltTri<S, EA, EB, EC, P1, P2>: Operator<S>,
    F: TriFilter<S, A, B, C>,
    Sc: Score,
{
    let tree = build_tree(extractor_a, extractor_b, extractor_c, ab_plan, second);
    Tri {
        tree,
        filter,
        _phantom: PhantomData,
    }
}

/// Three-collection join stream: `(A ⋈ B) ⋈ C`, with `P1` relating `A` to `B`
/// and `P2` relating the joined pair to `C`.
pub struct Tri<S, A, B, C, EA, EB, EC, P1, P2, F, Sc>
where
    Sc: Score,
    P1: CompileCondition<Plan: IndexedPlan>,
    P2: CompileCondition<Plan: IndexedPlan>,
{
    pub(crate) tree: BuiltTri<S, EA, EB, EC, P1, P2>,
    pub(crate) filter: F,
    pub(super) _phantom: PhantomData<(fn() -> S, fn() -> A, fn() -> B, fn() -> C, fn() -> Sc)>,
}

impl<S, A, B, C, EA, EB, EC, P1, P2, F, Sc> Tri<S, A, B, C, EA, EB, EC, P1, P2, F, Sc>
where
    S: Send + Sync + 'static,
    A: Clone + Send + Sync + 'static,
    B: Clone + Send + Sync + 'static,
    C: Clone + Send + Sync + 'static,
    EA: 'static,
    EB: 'static,
    EC: 'static,
    P1: CompileCondition<Plan: IndexedPlan> + 'static,
    P2: CompileCondition<Plan: IndexedPlan> + 'static,
    for<'a> <P1 as CompileCondition>::Plan: ExecutablePlan<Leaf<'a, A>, Leaf<'a, B>>,
    for<'a> <P2 as CompileCondition>::Plan:
        ExecutablePlan<Pair<Leaf<'a, A>, Leaf<'a, B>>, Leaf<'a, C>>,
    JoinNode<S, CollectionNode<S, EA>, CollectionNode<S, EB>, <P1 as CompileCondition>::Plan>:
        Operator<S>,
    BuiltTri<S, EA, EB, EC, P1, P2>: Operator<S>,
    F: TriFilter<S, A, B, C>,
    Sc: Score + 'static,
{
    /// Adds a filter predicate to the stream.
    pub fn filter<P>(
        self,
        predicate: P,
    ) -> Tri<
        S,
        A,
        B,
        C,
        EA,
        EB,
        EC,
        P1,
        P2,
        AndTriFilter<
            F,
            FnTriFilter<impl Fn(&S, &A, &B, &C, usize, usize, usize) -> bool + Send + Sync>,
        >,
        Sc,
    >
    where
        P: Fn(&A, &B, &C) -> bool + Send + Sync,
    {
        Tri {
            tree: self.tree,
            filter: AndTriFilter::new(
                self.filter,
                FnTriFilter::new(crate::stream::closures::triple_filter::<S, A, B, C, _>(
                    predicate,
                )),
            ),
            _phantom: PhantomData,
        }
    }

    fn into_weighted_builder<W>(
        self,
        impact_type: ImpactType,
        weight: W,
        is_hard: bool,
    ) -> Builder<S, A, B, C, EA, EB, EC, P1, P2, F, W, Sc>
    where
        W: Fn(&A, &B, &C) -> Sc + Send + Sync,
    {
        Builder {
            tree: self.tree,
            filter: self.filter,
            impact_type,
            weight,
            is_hard,
            _phantom: PhantomData,
        }
    }

    /// Extends this triple with a fourth source D.
    ///
    /// The target tuple's condition compiles fresh, so its left closure receives
    /// the whole borrowed (A, B, C) row and the fourth key domain is independent
    /// of every earlier relationship.
    ///
    /// # Key shapes
    ///
    /// Later joins of a chain take VIEW keys, not entity keys:
    ///
    /// - left key — the whole borrowed row so far (for a Tri this is
    ///   `&Pair<Pair<Leaf<'_, A>, Leaf<'_, B>>, Leaf<'_, C>>`)
    /// - right key — `&Leaf<'_, D>` of the new entity, reading fields via `.entity`
    ///
    /// `equal_bi` with entity closures does NOT typecheck here (E0631, expected
    /// `fn(&Pair<...>)`) — use `equal_on`. The first join of a chain keeps
    /// `equal_bi` with plain entity keys.
    pub fn join<D, ED, P3>(
        self,
        target: (ED, P3),
    ) -> crate::stream::cross_quad_stream::Quad<
        S,
        A,
        B,
        C,
        D,
        EA,
        EB,
        EC,
        ED,
        P1,
        P2,
        P3,
        TriAsQuadFilter<F, A, B, C>,
        Sc,
    >
    where
        D: Clone + Send + Sync + 'static,
        ED: CollectionExtract<S, Item = D> + 'static,
        P3: CompileCondition + 'static,
        P3::Plan: IndexedPlan,
        for<'a> P3::Plan:
            ExecutablePlan<Pair<Pair<Leaf<'a, A>, Leaf<'a, B>>, Leaf<'a, C>>, Leaf<'a, D>>,
        for<'a> BuiltTri<S, EA, EB, EC, P1, P2>:
            Operator<S, View<'a> = Pair<Pair<Leaf<'a, A>, Leaf<'a, B>>, Leaf<'a, C>>>,
        for<'a> JoinNode<
            S,
            BuiltTri<S, EA, EB, EC, P1, P2>,
            CollectionNode<S, ED>,
            <P3 as CompileCondition>::Plan,
        >: Operator<S>,
    {
        let (extractor_d, condition) = target;
        let tree = JoinNode::new(self.tree, CollectionNode::new(extractor_d, 3), condition);
        crate::stream::cross_quad_stream::Quad {
            tree,
            filter: TriAsQuadFilter::new(self.filter),
            _phantom: PhantomData,
        }
    }

    /// Penalizes each match by `weight`.
    ///
    /// `weight` is a fixed score, or a closure over the matched `(&A, &B, &C)`
    /// triple returning one.
    /// A fixed weight with a non-zero hard level marks the constraint hard; closures
    /// are soft unless wrapped in [`hard_weight`](crate::stream::hard_weight).
    pub fn penalize<W>(
        self,
        weight: W,
    ) -> Builder<S, A, B, C, EA, EB, EC, P1, P2, F, impl Fn(&A, &B, &C) -> Sc + Send + Sync, Sc>
    where
        W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C), Sc> + Send + Sync,
    {
        let is_hard = weight.is_hard();
        self.into_weighted_builder(
            ImpactType::Penalty,
            crate::stream::closures::weight3::<A, B, C, Sc, _>(weight),
            is_hard,
        )
    }

    /// Rewards each match by `weight`.
    ///
    /// `weight` is a fixed score, or a closure over the matched `(&A, &B, &C)`
    /// triple returning one.
    /// A fixed weight with a non-zero hard level marks the constraint hard; closures
    /// are soft unless wrapped in [`hard_weight`](crate::stream::hard_weight).
    pub fn reward<W>(
        self,
        weight: W,
    ) -> Builder<S, A, B, C, EA, EB, EC, P1, P2, F, impl Fn(&A, &B, &C) -> Sc + Send + Sync, Sc>
    where
        W: for<'w> ConstraintWeight<(&'w A, &'w B, &'w C), Sc> + Send + Sync,
    {
        let is_hard = weight.is_hard();
        self.into_weighted_builder(
            ImpactType::Reward,
            crate::stream::closures::weight3::<A, B, C, Sc, _>(weight),
            is_hard,
        )
    }
}

/// Zero-erasure builder for finalizing a canonical tri constraint.
pub struct Builder<S, A, B, C, EA, EB, EC, P1, P2, F, W, Sc>
where
    Sc: Score,
    P1: CompileCondition<Plan: IndexedPlan>,
    P2: CompileCondition<Plan: IndexedPlan>,
{
    tree: BuiltTri<S, EA, EB, EC, P1, P2>,
    filter: F,
    impact_type: ImpactType,
    weight: W,
    is_hard: bool,
    _phantom: PhantomData<(fn() -> S, fn() -> A, fn() -> B, fn() -> C, fn() -> Sc)>,
}

impl<S, A, B, C, EA, EB, EC, P1, P2, F, W, Sc> Builder<S, A, B, C, EA, EB, EC, P1, P2, F, W, Sc>
where
    S: Send + Sync + 'static,
    A: Clone + std::fmt::Debug + Send + Sync + 'static,
    B: Clone + std::fmt::Debug + Send + Sync + 'static,
    C: Clone + std::fmt::Debug + Send + Sync + 'static,
    P1: CompileCondition<Plan: IndexedPlan>,
    P2: CompileCondition<Plan: IndexedPlan>,
    for<'a> JoinNode<S, CollectionNode<S, EA>, CollectionNode<S, EB>, <P1 as CompileCondition>::Plan>:
        Operator<S, View<'a> = Pair<Leaf<'a, A>, Leaf<'a, B>>>,
    for<'a> BuiltTri<S, EA, EB, EC, P1, P2>:
        Operator<S, View<'a> = Pair<Pair<Leaf<'a, A>, Leaf<'a, B>>, Leaf<'a, C>>>,
    for<'a> TriRow<'a, S, EA, EB, EC, P1, P2>: ExplainRow,
    F: TriFilter<S, A, B, C> + 'static,
    W: Fn(&A, &B, &C) -> Sc + Send + Sync,
    Sc: Score + 'static,
{
    /// Finalizes into the generic operator terminal.
    ///
    /// The authored tri filter runs inside the scored operator so evaluate,
    /// match_count, initialize, and mutations all honor it exactly once; the
    /// terminal's weight stays the plain authored per-row weight.
    pub fn named(
        self,
        name: &str,
    ) -> OperatorTerminal<
        S,
        TriScored<S, A, B, C, EA, EB, EC, P1, P2, F>,
        impl Fn(&S, &TriRow<'_, S, EA, EB, EC, P1, P2>) -> Sc + Send + Sync,
        Sc,
    > {
        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 weight_fn = crate::stream::closures::triple_row_weight::<S, A, B, C, Sc, _>(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<Pair<Leaf<'a, A>, 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,
        )
    }
}