greynet 0.11.0

High performance rule and constraint satisfaction engine
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
// nodes.rs - Enhanced with new node types
use super::advanced_index::AdvancedIndex;
use super::arena::{NodeId, NodeOperation, SafeTupleIndex, TupleArena};
use super::collectors::{BaseCollector, UndoReceipt};
use super::joiner::JoinerType;
use super::stream_def::{CollectorSupplier, ZeroCopyTupleMapperFn};
use super::tuple::BiTuple;
use super::uni_index::UniIndex;
use crate::constraint::ConstraintWeights;
use crate::constraint::ConstraintId;
use crate::packed_indices::PackedIndices;
use crate::score::Score;
use crate::state::TupleState;
use crate::tuple::{AnyTuple, FactIterator, ZeroCopyFacts};
use crate::{GreynetError, Result};
use rustc_hash::FxHashMap as HashMap;
use smallvec::SmallVec;
use std::any::TypeId;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

// --- Zero-Copy Function Type Definitions ---

/// A function that extracts a hashable key from a tuple without allocations.
pub type ZeroCopyKeyFn = Rc<dyn Fn(&dyn ZeroCopyFacts) -> u64>;
/// A function that evaluates a tuple and returns true or false without allocations.
pub type ZeroCopyPredicate = Rc<dyn Fn(&dyn ZeroCopyFacts) -> bool>;
/// A function that calculates a score impact from a tuple without allocations.
pub type ZeroCopyImpactFn<S> = Rc<dyn Fn(&dyn ZeroCopyFacts) -> S>;
/// A function that maps a tuple to a new set of facts without allocations.
pub type ZeroCopyMapperFn = Rc<dyn Fn(&dyn ZeroCopyFacts) -> Vec<Rc<dyn crate::fact::GreynetFact>>>;

// --- Newtype Wrappers for Function Types ---

/// A wrapper for `ZeroCopyPredicate` for type safety and clarity.
#[derive(Clone)]
pub struct Predicate(pub ZeroCopyPredicate);

impl Predicate {
    #[inline]
    fn execute(&self, tuple: &AnyTuple) -> bool {
        self.0(tuple)
    }
}

/// A wrapper for `ZeroCopyKeyFn`.
#[derive(Clone)]
pub struct KeyFn(pub ZeroCopyKeyFn);

impl KeyFn {
    #[inline]
    fn execute(&self, tuple: &AnyTuple) -> u64 {
        self.0(tuple)
    }
}

/// A wrapper for `ZeroCopyImpactFn`.
#[derive(Clone)]
pub struct ImpactFn<S: Score>(pub ZeroCopyImpactFn<S>);

impl<S: Score> ImpactFn<S> {
    #[inline]
    pub fn execute(&self, tuple: &AnyTuple) -> S {
        self.0(tuple)
    }
}

/// A wrapper for `ZeroCopyMapperFn`.
#[derive(Clone)]
pub struct MapperFn(pub ZeroCopyMapperFn);

impl MapperFn {
    #[inline]
    fn execute(&self, tuple: &AnyTuple) -> Vec<Rc<dyn crate::fact::GreynetFact>> {
        self.0(tuple)
    }
}

/// NEW: A wrapper for tuple transformation functions
#[derive(Clone)]
pub struct TupleMapperFn(pub ZeroCopyTupleMapperFn);

impl TupleMapperFn {
    #[inline]
    fn execute(&self, tuple: &AnyTuple) -> AnyTuple {
        self.0(tuple)
    }
}

// --- Node Implementations ---

/// The entry point for facts of a specific type into the network.
#[derive(Debug)]
pub struct FromNode {
    pub children: Vec<NodeId>,
    pub fact_type: TypeId,
}

impl FromNode {
    pub fn new(fact_type: TypeId) -> Self {
        Self {
            children: Vec::new(),
            fact_type,
        }
    }

    #[inline]
    pub fn insert_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        _tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        for &child_id in &self.children {
            operations.push(NodeOperation::Insert(child_id, tuple_index));
        }
        Ok(())
    }

    #[inline]
    pub fn retract_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        _tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        for &child_id in &self.children {
            operations.push(NodeOperation::Retract(child_id, tuple_index));
        }
        Ok(())
    }
}

/// A node that filters tuples based on a predicate.
pub struct FilterNode {
    pub children: Vec<NodeId>,
    pub predicate: Predicate,
}

impl FilterNode {
    pub fn new(predicate: Predicate) -> Self {
        Self {
            children: Vec::new(),
            predicate,
        }
    }

