r/Clojure • • Feb 10 '21

O'Doyle Rules - a Clojure rules engine for the best of us

https://youtu.be/XONRaJJAhpA
76 Upvotes

24 comments sorted by

9

u/SimonGray Feb 10 '21 edited Feb 10 '21

I enjoyed this rundown as I didn't really know what a rules engine is. I get this impression that quite a few Clojure libraries are converging on this triple unification idea.

Since this is also a CLJS lib I wonder whether anyone tried using it for making a SPA? Seems like a simple way to integrate data from Datomic or another Clojure Datalog db into the logic of a web app. I wonder what the performance is like, though. The fans were spinning a lot in the video, but that might have been the screen capture process itself doing that.

27

u/joinr Feb 11 '21 edited Feb 11 '21

My general expectation is that anything based on tuple stores with ordered indexes that have logarithmic complexity are going to be inherently slower than column stores with better complexity bounds. In-memory associative stores or similar O(1) indexing will probably dominate for many use cases (e.g. absolute performance), although you trade that off for the extreme flexibility in querying that the tuple-stores provide. I did some recent experiments with an existing entity component system built on an optimized column store made from associative structures (been in production for years), and replaced the backing store with datascript to compare performance. Even with optimized reads (using indices directly) and caching I get from between 11-40x worse performance for similar queries (just reads). No idea what updates are like. I thought about trying something similar with datalevin and asami to see how they fared (potentially faster in practice), but didn't get there. Meander got closer to having a logic-like query engine with efficient access over maps, but still not as fast as the associative entity store.

I'm not familiar with the implementation in odoyle (the terminology used is out of scope for me), but it looks like the #Fact[e a v] facts are being stored in nested {e {a #Fact[e a v]}} maps. Since the facts are records, it's plausible that you could get effectively the same performance via the associative indices that I'm used to, although since they aren't stored in sorted indices, range queries aren't built in like in most datalog tuple stores (no big deal if you don't need them though).

