Transaction In Doubt

My notes on Software Engineering

Tag: complex event processing

Miss Manners and Waltzdb

While durable_rules is a framework for complex event coordination, its linguistic abstraction is also suitable for solving business rules problems such as constraint propagation. At its core durable_rules is powered by a variation of the Rete algorithm. Measuring and driving its performance using well established Business Rules industry standards has been extremely valuable. It has brought  the quality of the implementation to a new level: improving performance by orders of magnitude and making the system more robust.

The most popular industry standards for production Business Rules systems are “Miss Manners” and Waltzdb. Designed more than 25 years ago, they have been subject of endless debate. Their direct applicability to customer problems as well as features used by platform vendors specifically to improve the numbers have been questioned. After all, however, we still use such benchmarks to understand the performance of Business Rules systems. Manners and Waltzdb are complementary benchmarks: while Manners tests the speed of combinatoric evaluation, Waltzdb tests the efficiency of action scheduling and evaluation. 

Just as Thomas Edison once famously said about genius, performance improvements too are one percent inspiration and ninety nine percent perspiration. Because durable_rules relies on Redis to store inference state, all performance improvements derived from optimizing how Redis is used. For each experiment I reset the slowlog, executed the test, reviewed the slowlog results and implemented an improvement (sometimes a regression 😦 ). I repeated this over and over. In my first experiments I set the slowlog threshold to 1 second, as I implemented effective improvements I reduced the slowlog threshold and by the end I was only reviewing the commands which took more than 1 millisecond.

All the performance measurements were done using Redis 3.0, unix sockets, disabling Redis disk save and iMac, 4GHz i7, 32GB 1600MHz DDR3, 1.12 TB Fusion Drive.

Principles

Consider the following tests plotted in the chart below:

  1. Blue: Execute a set of sequential hget operations from a node.js client in a tight loop. The throughput for retrieving a 200 byte value is about 25K operations every second, as the size increases, the throughput decreases to 11K operations for 20KB values.
  2. Green: A set of 100 hget operations batched in a multi-exec command: The throughput in the case of 200 byte value is around 160k operations every second, degrading to 18k when the value is 20KB.
  3. Yellow: A set of hget operations inside a Lua script: The throughput for 200 bytes jumps all the way up to 3M operations/sec, the throughput degrades to 458K for 20KB value.
  4. Red: A set of cmsg unpack operations inside a Lua script: The throughput for 200 bytes is 9M operations/sec, which degrades to 1.1M for 20KB values.
  5. Orange: A set of Lua table get inside a Lua script: The throughput remains constant at 63M operations/sec.

redis

What is important about the experiment above is the order of magnitude of each operation. For the Manners and Waltzdb benchmarks, where hundreds of thousands of combinatorics need to be evaluated in a few seconds, reducing sequential and batched access from redis clients is critical but not enough. Access to Redis structures from Lua as well as packing and unpacking using cmsg can also become a bottleneck. Thus, all performance optimizations were done following these principles.

  1. Push the combinatorics evaluation as close to the data as possible leveraging Lua scripts.
  2. Design chunky Lua script function signatures batching operations when possible.
  3. Avoid fetching the same information multiple times from Redis data-structures by using Lua local variables.
  4. Be careful with the shape of the data stored, avoid excessive cmsg usage.

Miss Manners

Miss Manners has decided to throw a party. She wants her guests not to get bored, so she needs to sit them such that adjacent guests are always of opposite sex and share at least one hobby. The problem needs to be resolved for 8, 16, 32 and 128 guests. 

mannerstable

The ruleset for the algorithm is relatively simple consisting of only seven rules (RubyPython, JScript). Guests hobbies are expressed using facts. Therefore the input datasets consists of 20, 40, 83 and 439 facts for 8, 16, 32 and 128 guests respectively. The declarative algorithm conceptually (not practically) creates the combinatorics tree for all the guests and selects the first valid solution via depth first search.

Learnings