    #[inline]
    pub fn insert_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if let Ok(tuple) = tuples.get_tuple_checked(tuple_index) {
            if self.predicate.execute(tuple) {
                for &child_id in &self.children {
                    operations.push(NodeOperation::Insert(child_id, tuple_index));
                }
            }
        }
        Ok(())
    }

    #[inline]
    pub fn retract_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if let Ok(tuple) = tuples.get_tuple_checked(tuple_index) {
            if self.predicate.execute(tuple) {
                for &child_id in &self.children {
                    operations.push(NodeOperation::Retract(child_id, tuple_index));
                }
            }
        }
        Ok(())
    }
}

impl std::fmt::Debug for FilterNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FilterNode")
            .field("children", &self.children)
            .field("predicate", &"<function>")
            .finish()
    }
}

/// An enum that abstracts over different index types for joins.
#[derive(Debug)]
pub enum JoinIndex {
    Uni(UniIndex<u64>),
    Advanced(AdvancedIndex<u64>),
}

impl JoinIndex {
    fn new(joiner_type: JoinerType) -> Self {
        match joiner_type {
            JoinerType::Equal => JoinIndex::Uni(UniIndex::new()),
            _ => JoinIndex::Advanced(AdvancedIndex::new(joiner_type)),
        }
    }

    #[inline]
    fn put(&mut self, key: u64, tuple_index: SafeTupleIndex) {
        match self {
            JoinIndex::Uni(i) => i.put(key, tuple_index),
            JoinIndex::Advanced(i) => i.put(key, tuple_index),
        }
    }

    #[inline]
    fn remove(&mut self, key: u64, tuple_index: &SafeTupleIndex) {
        match self {
            JoinIndex::Uni(i) => i.remove(key, tuple_index),
            JoinIndex::Advanced(i) => i.remove(key, tuple_index),
        }
    }

    #[inline]
    fn get_matches(&self, key: u64, joiner_type: JoinerType) -> Vec<SafeTupleIndex> {
        match self {
            JoinIndex::Uni(i) => i.get(key).to_vec(),
            JoinIndex::Advanced(i) => i.get_matches(key, joiner_type),
        }
    }
}

/// A node that combines tuples from two parent streams based on a join condition.
pub struct JoinNode {
    pub children: Vec<NodeId>,
    pub joiner_type: JoinerType,
    pub left_index: JoinIndex,
    pub right_index: JoinIndex,
    pub left_key_fn: KeyFn,
    pub right_key_fn: KeyFn,
    /// Stores the results of successful joins (parent tuple pairs -> child tuple).
    pub beta_memory: HashMap<PackedIndices, SafeTupleIndex>,
}

impl JoinNode {
    pub fn new(
        joiner_type: JoinerType,
        left_key_fn: KeyFn,
        right_key_fn: KeyFn,
    ) -> Self {
        Self {
            children: Vec::new(),
            joiner_type,
            left_index: JoinIndex::new(joiner_type),
            right_index: JoinIndex::new(joiner_type.inverse()),
            left_key_fn,
            right_key_fn,
            beta_memory: HashMap::default(),
        }
    }

