Fork me on GitHub

I think comparing the result of queries, which will reflect the state of the session before and after you fire rules, is what you’re looking for. So if you have something like


(defrule lousy-weather-rule [?c <- Cold] => (insert! (->LousyWeather)))


(defquery lousy-weather-query “” [] [LousyWeather])


Then (def empty-session (mk-session [lousy-weather-rule lousy-weather-query]))


(query empty-session lousy-weather-query) will return nothing


However, (def not-empty-session (-> empty-session (insert (->Cold)) fire-rules))


(query not-empty-session lousy-weather-query) would find a LousyWeather fact


You could query both before and after inserting/retracting + firing rules afterward and see what changed, then dispatch on that


One perhaps non-obvious part of this is when you query the session, you’re not actually performing much work since Clara basically computes the results for queries after fire-rules. When you run a query you’re really basically retrieving the results already computed with a little data manipulation to get just the bindings you use in your query. You can see that implementation at


Basically a query and a rule look the same to the rules engine mostly when you look at determine what facts match, a rule just does more things (i.e. it is activated and can insert more facts) once you find matches


You can think of it as large trees of the different node types in engine.cljc where ProductionNode corresponds to rules, QueryNode corresponds to queries, facts are given to the root nodes of these trees and passed down to the leaf nodes, which are ProductionNodes and QueryNodes


Just comparing the results before and after for the queries would work, albeit somewhat inefficiently since you’d be performing work even when nothing at all changed. I think there are ways Clara could return changes in queries more efficiently than that if you were interested in contributing an enhancement like that though.


Thank you very much @wparker. Based in your answer I will try some approaches and let you know what I got.