Algorithmcore
Rete algorithm
Also called Rete network, Forgy's Rete.
Compile the rule conditions into a network that stores the partial matches, so each change of working memory updates the conflict set without matching all rules again.
- Time
- O(r m a n^m) worst
- Space
- O(r m n^m) extra
- Where
- a = the largest arity of an element; m = the largest number of conditions in a rule; n = the number of elements in working memory; r = the number of rules
- Model
- Word RAM
- Properties
- deterministicincremental
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Charles L. Forgy, 1982
The Rete algorithm solves the match step of a production system: after each change to the working memory, find the conflict set, the set of all instantiations of all rules. A plain forward chaining loop matches every rule against the whole memory again in each cycle. Rete compiles the conditions of all rules into one network. Alpha memories hold the working memory elements that pass the tests of a single condition, and join nodes hold the partial matches (tokens) of the first conditions of a rule. A change to working memory then only flows through the nodes that it touches. Rules that share conditions share the nodes. Forgy designed it for OPS5, and the commercial rule engines that came later use variants of it.
In plain words
A rule system checks its rules after every small change to its facts. Most of the work it did in the last check is still valid, because only one fact changed. Rete keeps that work. For each condition it keeps the list of facts that fit the condition. For each rule it keeps the groups of facts that fit its first condition, its first two conditions, and so on. A new fact is checked only against the lists it can join, and the new groups that it makes are passed on to the next condition. When a fact is removed, the groups that hold it are removed. Two rules that start with the same conditions share these lists. The cost is memory: the saved groups can be many.
The problem
A working memory element (WME) is a ground tuple, such as . A rule has the form
where each condition is a pattern with variables. An instantiation of in the working memory is a tuple of elements of with one binding of the variables such that for each . The conflict set is the set of pairs over all rules.
The task is incremental: given the rules once, and then a sequence of changes, each of which inserts or deletes one element, keep correct after each change. This page treats positive conditions only. Finding even one instantiation of one rule is the conjunctive query problem, which is NP-complete in combined complexity, so the incremental task cannot have a polynomial worst case in the size of the rules either.
The algorithm
The network is built from the rules before the first change. Each condition gets an alpha memory, keyed by the condition with its variables renamed by first occurrence, so that and share one memory. It holds the WMEs that pass the constant tests of the condition and the equality tests between its own variables. Each prefix of a rule gets a join node at depth , whose parent is the node of ; rules with equal prefixes share the nodes. The join node reads the alpha memory of and keeps a beta memory of tokens, one for each match of . The node of the full condition list of a rule is its production node. A token records its parent token, its WME and its children, and each WME records its tokens, for removal.
INSERT(w)- 1
for each alpha memory α whose tests w passes do - 2
add w to α - 3
sort the join nodes that read these alpha memories by depth, deepest first - 4
for each such join node j do RIGHT-ACTIVATE(j, w) RIGHT-ACTIVATE(j, w) ▷ a new element arrives from the alpha side- 5
for each token t in the beta memory of the parent of j (the empty token if j has depth 1) do - 6
if the condition of j matches w with a binding that extends the binding of t then - 7
MAKE-TOKEN(j, t, w) MAKE-TOKEN(j, t, w)- 8
add the token t + w to the beta memory of j, link it to t and to w; if j is the production node of a rule ρ then add (ρ, t + w) to the conflict set; for each child c of j do LEFT-ACTIVATE(c, t + w) LEFT-ACTIVATE(c, t) ▷ a new token arrives from the parent side- 9
for each element w in the alpha memory of c do - 10
if the condition of c matches w with a binding that extends the binding of t then - 11
MAKE-TOKEN(c, t, w) DELETE(w)- 12
remove w from every alpha memory - 13
for each token t that records w do - 14
remove t and all its descendants from their beta memories, and their instantiations from the conflict set
Line L3 is needed when one element can match two conditions of the same rule. Deepest first, the deeper node joins with the old tokens of its parent before the shallower node adds new tokens there, so no match is made twice. Deletion by the token tree (lines L13 and L14) is the tree-based removal of Doorenbos; Forgy's original network sent a delete token through the same joins as an insert.
Example
Two rules share their first two conditions:
The network has 4 alpha memories, for , , and , and 4 join nodes: for , for , and the production nodes of and of , both children of .
| insert | alpha memory | join activity | new tokens |
|---|---|---|---|
| goal | joins with the empty token | at | |
| block red | joins with ; and find empty alpha memories | at | |
| block red | as before | at | |
| none | the constant test rejects it | none | |
| on | joins with the two tokens of ; only is consistent | at , an instantiation of | |
| clear | joins with the two tokens of ; only is consistent | at , an instantiation of |
The network now holds 5 tokens, and the conflict set holds one instantiation of each rule. Deleting removes the token and its child at , so 3 tokens and the instantiation of remain. No join runs for the delete.
Correctness
The correctness proof shows an invariant: each alpha memory holds exactly the elements that pass its tests, each join node holds exactly one token for each match of its prefix, and the conflict set holds exactly the matches of the production nodes. For an insert, a new match gets its token at the first position where the new element occurs, by the right activation of that node, and then by left activations down the chain; the deepest-first order rules out a second copy. For a delete, the matches that contain the element are exactly the tokens that record it and their descendants.
Proof: The Rete network keeps exactly the partial matches and the conflict setfull
Fix a set of rules with positive conditions and the network that Rete builds for them. A join node stands for a prefix of the conditions of one or more rules; is the depth of (counted from 1 in this proof), and for its parent is the node of . For a working memory , a match of is a tuple of elements of such that one binding of the variables makes for all . We use the procedures INSERT and DELETE of the page.
Invariant. For the current working memory :
- (A) each alpha memory with pattern holds exactly the elements that match alone;
- (B) the beta memory of each join node holds exactly one token for each match of , and the token records the tuple and its binding;
- (C) the conflict set holds exactly the pairs where is a match of the last join node of the rule .
The invariant holds for the empty memory, since all memories and the conflict set are empty. (C) follows from (B), because a token at a node with productions adds or removes its instantiations at the same moment as the token is made or removed. So we prove that INSERT and DELETE keep (A) and (B).
Lemma 1 (a join step)
Let be a token for a match of the parent of with binding , and let be an element. The test of lines L6 and L10 succeeds exactly when is a match of , and then it returns the binding of that match.
Proof. The test extends so that equals . It fails exactly when a constant of differs from , or a variable already bound in , or bound earlier in , gets two values. These are the conditions for a common binding of .
The alpha test of line L1 uses with its variables renamed by first occurrence. It accepts a superset of the elements that pass the join test with any parent binding, so taking the candidates of the join from the alpha memory loses no match.
Lemma 2 (insert)
Let and . After INSERT, invariant (B) holds for , and no token is made twice.
Proof. Lines L1 and L2 make (A) hold for before any join runs. The matches of for are the old matches, which keep their tokens, and the new matches, which contain . Take a new match of a node , and let be the first position with . Let be the ancestor of at depth (or itself when ), and its parent.
gets a token. The prefix does not contain , so it was a match of before the insert and has an old token (for the root token plays this part). The node reads an alpha memory that received , so line L4 right-activates it. Line L3 sorts the nodes by depth, deepest first, and a token made by a join only goes down to deeper nodes. So when is right-activated, nothing has added a token to yet, and its memory holds exactly the old matches. By Lemma 1, the right activation makes a token for . Each new token at a node is passed at once to each child node (line L8), and the left activation of lines L9 to L11 joins it with the whole alpha memory of the child, which already holds and every other element of . By induction on , a token for is made at depth .
gets only one token. Each token is made either by a right activation, from an old parent token and the element in the last position, or by a left activation, from a new parent token and one element of the alpha memory. Consider the tokens for for . At depth , a left activation would need a new token for , which does not exist since that tuple does not contain . So the only token at depth is the one that the single right activation of made with the old parent token. For the parent tuple contains , so it is new. If , the node was right-activated before , at a time when the memory of held no new token, so the right activation made no token for 's prefix. So a token for comes only from the left activation by the unique new parent token, and that left activation meets once in the alpha memory. By induction, gets exactly one token.
No other token is made. By Lemma 1, every token that the joins make is a match for , and it contains , since right activations put last and left activations start from a new parent token.
Lemma 3 (delete)
Let and . After DELETE, invariants (A) and (B) hold for .
Proof. Line L12 makes (A) hold. A token for is the child of the token for , and it records . So the tokens whose tuple contains are exactly the tokens that record and their descendants, and lines L13 and L14 remove exactly these. The matches for are the matches for that do not contain , and each of them kept its one token.
Theorem
After every sequence of inserts and deletes, the conflict set of the network equals the set of all instantiations of the rules in the current working memory, with no duplicates.
Proof. By induction on the length of the sequence, with Lemmas 2 and 3 for the step and (C) for the conflict set. An insert of an element that is in already, or a delete of an element that is not, changes nothing.
Why the order of line L3 matters
Take the rule with the conditions and , and insert . It enters both alpha memories. If the node of depth 1 runs first, it makes the token , and the left activation of the node of depth 2 makes . If the node of depth 2 is right-activated after that, it finds the new parent token and makes the same pair again. Deepest first, the node of depth 2 runs while its parent memory is still empty, and the pair is made once.
Complexity
The costs depend on the data much more than on the number of rules. An insert costs the size of the parent memories of the join nodes that reaches, plus, for each new token, the size of the alpha memories of the child nodes. A delete costs the number of tokens that it removes when the token lists are linked lists. In the worst case a join node at depth holds up to tokens, so one change can cost time and the network can hold tokens: the same order as matching every rule again, with more memory. This is the combined complexity; the match problem itself is NP-complete when the rules are part of the input, and for fixed rules (data complexity) the cost is polynomial in .
The advantage of Rete is a measured one. Forgy's measurements of OPS programs found that most of their run time went into the match, and that a typical cycle changes few elements, so the saved state removes most of the work. Doorenbos (1995) measured the basic algorithm and his extensions on learning systems with more than a hundred thousand rules. These are results on particular programs, not bounds.
Properties
- Incremental. The state between cycles holds every partial match, and each change does work only for the matches it creates or destroys.
- State saving. The memory can be much larger than the working memory: the price of the speed.
- Sharing. Equal conditions share alpha memories, and equal prefixes share join nodes. The order of the conditions in a rule decides how much is shared and how large the beta memories are.
- Exact. The conflict set after each change is the same as a full rematch gives, with no duplicates.
Variants and improvements
- Negated conditions. A negative node keeps, for each token, the count of the elements that match the negated condition, and passes the token on only while the count is zero. This page does not implement it.
- Hashed memories. Index alpha and beta memories by the values of the join variables, so a join reads only the consistent partners, as in a hash join.
- Rete/UL. Doorenbos added unlinking of nodes whose memory is empty and other changes, so that very large learned rule sets do not slow each change.
- TREAT. The TREAT algorithm of Miranker keeps no beta memories and recomputes the joins after each insert, trading time on inserts for memory and cheap deletes.
- Later designs. Rete II and Rete-NT (Forgy's commercial versions), LEAPS (lazy matching) and Gator networks (which choose the join structure by cost) all change which partial matches are stored.
When to use it
Use Rete when many rules are matched again and again against a working memory that changes a little in each cycle, as in OPS5, CLIPS, Jess and Drools. The saved state pays off when the same partial matches are needed in many cycles. Use TREAT when memory is short or when elements are often removed, and use a plain query when the rules are run once over static data.
Pitfalls
- Cross products. A rule whose first conditions share no variables makes beta memories with the product of their alpha memories. Order the conditions so that each one joins with the earlier ones.
- Duplicate tokens. When an element can match two conditions of a rule, right activations must run deepest first, or the same match is made twice.
- Modify as delete plus insert. A change to an element in OPS5 is a delete and an insert, so the tokens of the element are removed and made again.
- Memory growth. The number of tokens can grow as , and a few bad rules can fill the memory.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# The Rete match algorithm for the page https://algorithm.tamnd.com/rete-algorithm/. The authors are listed in prov/.
"""The Rete match algorithm, with alpha memories, shared join nodes and tree-based removal.
A working memory element (WME) is a tuple of constants. A condition is a
pattern: a tuple in which a term may be a variable, a string that starts with
"?". A rule is (name, conditions), with one or more positive conditions. An
instantiation of a rule is the tuple of WMEs, one for each condition in order,
that match the conditions with one consistent binding of the variables. The
conflict set is the set of pairs (rule name, tuple of WMEs).
Rete(rules) builds the network. insert(w) and delete(w) change the working
memory, which is a set, and keep the conflict set up to date.
- An alpha memory holds the WMEs that pass the tests of one condition alone:
its constants and the equalities between its own variables. Conditions that
differ only in the names of their variables share one alpha memory.
- A join node stands for a prefix c_1, ..., c_i of the conditions of a rule.
Rules with the same prefix share the node. Its beta memory holds tokens: the
partial matches of the prefix.
- A token records its parent token, its WME and its children, and each WME
records the tokens that hold it, so a delete removes exactly the tokens that
contain the WME, without a new match.
"""
def is_var(term):
return isinstance(term, str) and term.startswith("?")
def match(pattern, wme, binding):
"""Extend binding so that pattern equals wme, or return None."""
if len(pattern) != len(wme):
return None
out = dict(binding)
for p, f in zip(pattern, wme):
if is_var(p):
if p in out:
if out[p] != f:
return None
else:
out[p] = f
elif p != f:
return None
return out
def canonical(pattern):
"""Rename the variables of a pattern by their first occurrence: ("p", "?x", "?x") becomes ("p", "?0", "?0")."""
names = {}
out = []
for t in pattern:
if is_var(t):
names.setdefault(t, "?" + str(len(names)))
out.append(names[t])
else:
out.append(t)
return tuple(out)
class AlphaMemory:
def __init__(self, pattern):
self.pattern = pattern
self.items = set()
self.successors = [] # the join nodes that read this memory
class Token:
__slots__ = ("parent", "wme", "binding", "node", "children", "wmes")
def __init__(self, parent, wme, binding, node):
self.parent = parent
self.wme = wme
self.binding = binding
self.node = node
self.children = []
self.wmes = () if parent is None else parent.wmes + (wme,)
class JoinNode:
def __init__(self, parent, alpha, condition, depth):
self.parent = parent # None for the first condition
self.alpha = alpha
self.condition = condition
self.depth = depth
self.tokens = [] # the beta memory
self.children = []
self.productions = []
class Rete:
def __init__(self, rules):
self.alpha = {}
self.joins = {}
self.root = Token(None, None, {}, None)
self.memory = set()
self.conflict = {}
self.wme_tokens = {}
self.tokens_made = 0
self.duplicates = 0
for name, conditions in rules:
if not conditions:
raise ValueError(f"rule {name} has no condition")
node = None
for i, c in enumerate(conditions):
key = tuple(conditions[: i + 1])
if key not in self.joins:
am = self.alpha.setdefault(canonical(c), AlphaMemory(canonical(c)))
nn = JoinNode(node, am, tuple(c), i)
am.successors.append(nn)
if node is not None:
node.children.append(nn)
self.joins[key] = nn
node = self.joins[key]
node.productions.append(name)
def conflict_set(self):
return set(self.conflict)
def _make_token(self, parent, wme, binding, node):
t = Token(parent, wme, binding, node) # @line L8
self.tokens_made += 1
node.tokens.append(t)
parent.children.append(t)
self.wme_tokens.setdefault(wme, []).append(t)
for name in node.productions:
key = (name, t.wmes)
if key in self.conflict:
self.duplicates += 1
self.conflict[key] = t.binding
for child in node.children:
self._left_activate(child, t)
def _left_activate(self, node, token):
for w in list(node.alpha.items): # @line L9
b = match(node.condition, w, token.binding) # @line L10
if b is not None:
self._make_token(token, w, b, node) # @line L11
def _right_activate(self, node, w):
parents = [self.root] if node.parent is None else list(node.parent.tokens)
for t in parents: # @line L5
b = match(node.condition, w, t.binding) # @line L6
if b is not None:
self._make_token(t, w, b, node) # @line L7
def insert(self, w):
w = tuple(w)
if w in self.memory:
return
self.memory.add(w)
targets = []
for am in self.alpha.values(): # @line L1
if match(am.pattern, w, {}) is not None:
am.items.add(w) # @line L2
targets.extend(am.successors)
targets.sort(key=lambda n: -n.depth) # @line L3
for node in targets: # @line L4
self._right_activate(node, w)
def _delete_token(self, t):
while t.children:
self._delete_token(t.children[-1])
t.node.tokens.remove(t)
t.parent.children.remove(t)
self.wme_tokens[t.wme].remove(t)
for name in t.node.productions:
self.conflict.pop((name, t.wmes), None)
def delete(self, w):
w = tuple(w)
if w not in self.memory:
return
self.memory.discard(w)
for am in self.alpha.values(): # @line L12
am.items.discard(w)
for t in list(self.wme_tokens.get(w, [])): # @line L13
if t.node is not None and t in t.node.tokens:
self._delete_token(t) # @line L14
self.wme_tokens.pop(w, None)
def token_count(self):
return sum(len(n.tokens) for n in self.joins.values())
test_rete_algorithm.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rete-algorithm/. The authors are listed in prov/.
import random
import unittest
from itertools import product
from rete_algorithm import Rete, canonical, match
CONSTS = ["a", "b", "c"]
PREDS = [("p", 1), ("q", 2), ("r", 2)]
VARS = ["?x", "?y", "?z"]
ALL_WMES = [(name,) + args for name, arity in PREDS for args in product(CONSTS, repeat=arity)]
def naive_conflict_set(rules, memory):
"""Rematch every rule against the whole working memory."""
out = set()
for name, conditions in rules:
def go(k, b, chosen):
if k == len(conditions):
out.add((name, tuple(chosen)))
return
for w in memory:
b2 = match(conditions[k], w, b)
if b2 is not None:
go(k + 1, b2, chosen + [w])
go(0, {}, [])
return out
def random_rules(rng):
def condition():
name, arity = rng.choice(PREDS)
return (name,) + tuple(rng.choice(VARS + VARS + CONSTS) for _ in range(arity))
rules = []
first = [condition() for _ in range(2)]
for r in range(rng.randint(1, 5)):
conds = [rng.choice(first)] if rng.random() < 0.5 else [] # shared prefixes
conds += [condition() for _ in range(rng.randint(1, 3))]
rules.append(("r" + str(r), conds))
return rules
class TestRete(unittest.TestCase):
def test_canonical(self):
self.assertEqual(canonical(("q", "?y", "?y")), ("q", "?0", "?0"))
self.assertEqual(canonical(("q", "?x", "b")), canonical(("q", "?z", "b")))
def test_page_example(self):
rules = [
("R1", [("goal", "?g"), ("block", "?b", "red"), ("on", "?b", "?t")]),
("R2", [("goal", "?g"), ("block", "?b", "red"), ("clear", "?b")]),
]
net = Rete(rules)
self.assertEqual(len(net.alpha), 4)
self.assertEqual(len(net.joins), 4)
for w in [("goal", "g1"), ("block", "b1", "red"), ("block", "b2", "red"), ("block", "b3", "blue"), ("on", "b1", "table"), ("clear", "b2")]:
net.insert(w)
self.assertEqual(
net.conflict_set(),
{
("R1", (("goal", "g1"), ("block", "b1", "red"), ("on", "b1", "table"))),
("R2", (("goal", "g1"), ("block", "b2", "red"), ("clear", "b2"))),
},
)
self.assertEqual(net.token_count(), 5)
net.delete(("block", "b1", "red"))
self.assertEqual(net.conflict_set(), {("R2", (("goal", "g1"), ("block", "b2", "red"), ("clear", "b2")))})
self.assertEqual(net.token_count(), 3)
def test_same_wme_in_two_conditions(self):
rules = [("loop", [("q", "?x", "?y"), ("q", "?y", "?x")])]
net = Rete(rules)
net.insert(("q", "a", "a"))
self.assertEqual(net.conflict_set(), {("loop", (("q", "a", "a"), ("q", "a", "a")))})
self.assertEqual(net.duplicates, 0)
net.delete(("q", "a", "a"))
self.assertEqual(net.conflict_set(), set())
self.assertEqual(net.token_count(), 0)
def test_random_against_naive(self):
rng = random.Random(20261115)
for _ in range(150):
rules = random_rules(rng)
net = Rete(rules)
memory = set()
for _ in range(40):
w = rng.choice(ALL_WMES)
if w in memory and rng.random() < 0.5:
memory.discard(w)
net.delete(w)
else:
memory.add(w)
net.insert(w)
self.assertEqual(net.memory, memory)
self.assertEqual(net.conflict_set(), naive_conflict_set(rules, memory))
self.assertEqual(net.duplicates, 0)
for w in list(memory):
net.delete(w)
self.assertEqual(net.conflict_set(), set())
self.assertEqual(net.token_count(), 0)
self.assertTrue(all(not am.items for am in net.alpha.values()))
if __name__ == "__main__":
unittest.main()
History
Forgy developed the network match at Carnegie-Mellon in the 1970s, for the OPS family of production system languages, described it in his 1979 thesis, and published the full algorithm in Artificial Intelligence in 1982. OPS5 (1981) made it widely known. Miranker (1987) proposed TREAT as a lighter alternative. Doorenbos (1995) gave the now standard description with tree-based removal and the Rete/UL extensions. CLIPS, Jess and Drools use Rete variants.
References
- Charles L. Forgy, Rete: A fast algorithm for the many pattern/many object pattern match problem, Artificial Intelligence 19(1), 17 to 37 (1982), the description of the pattern and data representations, the network and its node types, and the operations of the matcher
- Robert B. Doorenbos, Production Matching for Large Learning Systems, PhD thesis, Carnegie Mellon University, technical report CMU-CS-95-113 (1995), the chapter on the basic Rete algorithm (alpha memories, beta memories, join nodes and tree-based removal)
- Charles L. Forgy, OPS5 User's Manual, technical report CMU-CS-81-135, Carnegie-Mellon University (1981), the description of the recognize-act cycle that the matcher serves
- Lee Brownston, Robert Farrell, Elaine Kant and Nancy Martin, Programming Expert Systems in OPS5, Addison-Wesley (1985), the parts on the Rete match and on writing efficient OPS5 programs
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag R7WDW3 Edit this page History Report an error Markdown