    pub fn insert_left_collect_ops(
    &mut self,
    tuple_index: SafeTupleIndex,
    tuples: &mut TupleArena,
    operations: &mut Vec<NodeOperation>,
) -> Result<()> {
    let left_tuple = tuples.get_tuple_checked(tuple_index)?.clone();

    let key = self.left_key_fn.execute(&left_tuple);
    self.left_index.put(key, tuple_index);

    let right_matches: SmallVec<[SafeTupleIndex; 8]> = self
        .right_index
        .get_matches(key, self.joiner_type.inverse())
        .iter()
        .copied()
        .collect();

    if !right_matches.is_empty() {
        operations.reserve(right_matches.len() * self.children.len());
        for &right_match_idx in &right_matches {
            // First, create the packed key for the parent tuple pair.
            let packed = crate::packed_indices::PackedIndices::new(tuple_index, right_match_idx);
            
            // Before creating a child, check if one already exists for this pair.
            // This prevents creating a duplicate if the right-side tuple was processed first.
            if self.beta_memory.contains_key(&packed) {
                continue; // Child already exists, do nothing.
            }

            let right_tuple = tuples.get_tuple_checked(right_match_idx)?.clone();
            if let Ok(combined) = left_tuple.combine(&right_tuple) {
                let child_idx = tuples.acquire_tuple_fast(combined)?;
                // Use the 'packed' key we created earlier.
                self.beta_memory.insert(packed, child_idx);
                for &child_id in &self.children {
                    operations.push(NodeOperation::Insert(child_id, child_idx));
                }
            }
        }
    }
    Ok(())
}

pub fn insert_right_collect_ops(
    &mut self,
    tuple_index: SafeTupleIndex,
    tuples: &mut TupleArena,
    operations: &mut Vec<NodeOperation>,
) -> Result<()> {
    let right_tuple = tuples.get_tuple_checked(tuple_index)?.clone();

    let key = self.right_key_fn.execute(&right_tuple);
    self.right_index.put(key, tuple_index);

    let left_matches: SmallVec<[SafeTupleIndex; 8]> = self
        .left_index
        .get_matches(key, self.joiner_type)
        .iter()
        .copied()
        .collect();

    if !left_matches.is_empty() {
        operations.reserve(left_matches.len() * self.children.len());
    }

    for &left_match_idx in &left_matches {
        // Create the packed key for the parent tuple pair.
        let packed = PackedIndices::new(left_match_idx, tuple_index);

        // Check if a child already exists for this pair to prevent duplicates.
        if self.beta_memory.contains_key(&packed) {
            continue; // Child already exists, do nothing.
        }

        let left_tuple = tuples.get_tuple_checked(left_match_idx)?.clone();
        if let Ok(combined) = left_tuple.combine(&right_tuple) {
            let child_idx = tuples.acquire_tuple_fast(combined)?;
            // Use the 'packed' key we created earlier.
            self.beta_memory.insert(packed, child_idx);
            for &child_id in &self.children {
                operations.push(NodeOperation::Insert(child_id, child_idx));
            }
        }
    }
    Ok(())
}

    pub fn retract_left_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if let Ok(tuple) = tuples.get_tuple_checked(tuple_index) {
            let key = self.left_key_fn.execute(tuple);
            self.left_index.remove(key, &tuple_index);
        }

        let pairs_to_remove: SmallVec<[PackedIndices; 16]> = self
            .beta_memory
            .keys()
            .filter(|packed| packed.left_key() == tuple_index.key())
            .copied()
            .collect();

        for packed in pairs_to_remove {
            if let Some(child_idx) = self.beta_memory.remove(&packed) {
                for &child_id in &self.children {
                    operations.push(NodeOperation::Retract(child_id, child_idx));
                }
                if let Ok(child_tuple) = tuples.get_tuple_mut_checked(child_idx) {
                    child_tuple.set_state(TupleState::Dying);
                }
                operations.push(NodeOperation::ReleaseTuple(child_idx));
            }
        }
        Ok(())
    }

    pub fn retract_right_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if let Ok(tuple) = tuples.get_tuple_checked(tuple_index) {
            let key = self.right_key_fn.execute(tuple);
            self.right_index.remove(key, &tuple_index);
        }

        let pairs_to_remove: SmallVec<[PackedIndices; 16]> = self
            .beta_memory
            .keys()
            .filter(|packed| packed.right_key() == tuple_index.key())
            .copied()
            .collect();

        for packed in pairs_to_remove {
            if let Some(child_idx) = self.beta_memory.remove(&packed) {
                for &child_id in &self.children {
                    operations.push(NodeOperation::Retract(child_id, child_idx));
                }
                if let Ok(child_tuple) = tuples.get_tuple_mut_checked(child_idx) {
                    child_tuple.set_state(TupleState::Dying);
                }
                operations.push(NodeOperation::ReleaseTuple(child_idx));
            }
        }
        Ok(())
    }
}

impl std::fmt::Debug for JoinNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JoinNode")
            .field("children", &self.children)
            .field("joiner_type", &self.joiner_type)
            .field("beta_memory_size", &self.beta_memory.len())
            .field("left_key_fn", &"<function>")
            .field("right_key_fn", &"<function>")
            .finish()
    }
}

/// A node that propagates tuples only if a condition (existence or non-existence
/// of matching tuples in another stream) is met.
pub struct ConditionalNode {
    pub children: Vec<NodeId>,
    should_exist: bool,
    left_index: UniIndex<u64>,
    right_index: UniIndex<u64>,
    left_key_fn: KeyFn,
    right_key_fn: KeyFn,
    propagation_map: HashMap<SafeTupleIndex, u64>,
}

impl ConditionalNode {
    pub fn new(
        should_exist: bool,
        left_key_fn: KeyFn,
        right_key_fn: KeyFn,
    ) -> Self {
        Self {
            children: Vec::new(),
            should_exist,
            left_index: UniIndex::new(),
            right_index: UniIndex::new(),
            left_key_fn,
            right_key_fn,
            propagation_map: HashMap::default(),
        }
    }

