2007-03-23

Managing State... turned into Temporal Facts

The last few days I've spent some time trying out the idea I outlined in my previous post. It (stateless Rules) was rather simple but fortunately there's an even simpler idea (Temporal Facts) that does more or less exactly the same thing with much less effort.

I must admit I had some doubts about the statelessness even before I started to write the code to implement it. But at the time I really couldn't see a better way of getting the functionality I wanted (without going "outside" the Rule Engine). Peter was kind enough to post some more details regarding different ways of handling state which finally set me straight.

The problem with stateless Rules is basically that it works against one of the core strengths of the Rete algorithm and that's not very good when you're working with a Rule Engine.

Anyway, here's what I did. I started by adding a rule attribute (stateless) which, if set to True, "removed" the memories for partial (Alpha- and BetaMemories) and complete (ProductionNode) matches. Actually the Nodes were still there but they didn't store the Tokens passing through them. Also, when the Rule was compiled, I tagged all Facts that matched the ObjectType for the stateless Rules and stored them in a separate list. Whenever the run method was invoked I'd start by checking the timestamp on each of the Facts and remove those that had expired. After that all of the Facts in the list was asserted and, well... I think you get the idea.

Before I had finished my implementation I read Peter's post about Temporal Facts and realized that it would be a lot easier to check for expired Facts whenever an Activation is created or whenever an Activation is about to be executed.

Using Temporal Facts completely removes the extra matching effort I had introduced and reduces the amount of boilerplate code quite a lot. And it requires no modification of the Rete implementation, which I'm quite happy for. It's so simple and elegant I really wish I'd been able to think of it myself but I guess I wasn't smart enough last week.

1 kommentar:

woolfel sa...

Honestly I can't take credit for the idea. I forget where I read it, but the concept and implementation approach is atleast a decade old. If my memory was better, I would be able to remember the paper. Unfortunately, the older I get, the worse my memory gets. That's kind of why I dump all my thoughts in my blog. I know my memory is getting worse, so my solution was to borrow the old research journal idea and write everything down. This way, I can always go back and see what I was thinking and which approaches failed. I'm pretty sure there are papers on ACMQueue that talk about temporal facts as far back as mid 80's. I'm glad the entry helped.