The antecedent in the rule below (expressed in Python) is the heart of the algorithm, as it determines valid solutions. Consider the case of 128 seatings with 439 guest assertions: by the end of the test execution the first 3 terms of the expression will have generated hundreds of thousands combinatorics, the next two terms will have filtered out the invalid ones. Recalculating the full expression for all terms for all combinatorics every time a new seating is asserted slows down execution significantly. I addressed the problem with the following three improvements:


    @when_all(c.seating << (m.t == 'seating') & 
                           (m.path == True),
              c.right_guest << (m.t == 'guest') & 
                               (m.name == c.seating.right_guest_name),
              c.left_guest << (m.t == 'guest') & 
                              (m.sex != c.right_guest.sex) & 
                              (m.hobby == c.right_guest.hobby),
              none((m.t == 'path') & 
                   (m.p_id == c.seating.s_id) & 
                   (m.guest_name == c.left_guest.name)),
              none((m.t == 'chosen') & 
                   (m.c_id == c.seating.s_id) & 
                   (m.guest_name == c.left_guest.name) & 
                   (m.hobby == c.right_guest.hobby)),
              (m.t == 'context') & (m.l == 'assign'))
    def find_seating(c):
  1. When evaluating combinatorics and resolving action scheduling conflicts the rules engine has to choose the most recent result to enable the depth first search of a valid solution. This resolution policy has been implemented and pushed as de-facto standard since the early days of Business Rules.
  2. For a given rule, to avoid scanning and evaluating all expression lvalues (inference list) for every assertion, the inference results are stored in a hash-set indexed by the combined result of all equality expressions. Thus, the combinatorics calculation complexity becomes linear and depends on the number of assertions done on the rule.
  3. When evaluating a fact through a complex expression the engine might compare it with the same target fact multiple times, caching target facts in lua local variables reduces the number of Redis data-structure access.

Results

JavaScript is the fastest, as it solves the problem for 128 guests in about 1.7 seconds, on the flip side its memory usage is the highest reaching 46MB including Redis memory usage. Python can still solve the 128 guest problem below 2 seconds with remarkably efficient memory usage of 26MB including Redis memory. Ruby is not far behind, a little bit above 2 seconds and good memory usage of 35MB including Redis. 

manners

As shown in the graph below, benchmark execution time is directly correlated with the number of Redis commands executed. In the case of 128 guests more than 400K commands were executed. In the case of JavaScript, this is a throughput of 225K Redis commands per second.

mannerscommands

Waltzdb

Waltz is an image recognition algorithm invented by Dr. David Waltz in 1972. Given a set of lines in a 2D space, the computer needs to interpret the 3D depth of the image. The first part of the algorithm consists of identifying four types of junctions: Line, Arrow, Fork, Tee. Junctions have 16 different possible labelings following Huffman-Clowes notation, where + is convex, – is concave and an arrow is occluding. Valid junctions and labelings:

waltzjunctions

It is important to point out: pairs of adjacent junctions constraint each other’s edge labeling. So, after choosing the labeling for an initial junction, the second part of the algorithm iterates through the graph, propagating the labeling constraints by removing inconsistent labels. Example labeling a cube with 9 lines:

waltzcube

The ruleset for the algorithm consists of 34 rules (RubyPythonJScript). In the Waltzdb benchmark, the dataset provided is a set of cubes organized in regions. Each region consists of 4 visible and 2 hidden cubes composed by 72 lines. In addition, all tests are flanked by four visible and 1 hidden cube formed by 76 more lines. The tests were run with 4 (376 lines, 20 visible cubes, 9 hidden cubes), 8 (680 lines, 36 visible cubes, 17 hidden cubes), 12 (984 lines, 52 visible cubes, 23 hidden cubes), 16 (1288 lines, 68 visible cubes, 33 hidden cubes) and 50 regions (3872 lines, 204 visible cubes, 101 hidden cubes).

waltzdata

Learnings

  1. waltzdb requires a large amount of action evaluations. Some actions (reversing edges or making junctions) don’t imply a change in context (moving forward state), such actions can be batched and marshaled to the scripting engine in a single shot.
  2. Fact assertions can lead to multiple rule evaluation, instead of invoking a Lua function for every rule evaluation, all rule evaluations for a single fact assertion can be batched and marshaled to Redis in a single shot. 
  3. durable_rules doesn’t support fact modification. To avoid excessive churn in the scheduled action queue, events can be used (instead of facts) to drive the state machine coordination.