    pub fn insert_left_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let key = if let Ok(tuple) = tuples.get_tuple_checked(tuple_index) {
            self.left_key_fn.execute(tuple)
        } else {
            return Ok(());
        };

        self.left_index.put(key, tuple_index);
        let right_match_count = self.right_index.get(key).len() as u64;
        let has_matches = right_match_count > 0;
        self.propagation_map.insert(tuple_index, right_match_count);

        if has_matches == self.should_exist {
            for &child_id in self.children.iter() {
                operations.push(NodeOperation::Insert(child_id, tuple_index));
            }
        }
        Ok(())
    }

    pub fn insert_right_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let key = if let Ok(tuple) = tuples.get_tuple_checked(tuple_index) {
            self.right_key_fn.execute(tuple)
        } else {
            return Ok(());
        };

        self.right_index.put(key, tuple_index);
        let left_matches = self.left_index.get(key).to_vec();

        for &left_match_idx in &left_matches {
            let match_count = self.propagation_map.entry(left_match_idx).or_insert(0);
            let was_propagated = (*match_count > 0) == self.should_exist;
            *match_count += 1;
            let is_now_propagated = (*match_count > 0) == self.should_exist;

            if !was_propagated && is_now_propagated {
                for &child_id in self.children.iter() {
                    operations.push(NodeOperation::Insert(child_id, left_match_idx));
                }
            } else if was_propagated && !is_now_propagated {
                for &child_id in self.children.iter() {
                    operations.push(NodeOperation::Retract(child_id, left_match_idx));
                }
            }
        }
        Ok(())
    }

    pub fn retract_left_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let key = if let Ok(tuple) = tuples.get_tuple_checked(tuple_index) {
            self.left_key_fn.execute(tuple)
        } else {
            return Ok(());
        };

        self.left_index.remove(key, &tuple_index);

        if let Some(match_count) = self.propagation_map.remove(&tuple_index) {
            if (match_count > 0) == self.should_exist {
                for &child_id in self.children.iter() {
                    operations.push(NodeOperation::Retract(child_id, tuple_index));
                }
            }
        }
        Ok(())
    }

    pub fn retract_right_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let key = if let Ok(tuple) = tuples.get_tuple_checked(tuple_index) {
            self.right_key_fn.execute(tuple)
        } else {
            return Ok(());
        };

        self.right_index.remove(key, &tuple_index);
        let left_matches = self.left_index.get(key).to_vec();

        for &left_match_idx in &left_matches {
            if let Some(match_count) = self.propagation_map.get_mut(&left_match_idx) {
                let was_propagated = (*match_count > 0) == self.should_exist;
                *match_count = match_count.saturating_sub(1);
                let is_now_propagated = (*match_count > 0) == self.should_exist;

                if was_propagated && !is_now_propagated {
                    for &child_id in self.children.iter() {
                        operations.push(NodeOperation::Retract(child_id, left_match_idx));
                    }
                } else if !was_propagated && is_now_propagated {
                    for &child_id in self.children.iter() {
                        operations.push(NodeOperation::Insert(child_id, left_match_idx));
                    }
                }
            }
        }
        Ok(())
    }
}


impl std::fmt::Debug for ConditionalNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConditionalNode")
            .field("children", &self.children)
            .field("should_exist", &self.should_exist)
            .field("propagation_map", &self.propagation_map)
            .field("left_key_fn", &"<function>")
            .field("right_key_fn", &"<function>")
            .finish()
    }
}

/// A node that groups tuples by a key and applies a collector to each group.
pub struct GroupNode {
    pub children: Vec<NodeId>,
    key_fn: KeyFn,
    collector_supplier: CollectorSupplier,
    groups: HashMap<u64, Box<dyn BaseCollector>>,
    tuple_to_receipt: HashMap<SafeTupleIndex, (u64, UndoReceipt)>,
    group_key_to_tuple: HashMap<u64, SafeTupleIndex>,
}

impl GroupNode {
    pub fn new(key_fn: KeyFn, collector_supplier: CollectorSupplier) -> Self {
        Self {
            children: Vec::new(),
            key_fn,
            collector_supplier,
            groups: HashMap::default(),
            tuple_to_receipt: HashMap::default(),
            group_key_to_tuple: HashMap::default(),
        }
    }

    pub fn insert_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let parent_tuple = tuples.get_tuple_checked(tuple_index)?;
        let key = self.key_fn.execute(parent_tuple);