I find that the stated advantages of rules (run "automatically" [really runs when data changes], can be reasoned about in isolation, eliminate map fatigue) apply equally well with behavior trees on top of an entity store (a column store of {a {e v}}, with indices for for {e #{a}}). You get similar properties (declarative, isolated, dynamic), with the exception that behaviors compose via combinators that form a little dsl (sequence, if, and, or, etc.). There's a bit more structure IMO than the rules approach (they're trees by design), although it seems plausible to examine the rules and extract a structure based on data dependencies (probably very easy to visualize since rule definitions are basically data).

I see the applicability of this style of programming as opposed to legacy gui stuff with observers/observables or plain event subscriptions, and even with more recent stuff like react/re-frame or rx stuff. It superficially obviates all the plumbing around hooking up interested state transition functions to relevant pieces of state and allows granular "watching" of state via checking for patterns on inserts. It's elegant in that respect; one trade off (I think benefit) is how rules "communicate", which is instead of bilateral or multilateral event subscriptions, you just accrete new data into the store and interested parties pick up on it. The accretive model is very familiar in my work (any entity component store thing really), and is very powerful; just add new data for a new thing, and wire up the relevant stuff to look for the existence of that data and operate based on it. If that wiring can be done declaratively where the engine handles it for you, it's great.

The only things I'd be curious to see are how priority is handled. In behavior trees, it's typical to have a sort of hierarchy of needs represented in the structure of the tree itself (behaviors are typically evaluated in pre-order traversal, so parents succeed/fail based on child success/failure). I'm curious to see how a similar priority is established in the rules system where it's conceivable that two rules operating on identical data dependencies could have different priorities. I imagine establishing priority via the default "communicate with facts," but it's not obvious at the moment.

It would also be interesting to see how the rules system performs with something number heavy with lots of guaranteed updates, like a particle simulation with collisions and physics. Could demonstrate using external systems (like a physics engine) to provide fact updates for the rules, or having some means of using the rules + facts to communicate with an efficient external engine that does all the computation and updating.

I would bet the fan spinning was from vidcap competing for GPU resources; it only happened once the game popped up, which probably engaged webgl context.

[p.s.] The rules engine stuff coupled with a fact store reminds me of the old BlackBoard architecture from Game/AI programming from the 90's-2000's.

5

u/SimonGray Feb 11 '21

Other people have already awarded you, but I just wanted to say thank you for this awesome performance review.

8

u/joinr Feb 11 '21

Anyone who made it past the wall of text should be rewarded, hah! :)

12

u/oakes Feb 11 '21

In-memory associative stores or similar O(1) indexing will probably dominate for many use cases (e.g. absolute performance), although you trade that off for the extreme flexibility in querying that the tuple-stores provide.

No doubt there's a runtime cost in joining the facts together, so naturally a system that lumps facts together into records (like clara) will have to do fewer joins, and should be faster. I figured out that i could at least deduplicate my joins with derived facts as i explained here, which ended up being a really big perf boost. But there's still a tradeoff, and one where almost everyone should favor flexibility, i think.

I see the applicability of this style of programming as opposed to legacy gui stuff with observers/observables or plain event subscriptions, and even with more recent stuff like react/re-frame or rx stuff. It superficially obviates all the plumbing around hooking up interested state transition functions to relevant pieces of state and allows granular "watching" of state via checking for patterns on inserts.

Thank you! Not to get into clojure tropes, but aren't events just data? Why do we need to have a special concept of an event, when we can just insert a fact that represents the event and write rules that react to it?

The only things I'd be curious to see are how priority is handled.

It isn't :D That is, if you mean something like clara's salience. Right now, if you have two rules in o'doyle with the same :what block, the one that fires first is effectively random (the order of their node ids in a set). You could probably enforce order through clever use of facts or :when conditions, but honestly, if order really matters, and it's awkward to communicate that with the data itself, maybe what you really need is one rule with two functions, rather than two rules.

It would also be interesting to see how the rules system performs with something number heavy with lots of guaranteed updates, like a particle simulation with collisions and physics.

In a way my dungeon crawler game is kind of what you describe -- the delta time is inserted every frame, which forces most of the rules to fire, including movement/collisions of characters. But at some point my nim rules engine would be more appropriate. I actually wrote a nim version of the same game and i'm sure you could have a party adding more ogres and elementals, especially if you compile in release mode.

3

u/joinr Feb 11 '21

Why do we need to have a special concept of an event, when we can just insert a fact that represents the event and write rules that react to it?

For folks addicted to event subscription/handling, the insertion of the fact is the event, and reacting to the new fact is event handling. I think the advantage is that there's basically a universal "event handler" that knows which handlers care about which events based on flexible pattern matching (as opposed to primitive event-type, or rx style composed event flows). So any granular fact is now observable or reactive, if the ruleset deems it so via dependency/interest. While the event "vocabulary" is now potentially unbounded, you have an approachable "handler vocabulary" that tames it efficiently. [This is perhaps the first time in 10 years that I have developed a decent intuition for Rete, hah].

Coming from the legacy effectful worldview where you fire events, handle them, and try to watch or otherwise "log" stuff to get a sense of how the system evolves, the ability to retain all this directly in the store ends up being really useful (particularly for verification or analysis). If I have a sequence of stores which represent discrete changes over time, it's trivial to write functions to render or otherwise analyze that. The "game loop" is just a reduction (or unfold or iterate), and the notion of an effectul "engine" turns into a computation where you're computing a sequence of frames and doing something with them.

But at some point my nim rules engine would be more appropriate.

Aside from the platform difference and possible compiler optimizations, what's different in the implementation with odoyle? Mutable?

One last question: are you able to define rules that add rules to the current ruleset (I know the derived rules do this, but they are read-only)? In other words, is the ruleset itself is part of the evaluation context for "firing", much like the event network can be? You can probably accomplish everything with pre-determined static rule networks and existential data; I'm curious if this is precluded by design or allowed. I would think that it means recomputing the network for the rules to fire on every time a new rule is added to preserve efficiency (as opposed to legacy event handlers just "adding" a new subscriber or publishing a new event).

6

u/oakes Feb 12 '21

Aside from the platform difference and possible compiler optimizations, what's different in the implementation with odoyle? Mutable?

The algorithm is the same but yes it's mutable. Maybe the most interesting difference that affects performance is that in nim i can generate a special stack-allocated type to store your matches internally. It is a sum type, which nim calls an object variant, that has a "branch" for each rule. Unsurprisingly this was a huge perf improvement over using hash tables. Generating types with a macro is some wild stuff :D

One last question: are you able to define rules that add rules to the current ruleset (I know the derived rules do this, but they are read-only)?

Yeah you can add a rule to the session at any time, including from inside a :then block. You just use reset! like this: (o/reset! (reduce o/add-rule o/*session* new-rules)), where new-rules is presumably created by the ruleset macro somewhere.

Until you mentioned it i had never tried doing this, but it works. The only practical problem is that o'doyle doesn't let you add a rule whose name already exists, so if this rule fires more than once, it'll throw. There also isn't a way to remove or replace an existing rule, because the need hasn't come up yet.

2

u/daver Feb 14 '21

I find that the stated advantages of rules (run "automatically" [really runs when data changes], can be reasoned about in isolation, eliminate map fatigue) apply equally well with behavior trees on top of an entity store (a column store of {a {e v}}, with indices for for {e #{a}}). You get similar properties (declarative, isolated, dynamic), with the exception that behaviors compose via combinators that form a little dsl (sequence, if, and, or, etc.). There's a bit more structure IMO than the rules approach (they're trees by design), although it seems plausible to examine the rules and extract a structure based on data dependencies (probably very easy to visualize since rule definitions are basically data)

u/joinr, this sounds interesting. Do you have any references (e.g., code or papers) you can point me to? I'm particularly interested in your statement about composing behaviors via combinators and the DSL. Thanks!

5

u/joinr Feb 15 '21 edited Feb 15 '21

There's a large volume of work on behavior trees since the nineties. I believe Halo popularized them, and they (Bungie) presented quite a bit as well as published papers.

As far as code, my implementation focuses on the functional approach. It has quite a bit of inline documentation regarding the concepts.

The organizational idea is to define small focused behaviors that pick up on pieces of the context to determine if they execute. We use a function (beval) to evaluate a behavior in an initial context (similar to a reduce). If a behavior doesn't execute it fails (returns a failure result with the context), if it executes its success depends on the internals. At the plain level, it's just a function that takes a context and returns an entry of [:success ctx] or [:fail ctx] with some resulting context. With some sugar (the befn macro), I allow nil to be interpreted as [:fail ctx] (very useful), and define additional conveniences to treat maps and records as contexts to convey information with the "args" being keys in the context. At the bottom though, it's just a function that takes a map an spits out a success/fail result.

Since behaviors compose, it's useful to return behaviors instead of the fixed point we're converging on in beval (success or failure), so we can return functions or IBehaviorTree implementations. If those are returned, execution continues according to the new behavior (or the applied function). There are pre-supplied combinators that form nodes in the behavior tree, like ->and, and ->or, which implement success/failure semantics. ->and will only succeed if all of its children succeed. ->or will succeed as soon as any return success, otherwise fails. With these in place you can build pretty complex trees with local reasoning:

There's a stress test in the testing ns, of which the behavior-related stuff looks like this (I re-ordered it for presentation purposes, I typically define this stuff in a clojure friendly way, building "up" more complex behaviors as you go down the through the source, this is "top down" for visual purposes). While there is some impure mutation in here, nothing in the library forces you do that (it's an optimization) and you can easily work with pure contexts as well.

;;The root of the behavior tree
(befn default ^behaviorenv [entity]
      (->or [(->and [check-messages
                     handle-messages])
             advance]))

We have a truee composed of 3 behaviors combined using ->or and ->and. If we beval default against a behavior context (say a map with an :entity key), then the evaluation would apply ->or semantics to its children, in this case the ->and subtree and the advance behavior. beval on the ->and subtree determines success if all of its children succeed, so check-messages and handle-messages must both return a success context. If they do, that success is returned from ->or and we're done. If the either behavior fails, then ->and fails, and we contine to the next child in ->or, advance. advance either succeeds or fails and yields the resulting context. This forms a sort of Maslow's hierarchy of needs, where we can combine individual behaviors into prioritized order (can also trivially randomize), and use the semantics of nodes like ->or, ->and, ->if, etc. to conditionally branch as necessary. Leaf or primitive behaviors can just focus on picking up data they need from the context to do their job, and if that doesn't doesn't exist or match, the fail (do nothing). This creates a very flexible means for describing behavior IMO, and it works will in the FP approach (IME). So it's common in this design to see a lot of when, when-let binding up front picking up information from the context, which acts as a simple cheap pattern match (more complex matching could easily be done e.g. via core.match or even unification) that shunts to failure. I like it since I just specify the data the behavior needs/expects "locally" in the args for befn (basically keys in the map). It gets back to a simple examination of functional dependency and reasoning locally. In plain language, the default behavior will try to check pending messages for the entity and handle them, otherwise it will advance the entity.

;;leaf
(befn check-messages ^behaviorenv [entity current-messages ctx]
      (let [old-msgs (get (deref! entity) :messages)]
        (when-let [msgs (pq/chunk-peek! old-msgs)]
          (let [new-msgs (rconcat (r/map val  msgs) current-messages)
                _        (b/swap!! entity (fn [m]
                                            (assoc m :messages
                                                    (pq/chunk-pop! old-msgs msgs)
                                                    )))]
            (bind!! {:current-messages new-msgs})))))

;;leaf
(befn handle-messages ^behaviorenv {:keys [entity current-messages ctx] :as benv}
      (when current-messages
        (reduce (fn [acc msg]
                  (do ;(debug [:handling msg])
                    (message-handler msg (val! acc))))
                (success benv)
                current-messages)))

;;subtree
(befn advance ^behaviorenv [entity ctx]
      (if (not (identical? (:state (deref! entity)) :spawn))
        (->and [wait-in-state move])
        spawn))

;;leaf
(befn wait-in-state ^behaviorenv [entity current-message ctx]
  (let [msg    current-message
        t     (get msg :t)
        delta (- t (get (deref! entity) :t))]
    (when-let [duration (get  (deref! entity) :wait-time)]
      (if (<= delta duration) ;time remains or is zero.
        (merge!!  entity {:wait-time (- duration delta)
                          :t t}) ;;update the time.
        (do ;can't wait out entire time in this state.
          (merge!! entity {:wait-time 0
                           :t (- t duration)}) ;;still not up-to-date
           ;;have we handled the message?
           ;;what if time remains? this is akin to roll-over behavior.
           ;;we'll register that time is left over. We can determine what
           ;;to do in the next evaluation.  For now, we defer it.
          (bind!! {:current-message (assoc msg :delta (- delta duration))}))))))

;;subtree
(def move
   (->and [choose-state
           choose-time
           notify-change
           schedule-update]))

;;subtree
(befn spawn ^behaviorenv {:keys [entity] :as ctx}
      (when (identical? (:state (deref! entity)) :spawning)
        (->and [(->do (fn [_] (debug (str  "Entity " (:name (deref! entity)) " spawned"))))
                 move])))

;;leaf
(befn choose-state  ^behaviorenv [entity]
      (let [nxt (case (:state (deref! entity))
                                     :dwelling  :deploying
                                     :deploying :dwelling
                                     :dwelling
                                     )]
        (push! entity :state nxt)))

;;leaf
(befn choose-time ^behaviorenv [entity]
      (let [twait
            (case (:state (deref! entity))
                                 :dwelling  (unchecked-add (int 365)  (rand-int 730))
                                 :deploying (unchecked-add (int 230)  (rand-int 40)))]
        (push! entity :wait-time twait)))

I elided some noisey low-level stuff that's in there for speed experiments (basically alternatives to the polymorphic-and-slower clojure.core functions).

2

u/daver Feb 15 '21

Very helpful! Thanks!

1

u/[deleted] Feb 15 '21

You're welcome.

3

u/olymk2 Feb 11 '21

This sounds a bit like fulcro, I was watching this video https://www.youtube.com/watch?v=r1bMQxTr2QA and seems he is showing a very similar pattern.

3

u/scarredwaits Feb 14 '21

This looks very appealling, but I have a question about it's applicability to UIs. If you are in a context where you have to fully handle the lifecycle of UI components (create, update, remove), as opposed to React or the direct drawing mode of a games engine, how do you detect that a fact was just inserted instead of an existing fact being updated? Also is there a way to detect retractions?

3

u/oakes Feb 14 '21

I think it'd be best to represent the lifecycle event as a separate fact. So you could insert [component-id ::event :create] and have a rule that receives that in its :what block. There probably is a way to distinguish between new vs updated facts but representing this with its own fact seems more explicit and flexible (you can represent more than two states).

You can use :then-finally to react to retractions but you won't have access to the retracted fact. It's mainly meant for running queries to create derived facts, so not really the use case you seem to have.

2

u/scarredwaits Feb 14 '21

Thanks! I need some time to wrap my head around this, it could work. I'm thinking of using o'doyle rules with a Swing app I'm developing, and there is no React in Swing and I'm not in the mood to invent it. So all my :then blocks would have to be effectful creation/modification/removal of Swing components depending on what's happening with my facts. Does that sound like it would work?

3

u/oakes Feb 15 '21

That sounds neat. Yeah i think it should be possible to make rules that do all the swing mutations. But if you want it to be really general and work with all the different kinds of components in the framework, you will probably end up inventing react in swing :P Something that is really targeted for just your needs seems doable though.

Just keep in mind that those mutations have to happen on swing's render thread. So you either need to wrap them in SwingUtilities/invokeLater or make sure you only modify the o'doyle session on that thread.

2

u/Bob_la_tige Feb 14 '21

Let's say I have a rule that trigger when :what [player ::attack opponent].
To compute the result I need more data like the health and damage, but I don't think I want them to be described in my :what section because then the rule will trigger when the damage or health changes, so I need to fetch the data with a query on the *session inside of the :then statement ?

4

u/oakes Feb 14 '21

You can still put them in the :what block; just put {:then false} in the tuples if you don't want their updates to trigger the :then block. So it would look like this:

:what
[player-id ::attack opponent-id]
[player-id ::damage damage {:then false}]
[opponent-id ::health health {:then false}]

2

u/Bob_la_tige Feb 14 '21

I tried that but when the fact ::attack arrive before ::damage is available then it will not trigger, but then when later on ::damage is ready the rule trigger even with {:then false}

3

u/oakes Feb 15 '21

Yeah that's by design. Rules will always wait until they have a complete match, and once they do, they will fire as long as one of the facts did not have {:then false}, even if it wasn't the last fact received.

2

u/fjolne Feb 14 '21

You still add them to :what block with an option map as the 4th argument of the EAV tuple: [player ::health health {:then false}]

1

u/[deleted] Feb 27 '21

I am starting to see state machine libs pop up in javascript land like xstate, and robot, can someone maybe ELI5 where the differences come from state machien and rules engine like odoyle? thank you!

0

u/[deleted] Feb 10 '21

[deleted]

8

u/joinr Feb 11 '21

How would you get solid test coverage of an application that’s written entirely in a rules engine?

Test the rules in isolation to ensure they produce the expected changes to the facts. The nice thing about this is the relative compartmentation and functional approach. You have a persistent fact store that can be fed to the rules. Test it at the repl and save the result. You now have a reproducible test going forward. Alternately, establish expected outcomes and query the resulting fact store after the rules fire. If the outcomes don't match the query results, test fails.

Then do the equivalent of integration tests with all the rules working in concert. I'm curious if you could derive data dependencies automatically and figure out fact paths to trigger exercise all the rules. Seems plausible.

0

u/[deleted] Feb 14 '21

[deleted]

4

u/oakes Feb 14 '21

Yep they're all under the umbrella term of logic programming but prolog and core.logic are backward-chaining, whereas clara and o'doyle are forward-chaining.