Results

JavaScript was the fastest completing the 50 region problem in 21 seconds, memory usage reached 170MB including Redis memory usage. Both Python and Ruby finished the problem in about 23 seconds (not far behind). The memory usage for both Python and Ruby was below 100MB (including Redis).

waltzdbres

Just as the Manners benchmark, the benchmark time is directly correlated with the number of Redis commands executed. The case of 50 regions executed almost 3.5M Redis commands. The test in JavaScript has a throughput of 159K Redis commands per second.
waltzdbcommandsConclusion

durable_rules efficiency in combinatorics evaluation is competitive,  its efficiency in memory usage is remarkable. The results compare well with well established Production Business Rules systems. There is performance penalty for marshaling actions in and out of Redis as shown in Waltzdb.

Redis is a great technology, but it has to be used appropriately. The fact that Manners is able to push 225k Redis commands and Waltzdb 159K Redis commands every second, while I was able to get 3M hget commands/sec in a simple experiment, means I might be able to still squeeze more performance out of this system.

Rete_D

The past few months have been a time of intense study and creative software implementation. Which led to the full development of the durable_rules forward inference algorithm. Before I release what I consider the durable_rules beta version, I would like to present my thoughts on what I have done with the Rete algorithm. It is difficult to talk about an algorithm without naming it. That is why, in this note, I refer to durable_rules forward inference implementation as Rete_D (D for distributed).

As I read blogs and white papers on rules engines implementations, at least in principle, I found interesting similarities between Rete_D and Drools (ReteOO as well as PHREAK). In particular it is worth mentioning the features:

  • Alpha node indexing: Rete_D accomplishes by using a trie written in C (see my previous blog entry).
  • Beta node indexing: in Rete_D `join` and `not` nodes are indexed using a lua table.
  • Set oriented propagation:  Inserts and deletes are queued. During rule evaluation, inserts and deletes are evaluated against a set of frames which facts and events stored in redis.
  • Heap based agendas: The agenda for rule execution is managed with a redis sorted set and lists ordered by salience.

Rete_D has a number of important features, which make it unique. To demonstrate them I use a simple fraud detection rule written in Ruby.