        let collector = self
            .groups
            .entry(key)
            .or_insert_with(|| self.collector_supplier.create());
        
        let receipt = collector.insert(parent_tuple);
        self.tuple_to_receipt.insert(tuple_index, (key, receipt));
        self.update_or_create_child(key, tuples, operations)?;
        Ok(())
    }

    pub fn retract_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if let Some((key, receipt)) = self.tuple_to_receipt.remove(&tuple_index) {
            let parent_tuple = tuples.get_tuple_checked(tuple_index)?;
            if let Some(collector) = self.groups.get_mut(&key) {
                collector.remove(parent_tuple, receipt);
            }

            let is_empty = self.groups.get(&key).map_or(true, |c| c.is_empty());

            if is_empty {
                if let Some(child_tuple_index) = self.group_key_to_tuple.remove(&key) {
                    for &child_id in self.children.iter() {
                        operations.push(NodeOperation::Retract(child_id, child_tuple_index));
                    }

                    if let Ok(child_tuple) = tuples.get_tuple_mut_checked(child_tuple_index) {
                        child_tuple.set_state(TupleState::Dying);
                    }

                    operations.push(NodeOperation::ReleaseTuple(child_tuple_index));
                }
                self.groups.remove(&key);
            } else {
                self.update_or_create_child(key, tuples, operations)?;
            }
        }
        Ok(())
    }

    fn update_or_create_child(
        &mut self,
        key: u64,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let new_result_fact = {
            let collector = self
                .groups
                .get_mut(&key)
                .ok_or_else(|| GreynetError::arena_error("Collector not found for key"))?;
            collector.result_as_fact()
        };

        if let Some(&old_child_index) = self.group_key_to_tuple.get(&key) {
            let old_tuple = tuples.get_tuple_checked(old_child_index)?;
            let old_result_fact = match old_tuple {
                AnyTuple::Bi(t) => t.fact_b.clone(),
                _ => {
                    return Err(GreynetError::type_mismatch(
                        "GroupNode child should be BiTuple",
                    ))
                }
            };

            if old_result_fact.eq_fact(&*new_result_fact) {
                return Ok(());
            }

            for &child_id in self.children.iter() {
                operations.push(NodeOperation::Retract(child_id, old_child_index));
            }

            if let Ok(old_tuple_mut) = tuples.get_tuple_mut_checked(old_child_index) {
                old_tuple_mut.set_state(TupleState::Dying);
            }

            operations.push(NodeOperation::ReleaseTuple(old_child_index));
        }

        let key_fact: Rc<dyn crate::fact::GreynetFact> = Rc::new(key);
        let new_child_tuple = AnyTuple::Bi(BiTuple::new(key_fact, new_result_fact));
        let new_child_index = tuples.acquire_tuple(new_child_tuple)?;
        self.group_key_to_tuple.insert(key, new_child_index);

        for &child_id in self.children.iter() {
            operations.push(NodeOperation::Insert(child_id, new_child_index));
        }
        Ok(())
    }
}


impl std::fmt::Debug for GroupNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GroupNode")
            .field("children", &self.children)
            .field("groups", &self.groups.len())
            .field("key_fn", &"<function>")
            .field("collector_supplier", &self.collector_supplier)
            .finish()
    }
}

/// A node that transforms each incoming tuple into zero or more new tuples.
pub struct FlatMapNode {
    pub children: Vec<NodeId>,
    mapper_fn: MapperFn,
    parent_to_children_map: HashMap<SafeTupleIndex, Vec<SafeTupleIndex>>,
}

impl FlatMapNode {
    pub fn new(mapper_fn: MapperFn) -> Self {
        Self {
            children: Vec::new(),
            mapper_fn,
            parent_to_children_map: HashMap::default(),
        }
    }

    pub fn insert_collect_ops(
        &mut self,
        parent_tuple_idx: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let parent_tuple = tuples.get_tuple_checked(parent_tuple_idx)?;
        let new_facts = self.mapper_fn.execute(parent_tuple);

        if new_facts.is_empty() {
            return Ok(());
        }

        let mut child_indices = Vec::new();
        for fact in new_facts {
            let new_tuple = AnyTuple::Uni(crate::tuple::UniTuple::new(fact));
            let child_idx = tuples.acquire_tuple(new_tuple)?;
            child_indices.push(child_idx);
            for &child_id in self.children.iter() {
                operations.push(NodeOperation::Insert(child_id, child_idx));
            }
        }
        self.parent_to_children_map
            .insert(parent_tuple_idx, child_indices);
        Ok(())
    }

