How to find out why a Clojure agent got into an invalid state

Clojure allows set-validator!

for use to check if the new state of an agent is valid according to some rule. My validator catches a situation where, for some reason, agent values ​​are set to nil

. However, I can't figure out how this might happen - is there a way to identify the action that was trying to set an invalid state?

+3


source to share


1 answer


Agent

also works with clocks , so it makes perfect sense to add a watcher to the agent that logs all state transitions, so when things go wrong, you can use that log to replay the transitions that crash (and hopefully from here to the problem)

user> (def x (agent 0))
#'user/x
user> (def states (atom []))
#'user/states
user> (add-watch x :state-logger (fn [& change] (swap! states conj change)))
#<Agent@1dff7647: 0>
user> (send x inc)
#<Agent@1dff7647: 0>
user> (send x dec)
#<Agent@1dff7647: 0>
user> (send x inc)
#<Agent@1dff7647: 1>
user> @states
[(:state-logger #<Agent@1dff7647: 1> 0 1) 
 (:state-logger #<Agent@1dff7647: 1> 1 0) 
 (:state-logger #<Agent@1dff7647: 1> 0 1)]

      



It might be wise to put a (take 200 ...)

in an observer so you only keep a reasonable amount of state (or use a ringbuffer)

0


source







All Articles