Durable.ruleset :fraud do
  when_all c.first = m.t == "purchase",
                 c.second = (m.t == "purchase”) & (m.location != first.location) do
    puts "fraud detected " + first.location + " " + second.location
  end
end

Scripting

In the example above, you might have noticed there is no types nor models definition. Events and facts are JSON objects and rules are written for the JSON type system (sets of name value pairs). A good analogy is the MongoDB query language, in which the existence of JSON objects is assumed and an explicit structured schema definition is not needed. In fact in my earliest Rete_D implementation I used the MongoDB syntax for defining rules. I departed from MongoDB query because expression precedence when using operators such as And, Or, All and Any is ambiguous. In today’s durable_rules implementation our example will be translated to:

fraud: {
    all: [
        {first: {t: 'purchase'}},
        {second: {$and: [{t: 'purchase'}, {$neq: {location: {first: 'location'}}}]}}
     ],
}

Events and facts are fully propagated down the network, that is, there is no property extraction constructs in either the library nor the Rete_D structure. In a rule definition, events and facts have to be named and referenced by such a name when expressing correlations. Any property name can be used. The results:

  1. Simpler rule definitions. 
  2. Integration with scripting languages, that provide great support for JSON type system.

Distribution

With Rete_D, the tree evaluation can distributed among different compute units (call them processes or machines). There are three important reasons for doing so:

  1. Availability: avoid single points of failure.   
  2. Scalability: distribute the work utilizing resources available.
  3. Performance: consolidate event ingestion with real-time rule evaluation.

To make this viable, pushing evaluation as close to the data a possible is critical. Alpha nodes are evaluated by the Rete_D C library and can be distributed symmetrically across compute units (such as Heroku web dynos). The Beta nodes are evaluated by a lua script (created during rule registration) in the Redis servers where the state is kept. Events and facts can be evaluated in different Redis servers depending on the context they belong to. Finally actions are to be executed by the compute units responsible for alpha node evaluation.

trie

Events

Events are a first class citizen in the Rete_D data model. The difference between events and facts is events can only be seen once by any action. This principle implies that events can be deleted as soon as a rule is resolved and before the corresponding action is scheduled for dispatch. This can dramatically reduce the combinatorics of join evaluation and the amount of unnecessary computations for some scenarios.  

To illustrate this point, let’s add the following rule to the example above:


  when_start do
    assert :fraud1, {:id => 1, :sid => 1, :t => "purchase", :location => "US"}
    assert :fraud1, {:id => 2, :sid => 1, :t => "purchase", :location => "CA"}
    assert :fraud1, {:id => 3, :sid => 1, :t => "purchase", :location => "UK"}
    assert :fraud1, {:id => 4, :sid => 1, :t => "purchase", :location => "GE"}
    assert :fraud1, {:id => 5, :sid => 1, :t => "purchase", :location => "AU"}
    assert :fraud1, {:id => 6, :sid => 1, :t => "purchase", :location => "MX"}
    assert :fraud1, {:id => 7, :sid => 1, :t => "purchase", :location => "FR"}
    assert :fraud1, {:id => 8, :sid => 1, :t => "purchase", :location => "ES"}
    assert :fraud1, {:id => 9, :sid => 1, :t => "purchase", :location => "BR"}
    assert :fraud1, {:id => 10, :sid => 1, :t => "purchase", :location => "IT"}
  end

Because each fact matches the first and the second rule expression, there are 10 x 10 comparisons, which produce 10 x (10 -1) = 90 results. In contrast, let’s replace ‘when_start’ with the following rule:


  when_start do
    post :fraud1, {:id => 1, :sid => 1, :t => "purchase", :location => "US"}
    post :fraud1, {:id => 2, :sid => 1, :t => "purchase", :location => "CA"}
    post :fraud1, {:id => 3, :sid => 1, :t => "purchase", :location => "UK"}
    post :fraud1, {:id => 4, :sid => 1, :t => "purchase", :location => "GE"}
    post :fraud1, {:id => 5, :sid => 1, :t => "purchase", :location => "AU"}
    post :fraud1, {:id => 6, :sid => 1, :t => "purchase", :location => "MX"}
    post :fraud1, {:id => 7, :sid => 1, :t => "purchase", :location => "FR"}
    post :fraud1, {:id => 8, :sid => 1, :t => "purchase", :location => "ES"}
    post :fraud1, {:id => 9, :sid => 1, :t => "purchase", :location => "BR"}
    post :fraud1, {:id => 10, :sid => 1, :t => "purchase", :location => "IT"}
  end

Remember each event can only be see once, therefore there are 10 comparisons, which produce only 5 results. As you can see events can dramatically improve performance for some scenarios. 

Context References

It is common to provide rule configuration information by asserting facts. In some cases this might lead to increasing join combinatorics. Rete_D implements an eventually consistent state cache, which can be referenced during alpha node evaluation, thus reducing the beta evaluation load. Consider the rule implemented in Ruby:

Durable.ruleset :a8 do
  when_all m.amount > s.id(:global).min_amount do
    puts "a8 approved " + m.amount.to_s
  end
  when_start do
    patch_state :a8, {:sid => :global, :min_amount => 100}
    post :a8, {:id => 2, :sid => 1, :amount => 200}
  end
end

An event is compared against the ‘min_amount’ property of the context state object called ‘global’. This evaluation is done by an alpha node using the state cached in the compute unit and refreshed every two minutes (by default). Again this can lead to reduction in join combinatorics and significant performance improvements for some scenarios.

Conclusion

Rete_D provides a number of unique features, which I believe make it relevant for solving Streaming Analytics problems where rules are expected to handle a large amount of data in real time. The following features are not yet implemented in Rete_D. They represent exciting areas for future research.

  • Beta node sharing
  • Lazy rule evaluation
  • Rule based partitioning
  • Backward inference