    pub fn retract_collect_ops(
        &mut self,
        parent_tuple_idx: SafeTupleIndex,
        _tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if let Some(child_indices) = self.parent_to_children_map.remove(&parent_tuple_idx) {
            for child_idx in child_indices {
                for &child_id in self.children.iter() {
                    operations.push(NodeOperation::Retract(child_id, child_idx));
                }
                operations.push(NodeOperation::ReleaseTuple(child_idx));
            }
        }
        Ok(())
    }
}

impl std::fmt::Debug for FlatMapNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FlatMapNode")
            .field("children", &self.children)
            .field("mapper_fn", &"<function>")
            .finish()
    }
}

/// NEW: A node that transforms each incoming tuple into a single new tuple.
pub struct MapNode {
    pub children: Vec<NodeId>,
    mapper_fn: TupleMapperFn,
    parent_to_child_map: HashMap<SafeTupleIndex, SafeTupleIndex>,
}

impl MapNode {
    pub fn new(mapper_fn: TupleMapperFn) -> Self {
        Self {
            children: Vec::new(),
            mapper_fn,
            parent_to_child_map: HashMap::default(),
        }
    }

    pub fn insert_collect_ops(
        &mut self,
        parent_tuple_idx: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let parent_tuple = tuples.get_tuple_checked(parent_tuple_idx)?;
        let new_tuple = self.mapper_fn.execute(parent_tuple);

        let child_idx = tuples.acquire_tuple(new_tuple)?;
        self.parent_to_child_map.insert(parent_tuple_idx, child_idx);
        
        for &child_id in self.children.iter() {
            operations.push(NodeOperation::Insert(child_id, child_idx));
        }
        Ok(())
    }

    pub fn retract_collect_ops(
        &mut self,
        parent_tuple_idx: SafeTupleIndex,
        _tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if let Some(child_idx) = self.parent_to_child_map.remove(&parent_tuple_idx) {
            for &child_id in self.children.iter() {
                operations.push(NodeOperation::Retract(child_id, child_idx));
            }
            operations.push(NodeOperation::ReleaseTuple(child_idx));
        }
        Ok(())
    }
}

impl std::fmt::Debug for MapNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MapNode")
            .field("children", &self.children)
            .field("mapper_fn", &"<function>")
            .finish()
    }
}

/// NEW: A node that merges multiple streams into one.
pub struct UnionNode {
    pub children: Vec<NodeId>,
    // Track which parent each tuple came from for proper retraction
    tuple_source_map: HashMap<SafeTupleIndex, usize>,
}

impl UnionNode {
    pub fn new() -> Self {
        Self {
            children: Vec::new(),
            tuple_source_map: HashMap::default(),
        }
    }

    pub fn insert_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        _tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
        source_index: usize,
    ) -> Result<()> {
        self.tuple_source_map.insert(tuple_index, source_index);
        for &child_id in &self.children {
            operations.push(NodeOperation::Insert(child_id, tuple_index));
        }
        Ok(())
    }

    pub fn retract_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        _tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if self.tuple_source_map.remove(&tuple_index).is_some() {
            for &child_id in &self.children {
                operations.push(NodeOperation::Retract(child_id, tuple_index));
            }
        }
        Ok(())
    }
}

impl std::fmt::Debug for UnionNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UnionNode")
            .field("children", &self.children)
            .field("tracked_tuples", &self.tuple_source_map.len())
            .finish()
    }
}

/// NEW: A node that ensures only unique tuples pass through.
pub struct DistinctNode {
    pub children: Vec<NodeId>,
    // Use a hash-based approach for detecting duplicates
    seen_tuples: HashMap<u64, Vec<SafeTupleIndex>>,
    tuple_to_hash: HashMap<SafeTupleIndex, u64>,
}

impl DistinctNode {
    pub fn new() -> Self {
        Self {
            children: Vec::new(),
            seen_tuples: HashMap::default(),
            tuple_to_hash: HashMap::default(),
        }
    }

    fn compute_tuple_hash(tuple: &AnyTuple) -> u64 {
        let mut hasher = DefaultHasher::new();
        for fact in tuple.facts_iter() {
            fact.hash_fact().hash(&mut hasher);
        }
        hasher.finish()
    }

    pub fn insert_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let tuple = tuples.get_tuple_checked(tuple_index)?;
        let hash = Self::compute_tuple_hash(tuple);
        
        let is_duplicate = self.seen_tuples
            .get(&hash)
            .map_or(false, |indices| !indices.is_empty());

