-
Notifications
You must be signed in to change notification settings - Fork 115
/
engine.cljc
2145 lines (1801 loc) · 109 KB
/
engine.cljc
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
(ns clara.rules.engine
"This namespace is for internal use and may move in the future. Most users should use only the clara.rules namespace."
(:require [clojure.reflect :as reflect]
[clojure.core.reducers :as r]
[schema.core :as s]
[clojure.string :as string]
[clara.rules.memory :as mem]
[clara.rules.listener :as l]
#?(:clj [clara.rules.platform :as platform]
:cljs [clara.rules.platform :as platform :include-macros true])
[clara.rules.update-cache.core :as uc]
#?(:clj [clara.rules.update-cache.cancelling :as ca])))
;; The accumulator is a Rete extension to run an accumulation (such as sum, average, or similar operation)
;; over a collection of values passing through the Rete network. This object defines the behavior
;; of an accumulator. See the AccumulateNode for the actual node implementation in the network.
(defrecord Accumulator [initial-value retract-fn reduce-fn combine-fn convert-return-fn])
;; A Rete-style token, which contains two items:
;; * matches, a vector of [fact, node-id] tuples for the facts and corresponding nodes they matched.
;; NOTE: It is important that this remains an indexed vector for memory optimizations as well as
;; for correct conj behavior for new elements i.e. added to the end.
;; * bindings, a map of keyword-to-values for bound variables.
(defrecord Token [matches bindings])
;; A working memory element, containing a single fact and its corresponding bound variables.
(defrecord Element [fact bindings])
;; An activation for the given production and token.
(defrecord Activation [node token])
;; Token with no bindings, used as the root of beta nodes.
(def empty-token (->Token [] {}))
;; Record indicating the negation existing in the working memory.
;;
;; Determining if an object is an instance of a class is a primitive
;; JVM operation and is much more efficient than determining
;; if that object descends from a particular object through
;; Clojure's hierarchy as determined by the isa? function.
;; See Issue 239 for more details.
#?(:clj
(do
;; A marker interface to identify internal facts.
(definterface ISystemFact)
(defrecord NegationResult [gen-rule-name ancestor-bindings]
ISystemFact))
:cljs
(do
(defrecord NegationResult [gen-rule-name ancestor-bindings])
;; Make NegationResult a "system type" so that NegationResult
;; facts are special-cased when matching productions. This serves
;; the same purpose as implementing the ISystemFact Java interface
;; on the Clojure version of NegationResult.
;; ClojureScript does not have definterface; if we experience performance
;; problems in ClojureScript similar to those on the JVM that are
;; described in issue 239 we can investigate a similar strategy in JavaScript.
(derive NegationResult ::system-type)))
;; Schema for the structure returned by the components
;; function on the session protocol.
;; This is simply a comment rather than first-class schema
;; for now since it's unused for validation and created
;; undesired warnings as described at https://groups.google.com/forum/#!topic/prismatic-plumbing/o65PfJ4CUkI
(comment
(def session-components-schema
{:rulebase s/Any
:memory s/Any
:transport s/Any
:listeners [s/Any]
:get-alphas-fn s/Any}))
;; Returns a new session with the additional facts inserted.
(defprotocol ISession
;; Inserts facts.
(insert [session facts])
;; Retracts facts.
(retract [session facts])
;; Fires pending rules and returns a new session where they are in a fired state.
;;
;; Note that clara.rules/fire-rules, the public API for these methods, will handle
;; calling the two-arg fire-rules with an empty map itself, but we add handle it in the fire-rules implementation
;; as well in case anyone is directly calling the fire-rules protocol function or interface method on the LocalSession.
;; The two-argument version of fire-rules was added for issue 249.
(fire-rules [session] [session opts])
;; Runs a query agains thte session.
(query [session query params])
;; Returns the components of a session as defined in the session-components-schema
(components [session]))
;; Left activation protocol for various types of beta nodes.
(defprotocol ILeftActivate
(left-activate [node join-bindings tokens memory transport listener])
(left-retract [node join-bindings tokens memory transport listener])
(description [node])
(get-join-keys [node]))
;; Right activation protocol to insert new facts, connecting alpha nodes
;; and beta nodes.
(defprotocol IRightActivate
(right-activate [node join-bindings elements memory transport listener])
(right-retract [node join-bindings elements memory transport listener]))
;; Specialized right activation interface for accumulator nodes,
;; where the caller has the option of pre-reducing items
;; to reduce the data sent to the node. This would be useful
;; if the caller is not in the same memory space as the accumulator node itself.
(defprotocol IAccumRightActivate
;; Pre-reduces elements, returning a map of bindings to reduced elements.
(pre-reduce [node elements])
;; Right-activate the node with items reduced in the above pre-reduce step.
(right-activate-reduced [node join-bindings reduced memory transport listener]))
(defprotocol IAccumInspect
"This protocol is expected to be implemented on accumulator nodes in the rules network.
It is not expected that users will implement this protocol, and most likely will not call
the protocol function directly."
(token->matching-elements [node memory token]
"Takes a token that was previously propagated from the node,
or a token that is a descendant of such a token, and returns the facts in elements
matching the token propagated from the node. During rules firing
accumulators only propagate bindings created and the result binding
downstream rather than all facts that were accumulated over, but there
are use-cases in session inspection where we want to retrieve the individual facts.
Example: [?min-temp <- (acc/min :temperature) :from [Temperature (= temperature ?loc)]]
[?windspeed <- [WindSpeed (= location ?loc)]]
Given a token propagated from the node for the WindSpeed condition
we could retrieve the Temperature facts from the matching location."))
;; The transport protocol for sending and retracting items between nodes.
(defprotocol ITransport
(send-elements [transport memory listener nodes elements])
(send-tokens [transport memory listener nodes tokens])
(retract-elements [transport memory listener nodes elements])
(retract-tokens [transport memory listener nodes tokens]))
(defn- propagate-items-to-nodes [transport memory listener nodes items propagate-fn]
(doseq [node nodes
:let [join-keys (get-join-keys node)]]
(if (pos? (count join-keys))
;; Group by the join keys for the activation.
(doseq [[join-bindings item-group] (platform/group-by-seq #(select-keys (:bindings %) join-keys) items)]
(propagate-fn node
join-bindings
item-group
memory
transport
listener))
;; The node has no join keys, so just send everything at once
;; (if there is something to send.)
(when (seq items)
(propagate-fn node
{}
items
memory
transport
listener)))))
;; Simple, in-memory transport.
(deftype LocalTransport []
ITransport
(send-elements [transport memory listener nodes elements]
(propagate-items-to-nodes transport memory listener nodes elements right-activate))
(send-tokens [transport memory listener nodes tokens]
(propagate-items-to-nodes transport memory listener nodes tokens left-activate))
(retract-elements [transport memory listener nodes elements]
(propagate-items-to-nodes transport memory listener nodes elements right-retract))
(retract-tokens [transport memory listener nodes tokens]
(propagate-items-to-nodes transport memory listener nodes tokens left-retract)))
;; Protocol for activation of Rete alpha nodes.
(defprotocol IAlphaActivate
(alpha-activate [node facts memory transport listener])
(alpha-retract [node facts memory transport listener]))
;; Protocol for getting the type (e.g. :production and :query) and name of a
;; terminal node.
(defprotocol ITerminalNode
(terminal-node-type [this]))
;; Protocol for getting a node's condition expression.
(defprotocol IConditionNode
(get-condition-description [this]))
(defn get-terminal-node-types
[node]
(->> node
(tree-seq (comp seq :children) :children)
(keep #(when (satisfies? ITerminalNode %)
(terminal-node-type %)))
(into (sorted-set))))
(defn get-conditions-and-rule-names
"Returns a map from conditions to sets of rules."
([node]
(if-let [condition (when (satisfies? IConditionNode node)
(get-condition-description node))]
{condition (get-terminal-node-types node)}
(->> node
:children
(map get-conditions-and-rule-names)
(reduce (partial merge-with into) {})))))
;; Active session during rule execution.
(def ^:dynamic *current-session* nil)
;; Note that this can hold facts directly retracted and facts logically retracted
;; as a result of an external retraction or insertion.
;; The value is expected to be an atom holding such facts.
(def ^:dynamic *pending-external-retractions* nil)
;; The token that triggered a rule to fire.
(def ^:dynamic *rule-context* nil)
(defn ^:private external-retract-loop
"Retract all facts, then group and retract all facts that must be logically retracted because of these
retractions, and so forth, until logical consistency is reached. When an external retraction causes multiple
facts of the same type to be retracted in the same iteration of the loop this improves efficiency since they can be grouped.
For example, if we have a rule that matches on FactA and inserts FactB, and then a later rule that accumulates on FactB,
if we have multiple FactA external retractions it is more efficient to logically retract all the FactB instances at once to minimize the number of times we must re-accumulate on FactB.
This is similar to the function of the pending-updates in the fire-rules* loop."
[get-alphas-fn memory transport listener]
(loop []
(let [retractions (deref *pending-external-retractions*)
;; We have already obtained a direct reference to the facts to be
;; retracted in this iteration of the loop outside the cache. Now reset
;; the cache. The retractions we execute may cause new retractions to be queued
;; up, in which case the loop will execute again.
_ (reset! *pending-external-retractions* [])]
(doseq [[alpha-roots fact-group] (get-alphas-fn retractions)
root alpha-roots]
(alpha-retract root fact-group memory transport listener))
(when (-> *pending-external-retractions* deref not-empty)
(recur)))))
(defn- flush-updates
"Flush all pending updates in the current session. Returns true if there were
some items to flush, false otherwise"
[current-session]
(letfn [(flush-all [current-session flushed-items?]
(let [{:keys [rulebase transient-memory transport insertions get-alphas-fn listener]} current-session
pending-updates (-> current-session :pending-updates uc/get-updates-and-reset!)]
(if (empty? pending-updates)
flushed-items?
(do
(doseq [partition pending-updates
:let [facts (mapcat :facts partition)]
[alpha-roots fact-group] (get-alphas-fn facts)
root alpha-roots]
(if (= :insert (:type (first partition)))
(alpha-activate root fact-group transient-memory transport listener)
(alpha-retract root fact-group transient-memory transport listener)))
;; There may be new pending updates due to the flush just
;; made. So keep flushing until there are none left. Items
;; were flushed though, so flush-items? is now true.
(flush-all current-session true)))))]
(flush-all current-session false)))
(defn insert-facts!
"Place facts in a stateful cache to be inserted into the session
immediately after the RHS of a rule fires."
[facts unconditional]
(if unconditional
(swap! (:batched-unconditional-insertions *rule-context*) into facts)
(swap! (:batched-logical-insertions *rule-context*) into facts)))
(defn rhs-retract-facts!
"Place all facts retracted in the RHS in a buffer to be retracted after
the eval'ed RHS function completes."
[facts]
(swap! (:batched-rhs-retractions *rule-context*) into facts))
(defn ^:private flush-rhs-retractions!
"Retract all facts retracted in the RHS after the eval'ed RHS function completes.
This should only be used for facts explicitly retracted in a RHS.
It should not be used for retractions that occur as part of automatic truth maintenance."
[facts]
(let [{:keys [rulebase transient-memory transport insertions get-alphas-fn listener]} *current-session*
{:keys [node token]} *rule-context*]
;; Update the count so the rule engine will know when we have normalized.
(swap! insertions + (count facts))
(when listener
(l/retract-facts! listener node token facts))
(doseq [[alpha-roots fact-group] (get-alphas-fn facts)
root alpha-roots]
(alpha-retract root fact-group transient-memory transport listener))))
(defn ^:private flush-insertions!
"Perform the actual fact insertion, optionally making them unconditional. This should only
be called once per rule activation for logical insertions."
[facts unconditional]
(let [{:keys [rulebase transient-memory transport insertions get-alphas-fn listener]} *current-session*
{:keys [node token]} *rule-context*]
;; Update the insertion count.
(swap! insertions + (count facts))
;; Track this insertion in our transient memory so logical retractions will remove it.
(if unconditional
(l/insert-facts! listener node token facts)
(do
(mem/add-insertions! transient-memory node token facts)
(l/insert-facts-logical! listener node token facts)))
(-> *current-session* :pending-updates (uc/add-insertions! facts))))
(defn retract-facts!
"Perform the fact retraction."
[facts]
(-> *current-session* :pending-updates (uc/add-retractions! facts)))
;; Record for the production node in the Rete network.
(defrecord ProductionNode [id production rhs]
ILeftActivate
(left-activate [node join-bindings tokens memory transport listener]
;; Provide listeners information on all left-activate calls,
;; but we don't store these tokens in the beta-memory since the production-memory
;; and activation-memory collectively contain all information that ProductionNode
;; needs. See https://github.com/cerner/clara-rules/issues/386
(l/left-activate! listener node tokens)
;; Fire the rule if it's not a no-loop rule, or if the rule is not
;; active in the current context.
(when (or (not (get-in production [:props :no-loop]))
(not (= production (get-in *rule-context* [:node :production]))))
(let [activations (platform/eager-for [token tokens]
(->Activation node token))]
(l/add-activations! listener node activations)
;; The production matched, so add the tokens to the activation list.
(mem/add-activations! memory production activations))))
(left-retract [node join-bindings tokens memory transport listener]
;; Provide listeners information on all left-retract calls for passivity,
;; but we don't store these tokens in the beta-memory since the production-memory
;; and activation-memory collectively contain all information that ProductionNode
;; needs. See https://github.com/cerner/clara-rules/issues/386
(l/left-retract! listener node tokens)
;; Remove pending activations triggered by the retracted tokens.
(let [activations (platform/eager-for [token tokens]
(->Activation node token))
;; We attempt to remove a pending activation for all tokens retracted, but our expectation
;; is that each token may remove a pending activation
;; or logical insertions from a previous rule activation but not both.
;; We first attempt to use each token to remove a pending activation but keep track of which
;; tokens were not used to remove an activation.
[removed-activations unremoved-activations]
(mem/remove-activations! memory production activations)
_ (l/remove-activations! listener node removed-activations)
unremoved-tokens (mapv :token unremoved-activations)
;; Now use each token that was not used to remove a pending activation to remove
;; the logical insertions from a previous activation if the truth maintenance system
;; has a matching previous activation.
token-insertion-map (mem/remove-insertions! memory node unremoved-tokens)]
(when-let [insertions (seq (apply concat (vals token-insertion-map)))]
;; If there is current session with rules firing, add these items to the queue
;; to be retracted so they occur in the same order as facts being inserted.
(cond
;; Both logical retractions resulting from rule network activity and manual RHS retractions
;; expect *current-session* to be bound since both happen in the context of a fire-rules call.
*current-session*
;; Retract facts that have become untrue, unless they became untrue
;; because of an activation of the current rule that is :no-loop
(when (or (not (get-in production [:props :no-loop]))
(not (= production (get-in *rule-context* [:node :production]))))
(do
;; Notify the listener of logical retractions.
;; Note that this notification happens immediately, while the
;; alpha-retract notification on matching alpha nodes will happen when the
;; retraction is actually removed from the buffer and executed in the rules network.
(doseq [[token token-insertions] token-insertion-map]
(l/retract-facts-logical! listener node token token-insertions))
(retract-facts! insertions)))
;; Any session implementation is required to bind this during external retractions and insertions.
*pending-external-retractions*
(do
(doseq [[token token-insertions] token-insertion-map]
(l/retract-facts-logical! listener node token token-insertions))
(swap! *pending-external-retractions* into insertions))
:else
(throw (ex-info (str "Attempting to retract from a ProductionNode when neither *current-session* nor "
"*pending-external-retractions* is bound is illegal.")
{:node node
:join-bindings join-bindings
:tokens tokens}))))))
(get-join-keys [node] [])
(description [node] "ProductionNode")
ITerminalNode
(terminal-node-type [this] [:production (:name production)]))
;; The QueryNode is a terminal node that stores the
;; state that can be queried by a rule user.
(defrecord QueryNode [id query param-keys]
ILeftActivate
(left-activate [node join-bindings tokens memory transport listener]
(l/left-activate! listener node tokens)
(mem/add-tokens! memory node join-bindings tokens))
(left-retract [node join-bindings tokens memory transport listener]
(l/left-retract! listener node tokens)
(mem/remove-tokens! memory node join-bindings tokens))
(get-join-keys [node] param-keys)
(description [node] (str "QueryNode -- " query))
ITerminalNode
(terminal-node-type [this] [:query (:name query)]))
(defn node-rule-names
[child-type node]
(->> node
(tree-seq (comp seq :children) :children)
(keep child-type)
(map :name)
(distinct)
(sort)))
(defn- list-of-names
"Returns formatted string with correctly pluralized header and
list of names. Returns nil if no such node is found."
[singular plural prefix names]
(let [msg-for-unnamed (str " An unnamed " singular ", provide names to your "
plural " if you want them to be identified here.")
names-string (->> names
(sort)
(map #(if (nil? %) msg-for-unnamed %))
(map #(str prefix " " %))
(string/join "\n"))]
(if (pos? (count names))
(str prefix plural ":\n" names-string "\n"))))
(defn- single-condition-message
[condition-number [condition-definition terminals]]
(let [productions (->> terminals
(filter (comp #{:production} first))
(map second))
queries (->> terminals
(filter (comp #{:query} first))
(map second))
production-section (list-of-names "rule" "rules" " " productions)
query-section (list-of-names "query" "queries" " " queries)]
(string/join
[(str (inc condition-number) ". " condition-definition "\n")
production-section
query-section])))
(defn- throw-condition-exception
"Adds a useful error message when executing a constraint node raises an exception."
[{:keys [cause node fact env bindings] :as args}]
(let [bindings-description (if (empty? bindings)
"with no bindings"
(str "with bindings\n " bindings))
facts-description (if (contains? args :fact)
(str "when processing fact\n " (pr-str fact))
"with no fact")
message-header (string/join ["Condition exception raised.\n"
(str facts-description "\n")
(str bindings-description "\n")
"Conditions:\n"])
conditions-and-rules (get-conditions-and-rule-names node)
condition-messages (->> conditions-and-rules
(map-indexed single-condition-message)
(string/join "\n"))
message (str message-header "\n" condition-messages)]
(throw (ex-info message
{:fact fact
:bindings bindings
:env env
:conditions-and-rules conditions-and-rules}
cause))))
(defn- alpha-node-matches
[facts env activation node]
(platform/eager-for [fact facts
:let [bindings (try (activation fact env)
(catch #?(:clj Exception :cljs :default) e
(throw-condition-exception {:cause e
:node node
:fact fact
:env env})))]
:when bindings] ; FIXME: add env.
[fact bindings]))
;; Record representing alpha nodes in the Rete network,
;; each of which evaluates a single condition and
;; propagates matches to its children.
(defrecord AlphaNode [id env children activation fact-type]
IAlphaActivate
(alpha-activate [node facts memory transport listener]
(let [fact-binding-pairs (alpha-node-matches facts env activation node)]
(l/alpha-activate! listener node (map first fact-binding-pairs))
(send-elements
transport
memory
listener
children
(platform/eager-for [[fact bindings] fact-binding-pairs]
(->Element fact bindings)))))
(alpha-retract [node facts memory transport listener]
(let [fact-binding-pairs (alpha-node-matches facts env activation node)]
(l/alpha-retract! listener node (map first fact-binding-pairs))
(retract-elements
transport
memory
listener
children
(platform/eager-for [[fact bindings] fact-binding-pairs]
(->Element fact bindings))))))
(defrecord RootJoinNode [id condition children binding-keys]
ILeftActivate
(left-activate [node join-bindings tokens memory transport listener]
;; This specialized root node doesn't need to deal with the
;; empty token, so do nothing.
)
(left-retract [node join-bindings tokens memory transport listener]
;; The empty token can't be retracted from the root node,
;; so do nothing.
)
(get-join-keys [node] binding-keys)
(description [node] (str "RootJoinNode -- " (:text condition)))
IRightActivate
(right-activate [node join-bindings elements memory transport listener]
(l/right-activate! listener node elements)
;; Add elements to the working memory to support analysis tools.
(mem/add-elements! memory node join-bindings elements)
;; Simply create tokens and send it downstream.
(send-tokens
transport
memory
listener
children
(platform/eager-for [{:keys [fact bindings] :as element} elements]
(->Token [[fact (:id node)]] bindings))))
(right-retract [node join-bindings elements memory transport listener]
(l/right-retract! listener node elements)
;; Remove matching elements and send the retraction downstream.
(retract-tokens
transport
memory
listener
children
(platform/eager-for [{:keys [fact bindings] :as element} (mem/remove-elements! memory node join-bindings elements)]
(->Token [[fact (:id node)]] bindings))))
IConditionNode
(get-condition-description [this]
(let [{:keys [type constraints]} condition]
(into [type] constraints))))
;; Record for the join node, a type of beta node in the rete network. This node performs joins
;; between left and right activations, creating new tokens when joins match and sending them to
;; its descendents.
(defrecord HashJoinNode [id condition children binding-keys]
ILeftActivate
(left-activate [node join-bindings tokens memory transport listener]
;; Add token to the node's working memory for future right activations.
(mem/add-tokens! memory node join-bindings tokens)
(l/left-activate! listener node tokens)
(send-tokens
transport
memory
listener
children
(platform/eager-for [element (mem/get-elements memory node join-bindings)
token tokens
:let [fact (:fact element)
fact-binding (:bindings element)]]
(->Token (conj (:matches token) [fact id]) (conj fact-binding (:bindings token))))))
(left-retract [node join-bindings tokens memory transport listener]
(l/left-retract! listener node tokens)
(retract-tokens
transport
memory
listener
children
(platform/eager-for [token (mem/remove-tokens! memory node join-bindings tokens)
element (mem/get-elements memory node join-bindings)
:let [fact (:fact element)
fact-bindings (:bindings element)]]
(->Token (conj (:matches token) [fact id]) (conj fact-bindings (:bindings token))))))
(get-join-keys [node] binding-keys)
(description [node] (str "JoinNode -- " (:text condition)))
IRightActivate
(right-activate [node join-bindings elements memory transport listener]
(mem/add-elements! memory node join-bindings elements)
(l/right-activate! listener node elements)
(send-tokens
transport
memory
listener
children
(platform/eager-for [token (mem/get-tokens memory node join-bindings)
{:keys [fact bindings] :as element} elements]
(->Token (conj (:matches token) [fact id]) (conj (:bindings token) bindings)))))
(right-retract [node join-bindings elements memory transport listener]
(l/right-retract! listener node elements)
(retract-tokens
transport
memory
listener
children
(platform/eager-for [{:keys [fact bindings] :as element} (mem/remove-elements! memory node join-bindings elements)
token (mem/get-tokens memory node join-bindings)]
(->Token (conj (:matches token) [fact id]) (conj (:bindings token) bindings)))))
IConditionNode
(get-condition-description [this]
(let [{:keys [type constraints]} condition]
(into [type] constraints))))
(defn- join-node-matches
[node join-filter-fn token fact fact-bindings env]
(let [beta-bindings (try (join-filter-fn token fact fact-bindings {})
(catch #?(:clj Exception :cljs :default) e
(throw-condition-exception {:cause e
:node node
:fact fact
:env env
:bindings (merge (:bindings token)
fact-bindings)})))]
beta-bindings))
(defrecord ExpressionJoinNode [id condition join-filter-fn children binding-keys]
ILeftActivate
(left-activate [node join-bindings tokens memory transport listener]
;; Add token to the node's working memory for future right activations.
(mem/add-tokens! memory node join-bindings tokens)
(l/left-activate! listener node tokens)
(send-tokens
transport
memory
listener
children
(platform/eager-for [element (mem/get-elements memory node join-bindings)
token tokens
:let [fact (:fact element)
fact-binding (:bindings element)
beta-bindings (join-node-matches node join-filter-fn token fact fact-binding {})]
:when beta-bindings]
(->Token (conj (:matches token) [fact id])
(conj fact-binding (:bindings token) beta-bindings)))))
(left-retract [node join-bindings tokens memory transport listener]
(l/left-retract! listener node tokens)
(retract-tokens
transport
memory
listener
children
(platform/eager-for [token (mem/remove-tokens! memory node join-bindings tokens)
element (mem/get-elements memory node join-bindings)
:let [fact (:fact element)
fact-bindings (:bindings element)
beta-bindings (join-node-matches node join-filter-fn token fact fact-bindings {})]
:when beta-bindings]
(->Token (conj (:matches token) [fact id])
(conj fact-bindings (:bindings token) beta-bindings)))))
(get-join-keys [node] binding-keys)
(description [node] (str "JoinNode -- " (:text condition)))
IRightActivate
(right-activate [node join-bindings elements memory transport listener]
(mem/add-elements! memory node join-bindings elements)
(l/right-activate! listener node elements)
(send-tokens
transport
memory
listener
children
(platform/eager-for [token (mem/get-tokens memory node join-bindings)
{:keys [fact bindings] :as element} elements
:let [beta-bindings (join-node-matches node join-filter-fn token fact bindings {})]
:when beta-bindings]
(->Token (conj (:matches token) [fact id])
(conj (:bindings token) bindings beta-bindings)))))
(right-retract [node join-bindings elements memory transport listener]
(l/right-retract! listener node elements)
(retract-tokens
transport
memory
listener
children
(platform/eager-for [{:keys [fact bindings] :as element} (mem/remove-elements! memory node join-bindings elements)
token (mem/get-tokens memory node join-bindings)
:let [beta-bindings (join-node-matches node join-filter-fn token fact bindings {})]
:when beta-bindings]
(->Token (conj (:matches token) [fact id])
(conj (:bindings token) bindings beta-bindings)))))
IConditionNode
(get-condition-description [this]
(let [{:keys [type constraints original-constraints]} condition
full-constraints (if (seq original-constraints)
original-constraints
constraints)]
(into [type] full-constraints))))
;; The NegationNode is a beta node in the Rete network that simply
;; negates the incoming tokens from its ancestors. It sends tokens
;; to its descendent only if the negated condition or join fails (is false).
(defrecord NegationNode [id condition children binding-keys]
ILeftActivate
(left-activate [node join-bindings tokens memory transport listener]
;; Add token to the node's working memory for future right activations.
(l/left-activate! listener node tokens)
(mem/add-tokens! memory node join-bindings tokens)
(when (empty? (mem/get-elements memory node join-bindings))
(send-tokens transport memory listener children tokens)))
(left-retract [node join-bindings tokens memory transport listener]
(l/left-retract! listener node tokens)
(mem/remove-tokens! memory node join-bindings tokens)
(when (empty? (mem/get-elements memory node join-bindings))
(retract-tokens transport memory listener children tokens)))
(get-join-keys [node] binding-keys)
(description [node] (str "NegationNode -- " (:text condition)))
IRightActivate
(right-activate [node join-bindings elements memory transport listener]
;; Immediately evaluate whether there are previous elements since mem/get-elements
;; returns a mutable list with a LocalMemory on the JVM currently.
(let [previously-empty? (empty? (mem/get-elements memory node join-bindings))]
(l/right-activate! listener node elements)
(mem/add-elements! memory node join-bindings elements)
;; Retract tokens that matched the activation if no element matched the negation previously.
;; If an element matched the negation already then no elements were propagated and there is
;; nothing to retract.
(when previously-empty?
(retract-tokens transport memory listener children (mem/get-tokens memory node join-bindings)))))
(right-retract [node join-bindings elements memory transport listener]
(l/right-retract! listener node elements)
(mem/remove-elements! memory node join-bindings elements)
(when (empty? (mem/get-elements memory node join-bindings))
(send-tokens transport memory listener children (mem/get-tokens memory node join-bindings))))
IConditionNode
(get-condition-description [this]
(let [{:keys [type constraints]} condition]
[:not (into [type] constraints)])))
(defn- matches-some-facts?
"Returns true if the given token matches one or more of the given elements."
[node token elements join-filter-fn condition]
(some (fn [{:keys [fact bindings]}]
(join-node-matches node join-filter-fn token fact bindings (:env condition)))
elements))
;; A specialization of the NegationNode that supports additional tests
;; that have to occur on the beta side of the network. The key difference between this and the simple
;; negation node is the join-filter-fn, which allows negation tests to
;; be applied with the parent token in context, rather than just a simple test of the non-existence
;; on the alpha side.
(defrecord NegationWithJoinFilterNode [id condition join-filter-fn children binding-keys]
ILeftActivate
(left-activate [node join-bindings tokens memory transport listener]
;; Add token to the node's working memory for future right activations.
(l/left-activate! listener node tokens)
(mem/add-tokens! memory node join-bindings tokens)
(send-tokens transport
memory
listener
children
(let [elements (mem/get-elements memory node join-bindings)]
(platform/eager-for [token tokens
:when (not (matches-some-facts? node
token
elements
join-filter-fn
condition))]
token))))
(left-retract [node join-bindings tokens memory transport listener]
(l/left-retract! listener node tokens)
(mem/remove-tokens! memory node join-bindings tokens)
(retract-tokens transport
memory
listener
children
;; Retract only if it previously had no matches in the negation node,
;; and therefore had an activation.
(let [elements (mem/get-elements memory node join-bindings)]
(platform/eager-for [token tokens
:when (not (matches-some-facts? node
token
elements
join-filter-fn
condition))]
token))))
(get-join-keys [node] binding-keys)
(description [node] (str "NegationWithJoinFilterNode -- " (:text condition)))
IRightActivate
(right-activate [node join-bindings elements memory transport listener]
(l/right-activate! listener node elements)
(let [previous-elements (mem/get-elements memory node join-bindings)]
;; Retract tokens that matched the activation, since they are no longer negated.
(retract-tokens transport
memory
listener
children
(platform/eager-for [token (mem/get-tokens memory node join-bindings)
;; Retract downstream if the token now has matching elements and didn't before.
;; We check the new elements first in the expectation that the new elements will be
;; smaller than the previous elements most of the time
;; and that the time to check the elements will be proportional
;; to the number of elements.
:when (and (matches-some-facts? node
token
elements
join-filter-fn
condition)
(not (matches-some-facts? node
token
previous-elements
join-filter-fn
condition)))]
token))
;; Adding the elements will mutate the previous-elements since, on the JVM, the LocalMemory
;; currently returns a mutable List from get-elements after changes in issue 184. We need to use the
;; new and old elements in the logic above as separate collections. Therefore we need to delay updating the
;; memory with the new elements until after we are done with previous-elements.
(mem/add-elements! memory node join-bindings elements)))
(right-retract [node join-bindings elements memory transport listener]
(l/right-retract! listener node elements)
(mem/remove-elements! memory node join-bindings elements)
(send-tokens transport
memory
listener
children
(let [remaining-elements (mem/get-elements memory node join-bindings)]
(platform/eager-for [token (mem/get-tokens memory node join-bindings)
;; Propagate tokens when some of the retracted facts joined
;; but none of the remaining facts do.
:when (and (matches-some-facts? node
token
elements
join-filter-fn
condition)
(not (matches-some-facts? node
token
remaining-elements
join-filter-fn
condition)))]
token))))
IConditionNode
(get-condition-description [this]
(let [{:keys [type constraints original-constraints]} condition
full-constraints (if (seq original-constraints)
original-constraints
constraints)]
[:not (into [type] full-constraints)])))
(defn- test-node-matches
[node test-handler env token]
(let [test-result (try
(test-handler token)
(catch #?(:clj Exception :cljs :default) e
(throw-condition-exception {:cause e
:node node
:env env
:bindings (:bindings token)})))]
test-result))
;; The test node represents a Rete extension in which an arbitrary test condition is run
;; against bindings from ancestor nodes. Since this node
;; performs no joins it does not accept right activations or retractions.
(defrecord TestNode [id test children]
ILeftActivate
(left-activate [node join-bindings tokens memory transport listener]
(l/left-activate! listener node tokens)
(send-tokens
transport
memory
listener
children
(platform/eager-for
[token tokens
:when (test-node-matches node (:handler test) {} token)]
token)))
(left-retract [node join-bindings tokens memory transport listener]
(l/left-retract! listener node tokens)
(retract-tokens transport memory listener children tokens))
(get-join-keys [node] [])
(description [node] (str "TestNode -- " (:text test)))
IConditionNode
(get-condition-description [this]
(into [:test] (:constraints test))))
(defn- do-accumulate
"Runs the actual accumulation. Returns the accumulated value."
[accumulator facts]
(r/reduce (:reduce-fn accumulator)
(:initial-value accumulator)
facts))
(defn- retract-accumulated
"Helper function to retract an accumulated value."
[node accum-condition accumulator result-binding token converted-result fact-bindings transport memory listener]
(let [new-facts (conj (:matches token) [converted-result (:id node)])
new-bindings (merge (:bindings token)
fact-bindings
(when result-binding
{ result-binding
converted-result}))]
(retract-tokens transport memory listener (:children node)
[(->Token new-facts new-bindings)])))
(defn- send-accumulated
"Helper function to send the result of an accumulated value to the node's children."
[node accum-condition accumulator result-binding token converted-result fact-bindings transport memory listener]
(let [new-bindings (merge (:bindings token)
fact-bindings
(when result-binding
{ result-binding
converted-result}))
;; This is to check that the produced accumulator result is
;; consistent with any variable from another rule condition
;; that has the same binding. If another condition binds something