        self.seen_tuples.entry(hash).or_default().push(tuple_index);
        self.tuple_to_hash.insert(tuple_index, hash);

        // Only propagate if this is the first occurrence
        if !is_duplicate {
            for &child_id in &self.children {
                operations.push(NodeOperation::Insert(child_id, tuple_index));
            }
        }
        Ok(())
    }

    pub fn retract_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        _tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if let Some(hash) = self.tuple_to_hash.remove(&tuple_index) {
            if let Some(indices) = self.seen_tuples.get_mut(&hash) {
                let was_first = indices.first() == Some(&tuple_index);
                indices.retain(|&idx| idx != tuple_index);
                
                if was_first {
                    // We're removing the first occurrence, propagate the retraction
                    for &child_id in &self.children {
                        operations.push(NodeOperation::Retract(child_id, tuple_index));
                    }
                    
                    // If there are more occurrences, propagate the next one
                    if let Some(&next_index) = indices.first() {
                        for &child_id in &self.children {
                            operations.push(NodeOperation::Insert(child_id, next_index));
                        }
                    }
                }
                
                if indices.is_empty() {
                    self.seen_tuples.remove(&hash);
                }
            }
        }
        Ok(())
    }
}

impl std::fmt::Debug for DistinctNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DistinctNode")
            .field("children", &self.children)
            .field("unique_hashes", &self.seen_tuples.len())
            .finish()
    }
}

/// NEW: A node that performs global aggregation on all tuples.
pub struct GlobalAggregateNode {
    pub children: Vec<NodeId>,
    collector_supplier: CollectorSupplier,
    collector: Option<Box<dyn BaseCollector>>,
    tuple_to_receipt: HashMap<SafeTupleIndex, UndoReceipt>,
    current_result_tuple: Option<SafeTupleIndex>,
}

impl GlobalAggregateNode {
    pub fn new(collector_supplier: CollectorSupplier) -> Self {
        Self {
            children: Vec::new(),
            collector_supplier,
            collector: None,
            tuple_to_receipt: HashMap::default(),
            current_result_tuple: None,
        }
    }

    pub fn insert_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let parent_tuple = tuples.get_tuple_checked(tuple_index)?;
        
        // Initialize collector if needed
        if self.collector.is_none() {
            self.collector = Some(self.collector_supplier.create());
        }
        
        let receipt = self.collector.as_mut().unwrap().insert(parent_tuple);
        self.tuple_to_receipt.insert(tuple_index, receipt);
        
        self.update_or_create_result(tuples, operations)?;
        Ok(())
    }

    pub fn retract_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if let Some(receipt) = self.tuple_to_receipt.remove(&tuple_index) {
            let parent_tuple = tuples.get_tuple_checked(tuple_index)?;
            if let Some(collector) = self.collector.as_mut() {
                collector.remove(parent_tuple, receipt);
            }
            
            if self.collector.as_ref().map_or(true, |c| c.is_empty()) {
                // Remove the result tuple if collector is empty
                if let Some(result_index) = self.current_result_tuple.take() {
                    for &child_id in &self.children {
                        operations.push(NodeOperation::Retract(child_id, result_index));
                    }
                    operations.push(NodeOperation::ReleaseTuple(result_index));
                }
            } else {
                self.update_or_create_result(tuples, operations)?;
            }
        }
        Ok(())
    }

    fn update_or_create_result(
        &mut self,
        tuples: &mut TupleArena,
        operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        let new_result_fact = if let Some(collector) = self.collector.as_ref() {
            collector.result_as_fact()
        } else {
            return Ok(());
        };

        // Check if we need to update
        if let Some(old_result_index) = self.current_result_tuple {
            let old_tuple = tuples.get_tuple_checked(old_result_index)?;
            let old_result_fact = match old_tuple {
                AnyTuple::Uni(t) => &t.fact_a,
                _ => return Err(GreynetError::type_mismatch("GlobalAggregateNode result should be UniTuple")),
            };

            if old_result_fact.eq_fact(&*new_result_fact) {
                return Ok(());
            }

            // Retract old result
            for &child_id in &self.children {
                operations.push(NodeOperation::Retract(child_id, old_result_index));
            }
            operations.push(NodeOperation::ReleaseTuple(old_result_index));
        }

        // Create new result
        let new_result_tuple = AnyTuple::Uni(crate::tuple::UniTuple::new(new_result_fact));
        let new_result_index = tuples.acquire_tuple(new_result_tuple)?;
        self.current_result_tuple = Some(new_result_index);

        for &child_id in &self.children {
            operations.push(NodeOperation::Insert(child_id, new_result_index));
        }
        Ok(())
    }
}

impl std::fmt::Debug for GlobalAggregateNode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GlobalAggregateNode")
            .field("children", &self.children)
            .field("has_collector", &self.collector.is_some())
            .field("tuple_count", &self.tuple_to_receipt.len())
            .finish()
    }
}

/// A terminal node that calculates a score for each tuple that reaches it.
pub struct ScoringNode<S: Score> {
    /// MODIFIED: Uses the integer-based ConstraintId for fast lookups.
    pub constraint_id: ConstraintId,
    pub penalty_function: ImpactFn<S>,
    pub weights: Rc<RefCell<ConstraintWeights>>,
    score_accumulator: S::Accumulator,
    match_count: usize,
    active_matches: rustc_hash::FxHashSet<SafeTupleIndex>,
}

impl<S: Score> ScoringNode<S> {
    /// MODIFIED: The constructor now accepts the performant `ConstraintId`.
    pub fn new(
        constraint_id: ConstraintId,
        penalty_function: ImpactFn<S>,
        weights: Rc<RefCell<ConstraintWeights>>,
    ) -> Self {
        Self {
            constraint_id,
            penalty_function,
            weights,
            score_accumulator: S::Accumulator::default(),
            match_count: 0,
            active_matches: rustc_hash::FxHashSet::default(),
        }
    }

    #[inline]
    pub fn insert_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        _operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if let Ok(tuple) = tuples.get_tuple_checked(tuple_index) {
            if self.active_matches.insert(tuple_index) {
                let base_score = self.penalty_function.execute(tuple);
                // MODIFIED: get_weight is now called with the cheap-to-copy ConstraintId.
                // This avoids string hashing and comparison in the critical path.
                let weight = self.weights.borrow().get_weight(self.constraint_id);
                let weighted_score = base_score.mul(weight);
                
                S::accumulate_into(&mut self.score_accumulator, &weighted_score);
                self.match_count += 1;
            }
        }
        Ok(())
    }

    #[inline]
    pub fn retract_collect_ops(
        &mut self,
        tuple_index: SafeTupleIndex,
        tuples: &mut TupleArena,
        _operations: &mut Vec<NodeOperation>,
    ) -> Result<()> {
        if self.active_matches.remove(&tuple_index) {
            if let Ok(tuple) = tuples.get_tuple_checked(tuple_index) {
                let base_score = self.penalty_function.execute(tuple);
                // MODIFIED: get_weight is now called with the cheap-to-copy ConstraintId.
                let weight = self.weights.borrow().get_weight(self.constraint_id);
                let weighted_score = base_score.mul(weight);
                
                let negative_score = weighted_score.mul(-1.0);
                S::accumulate_into(&mut self.score_accumulator, &negative_score);
                self.match_count = self.match_count.saturating_sub(1);
            }
        }
        Ok(())
    }

    #[inline]
    pub fn get_total_score(&self) -> S {
        S::from_accumulator(&self.score_accumulator)
    }

    pub fn recalculate_scores(&mut self, tuples: &TupleArena) -> Result<()> {
        S::reset_accumulator(&mut self.score_accumulator);
        self.match_count = 0;
        
        // MODIFIED: get_weight is now called with the cheap-to-copy ConstraintId.
        let weight = self.weights.borrow().get_weight(self.constraint_id);
        
        for &tuple_idx in &self.active_matches {
            if let Ok(tuple) = tuples.get_tuple_checked(tuple_idx) {
                let base_score = self.penalty_function.execute(tuple);
                let weighted_score = base_score.mul(weight);
                S::accumulate_into(&mut self.score_accumulator, &weighted_score);
                self.match_count += 1;
            }
        }
        Ok(())
    }

    #[inline]
    pub fn match_count(&self) -> usize {
        self.match_count
    }

    #[inline]
    pub fn has_match(&self, tuple_index: &SafeTupleIndex) -> bool {
        self.active_matches.contains(tuple_index)
    }

    pub fn match_indices(&self) -> impl Iterator<Item = &SafeTupleIndex> {
        self.active_matches.iter()
    }
}

impl<S: Score> std::fmt::Debug for ScoringNode<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScoringNode")
            .field("constraint_id", &self.constraint_id)
            .field("match_count", &self.match_count)
            .field("accumulator", &self.score_accumulator)
            .field("penalty_function", &"<function>")
            .finish()
    }
}