Rule-based systems and expert systems
Expert systems were AI’s first commercial success and their rule engines remain in production in fraud detection, compliance, WAF and SIEM. Study production systems, conflict resolution strategies, the Rete algorithm for incremental matching, expert-system architecture with explanations, and lessons from the knowledge-engineering bottleneck.
After this lesson you can
- Describe a production system’s recognize–act cycle and conflict resolution strategies.
- Implement Rete with alpha and beta memories and measure its incremental advantage.
- Build a backward-chaining expert system with why and how explanations.
- Critically evaluate when a rule engine is preferable to a learned model.
- Explain historical lessons of knowledge engineering and rule-base maintenance.
Before you start
Why study expert systems today
A security operations center receives a flood of authentication events every second, and someone wants to know immediately whether an IP failed repeatedly before logging in. At a bank, each payment passes hundreds of conditions (“amount above the customer’s usual and new country and high-risk merchant”) before authorization. A web application firewall such as ModSecurity with the OWASP Core Rule Set checks each HTTP request against hundreds of rules and accumulates an anomaly score. In Kubernetes, an admission controller asks Open Policy Agent whether a deployment meets company policies before accepting it.
Inside, all use the same machine 1970s and 1980s AI called a production system: memory of facts, a set of “if this, then that” rules, and a loop deciding which rule to apply next. Expert systems, AI’s first commercial success, were built on it, and three ideas still in production come from it:
- Incremental matching. Checking thousands of rules against millions of facts after each change is impossible by brute force. Rete (Forgy, 1982) saves partial matches and updates only what changes: this lesson’s lab makes about comparisons where naive matching would make .
- Explicit control. When several rules can fire at once, a conflict-resolution strategy chooses one. The strategy changes the result, and understanding it distinguishes a predictable rule engine from one that fails as soon as someone adds a rule.
- Explanation. A rule system can say why it asks a question and how it reached a conclusion because its reasoning is a rule trace. That is why they remain in use where auditability is legally required, and why learned-model explainability tries to recover something similar.
In the previous lesson you saw rules’ declarative side: Datalog and Prolog, with model semantics and a fixed point. Here is the operational side: rules that act (retract facts, modify them, call functions), whose result depends on order, and the engineering needed for speed and maintainability. You will be able to build a production engine with Rete from scratch, an expert system with explanations, and decide when a rule engine is a better tool than a learned model.
Production systems
The earliest “productions” are Emil Post’s (1943), as string rewrite rules; Allen Newell and Herbert Simon turned them into a model of human cognition in Human Problem Solving (1972), leading to Carnegie Mellon’s OPS language family, with OPS5 (Forgy, 1981) its most widespread version and the language of XCON, the expert system seen later. The structure has not changed since.
Two details matter. First, matching is not unification: facts are tuples of constants, so only pattern variables are bound; it is half of unification, without an occurs check or variables on both sides, so it can be compiled into a test network. Second, an instance is not a rule but a rule plus the concrete facts satisfying it: one rule can have a hundred instances in the conflict set, one per fact combination.
If rules only insert facts, you know the result: Datalog’s forward chaining, reaching the least fixed point of operator . The interesting question is how much of that guarantee survives in a production system, choosing one instance per cycle and allowing deletion.
Proof
Soundness. Induction over firings: if every fact of is in , an instance inserts with , and since is closed under the rules, . Thus throughout.
Termination. Possible constants are those of initial facts and rules, since every right-side variable occurs on the left; finitely many facts and hence instances are possible. Each cycle fires a new instance (by refraction), so cycles are finite.
Completeness. At quiescence, every instance over has fired, so contains each instance’s right-hand side: is closed under the rules, . It contains initial facts and therefore the least model: . With soundness, .
∎The assumptions matter. Without refraction, the first fired instance remains in the next cycle’s conflict set (memory lost nothing), and a strategy selecting it again never terminates. With retract or modify, a rule can destroy another’s condition, so whoever fires first matters: firing order becomes part of the semantics. Negation as failure has the same effect another way: a negated CE holding today may stop holding when another rule inserts a fact. Nearly all real production systems violate the theorem’s assumptions, hence the next section.
Conflict resolution
Consider four incident-response rules. A brute-force alert for IP 10.0.0.7 is open; that IP is on the corporate VPN allowlist, and ana logged in successfully from it:
| Rule | If | Then |
|---|---|---|
bloquear | (alerta ?ip ?tipo abierta) | insert (bloqueo ?ip); alert becomes bloqueada |
descartar (salience 10) | (alerta ?ip ?tipo abierta) and (lista-blanca ?ip) | alert becomes descartada |
escalar | (fase triaje), (alerta ?ip fuerza-bruta abierta) and (exito ?ip ?u) | insert (incidente ?ip ?u); alert becomes escalada |
avisar | (incidente ?ip ?u) | notify the on-call team |
The first three activate simultaneously, and each changes alert status so the other two no longer hold. Which fires first completely determines the system’s result. The strategy fixes that.
With tags 1 (fase triaje), 2 (lista-blanca 10.0.0.7), 3 (alerta …) and 4 (exito 10.0.0.7 ana), instances are bloquear[3], descartar[3, 2] and escalar[1, 3, 4]. For LEX their sorted lists are , and : escalar wins because . MEA counts only the first CE: escalar begins with (fase triaje), tag 1, and comes last; between bloquear and descartar, tied at 3, LEX decides and descartar wins, whose list extends . MEA treats each rule’s first CE as a goal or context element ((fase triaje), (objetivo configurar-cpu)): insert a new goal and rules addressing it move ahead, behaving as means–ends analysis pursuing the newest subgoal.
avisar. Then in the counter scenario check that refraction is insufficient when a rule modifies the fact that activated it.What you should have seen:
- Three reasonable strategies, three outcomes. File order blocks the corporate VPN IP; salience and MEA discard the alert; LEX, recency and specificity open an incident for
ana. None is “correct”: the system is underspecified because all three rules apply to the same situation and say incompatible things. The strategy only chooses which mistake to make. - Without refraction, the system does not stop. After
escalar, instanceavisar[5]wins and, since it does not change memory, wins again next cycle forever. This is the observation preceding the theorem: quiescence depends on refraction. - With
modify, even refraction is insufficient. Rulecontarincrements the counter whenever it sees a failure. Butmodifyis “retract and insert”, so the modified counter gets a fresh tag, instancecontar[4, 3]differs fromcontar[1, 3]and refraction does not recognize it: the counter grows forever. Retracting the failure when counted (the rule “consumes” its cause) fixes the loop and gives the correct count, 2.
The first cell implements this using the simplest matching: each cycle recomputes the conflict set from scratch with nested loops. Tags are the memory clock; modify retracts and inserts, as in OPS5 and CLIPS; and each strategy is a sorting key.
def es_var(x):
return isinstance(x, str) and x.startswith("?")
def empareja(patron, hecho, b):
"""Extiende las ligaduras b para que patron encaje con hecho; None si no encaja."""
if len(patron) != len(hecho):
return None
b = dict(b)
for p, v in zip(patron, hecho):
if es_var(p):
if p in b and b[p] != v:
return None
b[p] = v
elif p != v:
return None
return b
class Regla:
def __init__(self, nombre, lhs, rhs, salience=0):
self.nombre, self.lhs, self.rhs, self.salience = nombre, lhs, rhs, salience
def especificidad(self):
"""Como en CLIPS: una comparación por cada constante y por cada aparición repetida de una variable."""
vistas, n = set(), 0
for patron in self.lhs:
for p in patron[1:]: # el nombre de la relación no cuenta
if es_var(p):
n += p in vistas
vistas.add(p)
else:
n += 1
return n
class MemoriaDeTrabajo:
def __init__(self, hechos=()):
self.hechos, self.reloj = {}, 0 # etiqueta temporal -> hecho
for h in hechos:
self.inserta(h)
def inserta(self, hecho):
if hecho in self.hechos.values(): # sin duplicados, como CLIPS
return None
self.reloj += 1
self.hechos[self.reloj] = hecho
return self.reloj
def retira(self, etiqueta):
del self.hechos[etiqueta]
def modifica(self, etiqueta, pos, valor):
h = list(self.hechos[etiqueta])
h[pos] = valor
self.retira(etiqueta)
return self.inserta(tuple(h)) # modificar = retirar + insertar: etiqueta NUEVA
def instancias(reglas, mt):
"""Conjunto conflicto por emparejamiento ingenuo: cada regla con cada tupla de hechos consistente."""
out = []
for r in reglas:
parciales = [((), {})]
for patron in r.lhs:
parciales = [(ets + (e,), b2) for ets, b in parciales
for e, h in mt.hechos.items() if (b2 := empareja(patron, h, b)) is not None]
out += [(r, ets, b) for ets, b in parciales]
return out
def clave(estrategia, inst, orden):
"""Clave de ordenación: gana la instancia con la clave MAYOR."""
r, ets, _ = inst
rec = tuple(sorted(ets, reverse=True)) # etiquetas de más a menos reciente
textual = -orden[r.nombre] # desempate final: posición en el fichero
return {"textual": (textual,),
"prioridad": (r.salience, textual),
"recencia": (rec, textual),
"especificidad": (r.especificidad(), textual),
"LEX": (rec, r.especificidad(), textual),
"MEA": (ets[0], rec, r.especificidad(), textual)}[estrategia]
def ejecuta(reglas, hechos, estrategia="LEX", refraccion=True, max_ciclos=12):
mt = MemoriaDeTrabajo(hechos)
orden = {r.nombre: i for i, r in enumerate(reglas)}
disparadas, traza = set(), []
for _ in range(max_ciclos):
cs = [i for i in instancias(reglas, mt) if not (refraccion and (i[0].nombre, i[1]) in disparadas)]
if not cs:
return traza, mt, "reposo"
r, ets, b = max(cs, key=lambda i: clave(estrategia, i, orden))
disparadas.add((r.nombre, ets))
traza.append(f"{r.nombre}{list(ets)}")
r.rhs(mt, ets, b)
return traza, mt, "límite de ciclos"
def pasa_a(estado):
def rhs(mt, ets, b):
alerta = next(e for e in ets if mt.hechos[e][0] == "alerta")
mt.modifica(alerta, 3, estado)
return rhs
def y_luego(*acciones):
return lambda mt, ets, b: [a(mt, ets, b) for a in acciones]
def afirma(*patron):
return lambda mt, ets, b: mt.inserta(tuple(b.get(p, p) for p in patron))
nada = lambda mt, ets, b: None
triaje = [
Regla("bloquear", [("alerta", "?ip", "?tipo", "abierta")],
y_luego(afirma("bloqueo", "?ip"), pasa_a("bloqueada"))),
Regla("descartar", [("alerta", "?ip", "?tipo", "abierta"), ("lista-blanca", "?ip")],
pasa_a("descartada"), salience=10),
Regla("escalar", [("fase", "triaje"), ("alerta", "?ip", "fuerza-bruta", "abierta"), ("exito", "?ip", "?u")],
y_luego(afirma("incidente", "?ip", "?u"), pasa_a("escalada"))),
Regla("avisar", [("incidente", "?ip", "?u")], nada),
]
hechos_triaje = [("fase", "triaje"), ("lista-blanca", "10.0.0.7"),
("alerta", "10.0.0.7", "fuerza-bruta", "abierta"), ("exito", "10.0.0.7", "ana")]
for r in triaje:
print(f"{r.nombre:10s} especificidad {r.especificidad()} salience {r.salience}")
for est in ["textual", "prioridad", "recencia", "especificidad", "LEX", "MEA"]:
traza, mt, fin = ejecuta(triaje, hechos_triaje, est)
estado = next(h[3] for h in mt.hechos.values() if h[0] == "alerta")
print(f"{est:14s} {' -> '.join(traza):34s} alerta {estado:11s} ({fin})")
traza, mt, fin = ejecuta(triaje, hechos_triaje, "LEX", refraccion=False, max_ciclos=8)
print("LEX sin refracción:", " -> ".join(traza), f"({fin})")The table confirms the interactive, and its last line shows the avisar loop without refraction. The counter with and without consuming the failure:
def cuenta(consumir):
def rhs(mt, ets, b):
mt.modifica(ets[0], 2, b["?n"] + 1) # nuevo contador, con etiqueta nueva
if consumir:
mt.retira(ets[1]) # el fallo ya contado sale de la memoria
return [Regla("contar", [("intentos", "?ip", "?n"), ("fallo", "?ip", "?t")], rhs)]
hechos_contador = [("intentos", "10.0.0.7", 0), ("fallo", "10.0.0.7", 1), ("fallo", "10.0.0.7", 2)]
for consumir in (False, True):
traza, mt, fin = ejecuta(cuenta(consumir), hechos_contador, "LEX", max_ciclos=8)
n = next(h[2] for h in mt.hechos.values() if h[0] == "intentos")
print(f"consumir el fallo: {str(consumir):5s} disparos {len(traza)} intentos = {n} ({fin})")
print(" ", " -> ".join(traza))Without consuming the failure, each firing creates a freshly tagged counter and two fresh instances refraction has never seen. LEX always picks the newest counter with the newest failure, contar[1, 3], contar[4, 3], contar[5, 3]…, so the same failure is counted repeatedly: eight firings and intentos = 8 with two failures in memory, continuing indefinitely. Consuming the failure, contar[1, 3] and contar[4, 2] count each once and the system stops with intentos = 2.
Rete: matching without repeating work
The previous cell recomputes the conflict set every cycle; with nested loops, for a rule of patterns and memory of facts this costs on the order of comparisons for the first pattern plus per partial match at each level. With dozens of rules and thousands of facts, matching consumes nearly all runtime. Charles Forgy, in his 1979 thesis and 1982 paper, started from two observations:
- Temporal redundancy. A firing changes a few facts; the rest of memory and therefore nearly all partial matches remain unchanged. Recomputing them wastes work.
- Structural similarity. Many rules share conditions (same fact type, constant, or pair of patterns joined by the same variable). Checking each once per rule repeats work.
The solution compiles rules into a data-flow network that stores partial matches and through which only changes flow.
The correctness invariant is simple: after each change, every level beta memory contains exactly the partial matches of the first patterns over current working memory. It holds by induction over the network: a new level token must contain new fact (otherwise it already existed), and is either in position (found by right activation, comparing with all level tokens) or an earlier position (then its prefix is a new level token, found by the left activation it triggers). No token is generated twice, because each (token, fact) pair is examined once: when the latter arrives.
The interactive’s three rules detect intrusions. The first two seek two login failures from one IP followed by a success from it (the second only if the account is admin); the third a login from a blocklisted IP:
The first two share their first two patterns, and Rete compiles that prefix once.
What to observe:
- Each fact touches a small network part.
(negra X)makes one alpha test and nothing more; a failure makes one alpha test and enters the two-failure join on both sides (first and second pattern). Comparisons depend on touched memory sizes, not all working memory. - The network remembers. When
(exito A ana 11)arrives, A’s failure pairs already occupy the first join’s memory (level-2 tokens): the join only compares the success with those pairs and produces three activations at once, for failure pairs at , and . - Naive matching keeps growing. Its bars grow with memory (each event repeats all matching), while Rete’s stay small. Total: 94 Rete comparisons versus 1703; without shared nodes, 130, because each failure is compared twice, once per rule.
- The agenda accumulates redundant instances. Three
fuerza-brutainstances for one suspicious login: with prior failures, a “two failures and one success” rule has instances per success. This cross-product problem recurs in exercises and lab.
Cost, carefully
Rete trades time for memory. Inserting a fact costs the sum, over reached join nodes, of opposite-memory sizes plus propagating new tokens; it depends not directly on but how many partial matches share variables with the new fact. In exchange beta memories store all partial matches, and a rule with patterns sharing no variables has memories of size : the cross product. Pattern order matters: placing the most selective patterns and those sharing variables with prior patterns first keeps intermediate memories small, as with database join order.
Two standard improvements used in our lab engine address activation cost. Indexed memories: rather than traversing all opposite memory, index equality-test variable values (?ip) with a chained hash table, so an IP A failure is compared only with A’s tokens; ordering tests (?t1 < ?t2) can use an ordered index such as a B-tree. Doorenbos reports indexed memories sped matching by 1.2 to 3.5 times across OPS5 systems (Gupta et al., 1988). Tree-based retraction: each fact stores its containing tokens, and retracting deletes that list without rematching.
TREAT, Rete/UL and current engines
Storing every beta memory is not the only option. TREAT (Miranker, 1987) omits them: it retains only alpha memories and the conflict set, recomputing affected rule joins when a fact arrives. It saves memory and makes retraction cheap (remove conflict-set instances containing the fact), and was faster than Rete on its study’s five OPS5 programs, in some cases by over 50%. Neither dominates: Rete wins when partial matches are reused heavily, TREAT when memory changes so much that maintaining them is expensive.
Doorenbos (1995) studied the other extreme, systems that learn at least 100,000 rules. Rete and TREAT slowed linearly with rule count even when each fact affected few, due to null activations: a fact reaching a join with empty opposite memory produces nothing but visiting costs time, and a hundred thousand rules have many such joins. His Rete/UL algorithm unlinks a join from alpha memory while beta memory is empty and vice versa, eliminating or greatly reducing slowdown across all test systems; one reached over a million rules without significant matching-cost increase. The thesis also measures beta-node sharing: with initial rules it reduces token count 1.5 to 10.2 times depending on system; with 100,000 rules, 450 to 1000 times.
Current engines descend from these ideas. CLIPS, NASA’s 1985 rule system still maintained today, uses Rete. Drools replaced Rete with PHREAK in version 6: a lazy, goal-directed variant deriving, per its documentation, from LEAPS, Rete/UL and collection-oriented matching. All rules start unlinked; a network segment links when all nodes have data, and a rule is evaluated only when its complete path is linked. This takes Rete/UL’s idea to the extreme.
A Rete engine from scratch
The next cell implements the full engine: shared alpha memories, beta memories with optional hash indexes, joins with tests placed at the first level binding their variables, node sharing, tree-based retraction, an agenda with salience, recency and refraction, and comparison counts. To check it, compare each event with naive matcher ingenuo, which repeats everything with nested loops: both must give the same activations, and method coste_ingenuo must predict naive comparisons exactly from beta-memory sizes (because partial matches traversed by naive matching at level are level beta-memory tokens).
from collections import defaultdict
def es_var(x):
return isinstance(x, str) and x.startswith("?")
class Test:
"""Predicado sobre variables ya ligadas. El texto lo identifica, para poder compartir nodos."""
def __init__(self, texto, variables, f):
self.texto, self.variables, self.f = texto, tuple(variables), f
class Regla:
def __init__(self, nombre, lhs, tests=(), rhs=None, salience=0):
self.nombre, self.lhs, self.tests = nombre, [tuple(p) for p in lhs], list(tests)
self.rhs, self.salience = rhs, salience
def liga(patron, hecho, b):
"""Extiende las ligaduras b con las variables de patron (las constantes ya las probó la red alfa)."""
b = dict(b)
for p, v in zip(patron, hecho):
if es_var(p):
if p in b and b[p] != v:
return None
b[p] = v
return b
class MemoriaAlfa:
"""Hechos que pasan las pruebas de un solo patrón: tipo, aridad y constantes."""
def __init__(self, constantes):
self.constantes = constantes
self.hechos = {} # etiqueta -> hecho
self.sucesores = [] # ("join", nodo) o ("primera", memoria, patrón)
def pasa(self, hecho):
return all(hecho[i] == v for i, v in self.constantes)
class MemoriaBeta:
"""Tokens: emparejamientos parciales, como tupla de etiquetas con sus ligaduras."""
def __init__(self):
self.tokens = {}
self.hijos, self.producciones = [], []
class Join:
"""Une los tokens de una memoria beta (izquierda) con los hechos de una memoria alfa (derecha)."""
def __init__(self, motor, izq, alfa, patron, tests, ligadas):
self.motor, self.izq, self.alfa, self.patron, self.tests = motor, izq, alfa, patron, tests
self.salida = MemoriaBeta()
# variables del patrón ya ligadas por la izquierda: con sus valores se indexan las dos entradas
self.claves = [(i, x) for i, x in enumerate(patron) if es_var(x) and x in ligadas] if motor.indexado else []
self.idx_izq, self.idx_der = defaultdict(dict), defaultdict(dict)
def clave_hecho(self, hecho):
return tuple(hecho[i] for i, _ in self.claves)
def clave_token(self, b):
return tuple(b[x] for _, x in self.claves)
def une(self, ets, b, et, hecho):
self.motor.comparaciones += 1
b2 = liga(self.patron, hecho, b)
if b2 is not None and all(t.f(*(b2[x] for x in t.variables)) for t in self.tests):
self.motor.nuevo_token(self.salida, ets + (et,), b2)
def activa_izq(self, ets, b): # token nuevo por la izquierda
k = self.clave_token(b)
self.idx_izq[k][ets] = b
for et, hecho in list(self.idx_der.get(k, {}).items()):
self.une(ets, b, et, hecho)
def activa_der(self, et, hecho): # hecho nuevo por la derecha
k = self.clave_hecho(hecho)
self.idx_der[k][et] = hecho
for ets, b in list(self.idx_izq.get(k, {}).items()):
self.une(ets, b, et, hecho)
class Rete:
def __init__(self, reglas, indexado=True, compartir=True):
self.indexado, self.compartir = indexado, compartir
self.alfas = defaultdict(list) # (tipo, aridad) -> memorias alfa
self.nodos = {} # clave estructural -> nodo, para compartir
self.cadena = {} # regla -> memorias beta de sus niveles 1..k
self.hechos, self.contenido, self.reloj = {}, set(), 0
self.tokens_de = defaultdict(list) # etiqueta -> tokens que la contienen
self.agenda, self.comparaciones = {}, 0
for r in reglas:
self.compila(r)
def alfa(self, patron):
constantes = tuple((i, v) for i, v in enumerate(patron) if i > 0 and not es_var(v))
for a in self.alfas[(patron[0], len(patron))]:
if a.constantes == constantes:
return a # memoria alfa compartida
a = MemoriaAlfa(constantes)
self.alfas[(patron[0], len(patron))].append(a)
return a
def compila(self, r):
propia = "" if self.compartir else r.nombre # sin compartir, cada regla tiene sus nodos beta
clave = ("primera", r.lhs[0], propia)
if clave not in self.nodos:
self.nodos[clave] = MemoriaBeta()
self.alfa(r.lhs[0]).sucesores.append(("primera", self.nodos[clave], r.lhs[0]))
mem = self.nodos[clave]
cadena = [mem]
ligadas = {x for x in r.lhs[0] if es_var(x)}
pendientes = list(r.tests)
for patron in r.lhs[1:]:
ahora_ligadas = ligadas | {x for x in patron if es_var(x)}
tests = [t for t in pendientes if set(t.variables) <= ahora_ligadas] # cada test, lo antes posible
pendientes = [t for t in pendientes if t not in tests]
clave = ("join", id(mem), patron, tuple(t.texto for t in tests), propia)
if clave not in self.nodos:
j = Join(self, mem, self.alfa(patron), patron, tests, ligadas)
self.nodos[clave] = j
mem.hijos.append(j)
j.alfa.sucesores.append(("join", j))
mem = self.nodos[clave].salida
cadena.append(mem)
ligadas = ahora_ligadas
mem.producciones.append(r)
self.cadena[r.nombre] = cadena
def nuevo_token(self, mem, ets, b):
if ets in mem.tokens:
return
mem.tokens[ets] = b
for et in ets:
self.tokens_de[et].append((mem, ets))
for r in mem.producciones: # token completo: activación en la agenda
self.agenda[(r.nombre, ets)] = (r, ets, b)
for j in mem.hijos:
j.activa_izq(ets, b)
def inserta(self, hecho):
if hecho in self.contenido: # sin duplicados, como CLIPS
return None
self.reloj += 1
et = self.reloj
self.hechos[et] = hecho
self.contenido.add(hecho)
for a in self.alfas.get((hecho[0], len(hecho)), []): # discriminación por tipo con un dict
self.comparaciones += 1 # una prueba alfa por memoria de ese tipo
if not a.pasa(hecho):
continue
a.hechos[et] = hecho
for suc in a.sucesores:
if suc[0] == "join":
suc[1].activa_der(et, hecho)
elif (b := liga(suc[2], hecho, {})) is not None:
self.nuevo_token(suc[1], (et,), b)
return et
def retira(self, et):
hecho = self.hechos.pop(et)
self.contenido.discard(hecho)
for a in self.alfas.get((hecho[0], len(hecho)), []):
if a.hechos.pop(et, None) is not None:
for suc in a.sucesores:
if suc[0] == "join":
suc[1].idx_der[suc[1].clave_hecho(hecho)].pop(et, None)
for mem, ets in self.tokens_de.pop(et, []): # retirada por árbol: solo los tokens que lo usan
b = mem.tokens.pop(ets, None)
if b is None:
continue
for j in mem.hijos:
j.idx_izq[j.clave_token(b)].pop(ets, None)
for r in mem.producciones:
self.agenda.pop((r.nombre, ets), None)
def dispara(self):
"""Reconocer-actuar hasta vaciar la agenda: salience y después recencia. Hay refracción porque
cada activación sale de la agenda al dispararse y solo vuelve con un token nuevo."""
n = 0
while self.agenda:
clave = max(self.agenda, key=lambda k: (self.agenda[k][0].salience, tuple(sorted(k[1], reverse=True))))
r, ets, b = self.agenda.pop(clave)
n += 1
if r.rhs:
r.rhs(self, ets, b)
return n
def coste_ingenuo(self):
"""Comparaciones que haría el emparejador ingenuo con la memoria actual:
W por el primer patrón y W por cada emparejamiento parcial de cada nivel siguiente."""
W = len(self.hechos)
return sum(W * (1 + sum(len(m.tokens) for m in cad[:-1])) for cad in self.cadena.values())
def ingenuo(reglas, hechos):
"""Emparejamiento desde cero, con bucles anidados sobre toda la memoria: (activaciones, comparaciones)."""
comp, activaciones = 0, set()
items = list(hechos.items())
for r in reglas:
parciales, ligadas, pendientes = [((), {})], set(), list(r.tests)
for patron in r.lhs:
ligadas |= {x for x in patron if es_var(x)}
tests = [t for t in pendientes if set(t.variables) <= ligadas]
pendientes = [t for t in pendientes if t not in tests]
nuevos = []
for ets, b in parciales:
for et, h in items:
comp += 1
if len(h) != len(patron) or h[0] != patron[0]:
continue
if any(not es_var(p) and p != v for p, v in zip(patron, h)):
continue
b2 = liga(patron, h, b)
if b2 is not None and all(t.f(*(b2[x] for x in t.variables)) for t in tests):
nuevos.append((ets + (et,), b2))
parciales = nuevos
activaciones |= {(r.nombre, ets) for ets, _ in parciales}
return activaciones, comp
# Las tres reglas del interactivo y sus doce eventos, con memorias sin índice como en la figura
antes = Test("?t1 < ?t2", ["?t1", "?t2"], lambda a, b: a < b)
despues = Test("?t2 < ?t3", ["?t2", "?t3"], lambda a, b: a < b)
reglas_demo = [
Regla("fuerza-bruta", [("fallo", "?ip", "?t1"), ("fallo", "?ip", "?t2"), ("exito", "?ip", "?u", "?t3")], [antes, despues]),
Regla("fuerza-bruta-admin", [("fallo", "?ip", "?t1"), ("fallo", "?ip", "?t2"), ("exito", "?ip", "admin", "?t3")], [antes, despues]),
Regla("lista-negra", [("exito", "?ip", "?u", "?t"), ("negra", "?ip")]),
]
eventos_demo = [("negra", "X"), ("fallo", "A", 1), ("exito", "C", "luis", 2), ("fallo", "A", 3), ("fallo", "B", 4),
("exito", "A", "ana", 5), ("fallo", "B", 6), ("fallo", "A", 7), ("exito", "B", "admin", 8),
("exito", "X", "eva", 9), ("fallo", "B", 10), ("exito", "A", "ana", 11)]
for compartir in (True, False):
rete = Rete(reglas_demo, indexado=False, compartir=compartir)
total_r = total_n = 0
for ev in eventos_demo:
antes_c = rete.comparaciones
rete.inserta(ev)
activas, coste = ingenuo(reglas_demo, rete.hechos)
assert activas == set(rete.agenda), "Rete y el emparejador ingenuo discrepan"
assert coste == rete.coste_ingenuo()
total_r += rete.comparaciones - antes_c
total_n += coste
if compartir:
print(f"{' '.join(map(str, ev)):16s} Rete {rete.comparaciones - antes_c:3d} ingenuo {coste:4d} agenda {len(rete.agenda)}")
print(f"{'con' if compartir else 'sin'} compartir nodos beta: Rete {total_r} comparaciones, ingenuo {total_n}")
print("activaciones finales:", sorted(rete.agenda))The numbers match the interactive event by event, and both implementations agree on every agenda. Final activations carry fact tags: fuerza-bruta (2, 4, 6) are A’s failures tagged 2 and 4 (times 1 and 3) and success tagged 6. Retraction is the algorithm’s other half: removing (fallo A 3) must remove exactly the tokens and activations using it.
rete = Rete(reglas_demo, indexado=False)
for ev in eventos_demo:
rete.inserta(ev)
print("antes:", sorted(rete.agenda))
et = next(e for e, h in rete.hechos.items() if h == ("fallo", "A", 3))
rete.retira(et)
print(f"tras retirar (fallo A 3), etiqueta {et}:", sorted(rete.agenda))
assert set(rete.agenda) == ingenuo(reglas_demo, rete.hechos)[0]
print("coincide con el emparejamiento ingenuo; memorias beta de fuerza-bruta:",
[len(m.tokens) for m in rete.cadena["fuerza-bruta"]])Lab: correlating 10⁴ authentication events
Now at scale. Function genera_eventos produces a synthetic log of login events with an explicit model: 151 users logging in from their usual IP, sometimes after one or two typos (probabilities 0.12 and 0.03); four attacker IPs sending bursts of 4 to 8 failures in seconds against random accounts and, half the time, succeeding as admin, u017 or u042; and some legitimate users logging in from another country. One attacker IP is on a 20-address blocklist. The rules are those of a small SIEM, now with time windows: two failures from one IP in 60 s followed by a success in that window, the admin variant (priority 10), a blocklisted login, “impossible travel” (same account from two countries in 10 minutes), and a second-level rule opening an incident if one IP accumulates brute-force and blocklist alerts. Their right-hand sides insert alerta facts feeding the last rule: forward chaining.
import random, time
from collections import Counter
def genera_eventos(n=10_000, semilla=7):
"""Registro sintético de autenticaciones: tráfico legítimo con erratas, ráfagas de atacantes y viajes imposibles."""
rnd = random.Random(semilla)
usuarios = [f"u{i:03d}" for i in range(150)] + ["admin"]
casa = {u: f"10.0.{i // 200}.{i % 200}" for i, u in enumerate(usuarios)} # cada usuario entra desde su IP, en ES
atacantes = ["198.51.100.7", "198.51.100.23", "203.0.113.9", "203.0.113.50"]
negras = [f"203.0.113.{k}" for k in range(1, 40, 2)] # 203.0.113.9 está en la lista negra
eventos, t = [], 0
while len(eventos) < n:
t += rnd.randint(1, 16)
x = rnd.random()
if x < 0.004: # ráfaga: de 4 a 8 fallos en pocos segundos
ip = rnd.choice(atacantes)
for _ in range(rnd.randint(4, 8)):
t += rnd.randint(1, 3)
eventos.append(("fallo", ip, rnd.choice(usuarios), t))
if rnd.random() < 0.5: # y, la mitad de las veces, un acceso que entra
t += rnd.randint(1, 5)
eventos.append(("exito", ip, rnd.choice(["admin", "u017", "u042"]), t, "US"))
elif x < 0.006: # la misma cuenta, desde otro país
u = rnd.choice(usuarios)
eventos.append(("exito", f"192.0.2.{rnd.randint(1, 254)}", u, t, rnd.choice(["PT", "FR", "DE", "US"])))
else: # acceso legítimo, a veces con una o dos erratas
u = rnd.choice(usuarios)
for _ in range(rnd.choices([0, 1, 2], [0.85, 0.12, 0.03])[0]):
eventos.append(("fallo", casa[u], u, t))
t += rnd.randint(2, 9)
eventos.append(("exito", casa[u], u, t, "ES"))
return [("negra", ip) for ip in negras] + eventos[:n], set(atacantes)
def alerta(tipo, var_clave, var_t):
return lambda motor, ets, b: motor.inserta(("alerta", tipo, b[var_clave], b[var_t]))
ventana_2 = Test("?t1 < ?t2 <= ?t1 + 60", ["?t1", "?t2"], lambda t1, t2: t1 < t2 <= t1 + 60)
ventana_3 = Test("?t2 < ?t3 <= ?t1 + 60", ["?t1", "?t2", "?t3"], lambda t1, t2, t3: t2 < t3 <= t1 + 60)
reglas_soc = [
Regla("fuerza-bruta", [("fallo", "?ip", "?u1", "?t1"), ("fallo", "?ip", "?u2", "?t2"), ("exito", "?ip", "?u", "?t3", "?p")],
[ventana_2, ventana_3], rhs=alerta("fuerza-bruta", "?ip", "?t3")),
Regla("fuerza-bruta-admin", [("fallo", "?ip", "?u1", "?t1"), ("fallo", "?ip", "?u2", "?t2"), ("exito", "?ip", "admin", "?t3", "?p")],
[ventana_2, ventana_3], rhs=alerta("admin-comprometido", "?ip", "?t3"), salience=10),
Regla("lista-negra", [("exito", "?ip", "?u", "?t", "?p"), ("negra", "?ip")], rhs=alerta("lista-negra", "?ip", "?t")),
Regla("viaje-imposible", [("exito", "?ip1", "?u", "?t1", "?p1"), ("exito", "?ip2", "?u", "?t2", "?p2")],
[Test("?p1 != ?p2 and ?t1 < ?t2 <= ?t1 + 600", ["?p1", "?p2", "?t1", "?t2"], lambda p1, p2, t1, t2: p1 != p2 and t1 < t2 <= t1 + 600)],
rhs=alerta("viaje-imposible", "?u", "?t2")),
Regla("incidente", [("alerta", "fuerza-bruta", "?ip", "?ta"), ("alerta", "lista-negra", "?ip", "?tb")],
rhs=lambda motor, ets, b: motor.inserta(("incidente", b["?ip"]))),
]
class ReteConCuenta(Rete):
"""Rete que, tras cada cambio de la memoria, suma lo que costaría rehacer el emparejamiento ingenuo."""
def __init__(self, *a, **k):
super().__init__(*a, **k)
self.ingenuo = 0
def inserta(self, hecho):
et = super().inserta(hecho)
if et is not None:
self.ingenuo += self.coste_ingenuo()
return et
eventos, atacantes = genera_eventos()
motor = ReteConCuenta(reglas_soc)
disparos, hitos = 0, {}
t0 = time.perf_counter()
for i, ev in enumerate(eventos, 1):
motor.inserta(ev)
disparos += motor.dispara()
if i in (1000, 3000, len(eventos)):
hitos[i] = (motor.comparaciones, motor.ingenuo)
segundos = time.perf_counter() - t0
alertas = [h for h in motor.hechos.values() if h[0] == "alerta"]
print(f"{len(eventos)} hechos de entrada {dict(Counter(e[0] for e in eventos))}")
print(f"Rete: {segundos:.2f} s, {motor.comparaciones:,} comparaciones, {disparos} disparos")
print("alertas:", dict(Counter(a[1] for a in alertas)))
fb = [a for a in alertas if a[1] == "fuerza-bruta"]
print(f" de las {len(fb)} de fuerza bruta, {sum(a[2] in atacantes for a in fb)} son de IP atacantes y "
f"{sum(a[2].startswith('10.') for a in fb)} de usuarios legítimos con dos erratas")
adm = [a for a in alertas if a[1] == "admin-comprometido"]
print(f" de las {len(adm)} de admin comprometido, {sum(a[2] in atacantes for a in adm)} son de IP atacantes")
print("incidentes:", [h for h in motor.hechos.values() if h[0] == "incidente"])
print("tokens en las memorias beta:", {r: [len(m.tokens) for m in cad] for r, cad in motor.cadena.items()})
for n, (cr, cn) in hitos.items():
print(f"tras {n:5d} hechos de entrada: Rete {cr:.2e} comparaciones, ingenuo {cn:.2e}, cociente {cn / cr:,.0f}")Rete processes 10,020 input facts ( events and 20 blocklisted IPs) with about comparisons and 652 firings. Naive matching, repeating everything after each of 10,344 memory changes (inputs plus alerts and incident), counts : over a million times more. The ratio grows with the log (about times after 1000 facts, after 3000), because naive matching pays per change proportional to memory size, and Rete proportional to what the change touches. The naive count comes from coste_ingenuo’s formula; the next cell verifies it exactly by actually running naive matching on the first hundred events, and estimates full-log time.
m = ReteConCuenta(reglas_soc)
for ev in eventos[:100]:
m.inserta(ev)
m.dispara()
hechos, reales = {}, 0
t0 = time.perf_counter()
for et, h in sorted(m.hechos.items()): # la memoria tal como era tras cada cambio
hechos[et] = h
reales += ingenuo(reglas_soc, hechos)[1]
t_ing = time.perf_counter() - t0
print(f"{len(m.hechos)} hechos: ingenuo medido {reales:,} comparaciones, fórmula {m.ingenuo:,}, Rete {m.comparaciones:,}")
velocidad = reales / t_ing
print(f"el ingenuo va a {velocidad:.2e} comparaciones/s aquí: con los 10⁴ eventos tardaría unos "
f"{hitos[len(eventos)][1] / velocidad / 86400:.0f} días")The formula matches measurement to the digit. At the speed naive matching traverses memory in your browser, the full log would take days; Rete takes seconds. This is not an exaggeration: it is why no serious rule engine matches naively.
What alerts say: the cost of a poorly tuned rule
The lab’s most instructive result is not speed. Of 274 brute-force alerts, only 14 come from attacker IPs; the other 260 are legitimate users who mistyped twice before logging in on the third attempt. “Two failures and one success in a minute” describes an attacker as well as a hurried person. The data show the difference: the attacker tries different accounts (password spraying), while the user repeats their own. Add test ?u1 != ?u2:
distintas = Test("?u1 != ?u2", ["?u1", "?u2"], lambda u1, u2: u1 != u2)
afinadas = [
Regla("fuerza-bruta", reglas_soc[0].lhs, [ventana_2, distintas, ventana_3], rhs=alerta("fuerza-bruta", "?ip", "?t3")),
Regla("fuerza-bruta-admin", reglas_soc[1].lhs, [ventana_2, distintas, ventana_3],
rhs=alerta("admin-comprometido", "?ip", "?t3"), salience=10),
] + reglas_soc[2:]
motor2 = Rete(afinadas)
for ev in eventos:
motor2.inserta(ev)
motor2.dispara()
alertas2 = [h for h in motor2.hechos.values() if h[0] == "alerta"]
for tipo in ("fuerza-bruta", "admin-comprometido"):
a = [h for h in alertas2 if h[1] == tipo]
print(f"{tipo:19s}: {len(a):3d} alertas, {sum(h[2] in atacantes for h in a)} de IP atacantes")
accesos = [e for e in eventos if e[0] == "exito" and e[1] in atacantes]
print(f"accesos con éxito de las IP atacantes en el registro: {len(accesos)}")
print("incidentes:", [h for h in motor2.hechos.values() if h[0] == "incidente"])Now all 14 brute-force alerts correspond exactly to the 14 attacker-IP logins, and admin alerts drop from 8 to 7 (the extra was the administrator with two typos). This is knowledge engineering in miniature with an uncomfortable lesson: the tuned rule no longer detects classic brute force against one account, absent from this log but possible in another. Each tuning can close a false positive while opening a false negative, and maintainers must know this. Notice the first cell’s beta memories: 635 failure pairs and 478 fuerza-bruta instances yielding 274 distinct alerts because several instances conclude the same alert. “ failures” rules written as a cross product generate tokens per burst. Engines therefore offer aggregates (accumulate in Drools, event_count in Sigma correlation rules) instead of repeated patterns.
Backward chaining: MYCIN and consultation dialogue
Rete is forward chaining: data arrives and rules react. But a physician facing a patient with fever lacks all data, has a question (“which organism causes the infection?”), and can order tests. Edward Shortliffe built MYCIN, the most influential expert system in history, at Stanford for this in his 1970s thesis. MYCIN advised on bloodstream infections and meningitis, reasoning backward: start from the goal, find rules concluding it and, for each premise, derive it with other rules or ask the physician. A typical rule in its format:
IF 1) the organism’s stain is gram-negative, and 2) its morphology is a bacillus, and 3) it is anaerobic, THEN there is suggestive evidence (0.6) that its identity is Bacteroides.
The 0.6 is a certainty factor, MYCIN’s mechanism for combining uncertain evidence; you will study it and its problems in certainty factors. Here we keep the logical structure, Prolog’s SLD resolution with three additions:
- Askables. Some atoms are concluded by no rule: ask the user the first time they are needed and remember the answer.
- Goal memory. Remember a derived (or failed) goal to avoid reproving it or repeating questions in another branch.
- Explanation. At any question the user can write why? (WHY): the system gives the rule being tried and goal pursued, and each further “why?” climbs one level of the goal stack. At the end, how? (HOW) shows the rule trace leading to a conclusion.
Question order follows hypothesis, rule and premise order: the system asks what the first rule of the first hypothesis needs and moves on only if it fails. A well-designed system therefore puts cheap or decisive questions first.
Notice three things. The first question asks about “ten or more failures in five minutes”, not whether the account is privileged, although the first rule (T1) starts there: T1 first requires “compromised account”, and the engine descends through T5 and T7 to an askable before returning. In impossible travel with MFA, the engine rejects both compromise rules, abandons incident hypotheses without asking whether the account is privileged, and reaches a false positive when the owner confirms the login: asking only what is needed is backward chaining’s main dialogue advantage. “I don’t know” fails the premise, like “no” for positive premises: the closed-world assumption applied to answers. In T6, the negated premise “no successful MFA” requires an explicit “no”, so “I don’t know” does not satisfy it either; treating ignorance as negation would be convenient here and dangerous there, so MYCIN used certainty factors rather than true or false.
The cell implements the requested lab domain, vulnerability triage: ten rules deciding patch priority from service exposure, authentication requirement, leaked credentials, presence in CISA’s KEV catalog, impact on sensitive data and mitigation. The user is simulated (an answer dictionary) and asks “why?” at one question.
from dataclasses import dataclass
@dataclass
class ReglaBC:
nombre: str
conclusion: str
premisas: list # átomos; "no x" exige que la pregunta x se haya respondido «no»
texto: str = ""
BASE = [
ReglaBC("V1", "prioridad=crítica", ["explotable en remoto", "explotación activa"],
"una vulnerabilidad explotable en remoto que ya se está explotando es crítica"),
ReglaBC("V2", "prioridad=crítica", ["explotable en remoto", "datos sensibles", "sin mitigación"],
"explotable en remoto, sin mitigación y sobre datos sensibles es crítica"),
ReglaBC("V3", "prioridad=alta", ["explotable en remoto"], "lo explotable en remoto es, como poco, alta"),
ReglaBC("V4", "prioridad=alta", ["explotación activa", "sin mitigación"], "explotación activa sin mitigación es alta"),
ReglaBC("V5", "prioridad=media", ["exploit público"], "con exploit público, media"),
ReglaBC("V6", "prioridad=baja", [], "si nada de lo anterior se cumple, baja"),
ReglaBC("V7", "explotable en remoto", ["expuesta a internet", "no requiere autenticación"],
"expuesta y sin autenticación previa: cualquiera puede alcanzarla"),
ReglaBC("V8", "explotable en remoto", ["expuesta a internet", "credenciales filtradas"],
"expuesta y con credenciales válidas filtradas: la autenticación no protege"),
ReglaBC("V9", "explotación activa", ["en el catálogo KEV"], "CISA la lista como explotada activamente"),
ReglaBC("V10", "sin mitigación", ["no parche aplicable", "no regla WAF"], "ni parche aplicable ni regla que la bloquee"),
]
PREGUNTABLES = {"expuesta a internet", "requiere autenticación", "credenciales filtradas", "en el catálogo KEV",
"datos sensibles", "parche aplicable", "regla WAF", "exploit público"}
HIPOTESIS = ["prioridad=crítica", "prioridad=alta", "prioridad=media", "prioridad=baja"]
class Consulta:
"""Encadenamiento hacia atrás con preguntas, memoria de respuestas y explicaciones por qué y cómo."""
def __init__(self, base, responde):
self.base, self.responde = base, responde # responde(pregunta, pila) -> True/False
self.respuestas, self.probado, self.pila = {}, {}, []
self.preguntas = 0
def pregunta(self, atomo):
if atomo not in self.respuestas:
self.preguntas += 1
self.respuestas[atomo] = self.responde(atomo, list(self.pila))
return self.respuestas[atomo]
def demuestra(self, objetivo):
"""True si el objetivo se deriva; guarda en self.probado la regla que lo prueba."""
if objetivo.startswith("no "):
return self.pregunta(objetivo[3:]) is False # negación de una pregunta, no de un objetivo derivado
if objetivo in PREGUNTABLES:
return self.pregunta(objetivo)
if objetivo in self.probado:
return self.probado[objetivo] is not None
for r in self.base:
if r.conclusion != objetivo:
continue
self.pila.append((r, objetivo))
ok = all(self.demuestra(p) for p in r.premisas) # en orden y con cortocircuito
self.pila.pop()
if ok:
self.probado[objetivo] = r
return True
self.probado[objetivo] = None # fallo memorizado: no se vuelve a intentar
return False
def diagnostica(self):
return next(h for h in HIPOTESIS if self.demuestra(h))
def como(self, atomo, sangria=""):
"""Traza de derivación: la regla que lo probó y cómo se probó cada premisa."""
if atomo.startswith("no ") or atomo in PREGUNTABLES:
base = atomo[3:] if atomo.startswith("no ") else atomo
return [f"{sangria}{atomo}: respondiste «{'sí' if self.respuestas[base] else 'no'}» a «¿{base}?»"]
r = self.probado[atomo]
lineas = [f"{sangria}{atomo}: por {r.nombre} ({r.texto})"]
for p in r.premisas:
lineas += self.como(p, sangria + " ")
return lineas
def por_que(pila):
"""Respuesta a «¿por qué me lo preguntas?»: la cadena de reglas y objetivos abiertos, de dentro afuera."""
return [f" porque intento {r.nombre}: si {' y '.join(r.premisas)}, entonces {obj}" for r, obj in reversed(pila)]
# Un caso: servidor expuesto, la vulnerabilidad pide autenticación, pero hay credenciales filtradas.
caso = {"expuesta a internet": True, "requiere autenticación": True, "credenciales filtradas": True,
"en el catálogo KEV": False, "datos sensibles": True, "parche aplicable": False, "regla WAF": False,
"exploit público": True}
def usuario(atomo, pila):
print(f"¿{atomo}? -> {'sí' if caso[atomo] else 'no'}")
if atomo == "parche aplicable": # aquí el usuario pide explicaciones antes de responder
print(" [¿por qué?]")
print("\n".join(por_que(pila)))
return caso[atomo]
c = Consulta(BASE, usuario)
resultado = c.diagnostica()
print(f"\nConclusión: {resultado} ({c.preguntas} preguntas de {len(PREGUNTABLES)} posibles)")
print("[¿cómo?]")
print("\n".join(c.como(resultado)))Read the trace carefully. After “requires authentication: yes”, V7’s negated premise fails and the engine tries V8, asking about leaked credentials. V1 fails because it is not in KEV, and the engine moves to V2 without asking again whether it is remotely exploitable: that goal was proven and remembered. The patch “why?” shows two levels, V10 inside V2, and the “how” explanation is the derivation tree. “Public exploit” is never asked: only V5 needs it, and consultation ends earlier.
Two engine limitations matter. Failure memory is correct because answers do not change during consultation; with recursive rules (a goal depending on itself through other rules), cycle detection would be needed, exactly the SLD termination problem seen in Prolog. Negation is only applied to askables: negating a derived goal would be negation as failure, with all its subtleties.
Expert-system architecture
MYCIN left an architecture pattern that became industry standard. EMYCIN (“empty MYCIN”, van Melle, 1979) made its key separation explicit: remove medical rules and leave engine, interface and explanation as a reusable shell for any domain. It supported lung diagnosis and structural-analysis systems without rewriting the engine.
The best-known acquisition facility was TEIRESIAS (Randall Davis, 1976), built on MYCIN: when an expert disagreed with a conclusion, TEIRESIAS walked the “how” trace with them to locate the wrong or missing rule, and checked that the new rule resembled existing rules of its type. Debugging knowledge in context, using a concrete case, remains the most effective way to maintain rule bases.
The explanation facility has a limit William Clancey analyzed in 1983 when trying to teach medicine with MYCIN in his GUIDON system: a rule trace says which rules were applied, not why they are true. A rule like Bacteroides compresses causal knowledge (organism physiology) and strategic knowledge (which hypothesis order is efficient) the system does not represent, so its “explanation” resembles a student reciting notes. Clancey distinguished rule knowledge, support (why a rule is valid), and strategic knowledge (why hypotheses are explored in that order), showing that genuine explanation requires representing all three.
Knowledge engineering
Building the knowledge base proved difficult. Edward Feigenbaum, who led DENDRAL and Stanford’s heuristic programming project, named the discipline knowledge engineering in the late 1970s and summarized it: an expert system’s power lies in domain knowledge, not its inference engine.
The case best showing both sides is R1, later XCON, from John McDermott (Carnegie Mellon) and Digital Equipment Corporation. Configuring a VAX order was a design problem: choose compatible cabinets, buses, power supplies and cables for hundreds of components, work by expert technicians who often erred. R1, an OPS-family production system, entered use at Digital’s Salem, New Hampshire plant in 1980. Its 1982 description became a classic, and in 1989 Barker and Digital colleagues estimated annual savings in tens of millions of dollars. That is the good side.
The other side is maintenance. Soloway, Bachant and Jensen (1987) report that in seven years XCON grew to 6200 rules, about half changing annually as each new Digital product brought new components and constraints; by 1989 it had 10,129 rules. With OPS5 rules interacting through conflict resolution, each change could break distant behavior, and Digital eventually rewrote the base using a methodology (RIME) structuring it into subtasks with explicit control instead of leaving order to conflict resolution. This is the agenda mistake at industrial scale.
Knowledge-engineering limits also contributed to the decline. Expert systems were brittle: competent in a narrow domain, with no common sense at the boundary, where they failed silently. Knowledge did not transfer between problems. MYCIN, which in a blind evaluation by Yu et al. (1979) achieved 65% acceptable treatment recommendations from eight external evaluators versus 42.5% to 62.5% for five Stanford faculty members, never entered clinical practice. In the late 1980s the market for Lisp machines running many such systems collapsed against general-purpose workstations, expectations deflated and funding fell: the second AI winter. Rule engines did not disappear; they stopped being called AI and became enterprise software, where you will find them today.
Modern rule and policy engines
With this background, read any current rule engine as a production system and ask four questions: what is working memory, how are conditions written, what do actions do, and who resolves conflicts?
| System | Working memory | Conditions | Actions | Conflicts and evaluation |
|---|---|---|---|---|
| CLIPS | facts and objects | patterns with variables and tests | assert, retract, modify, functions | Rete; depth (default), breadth, LEX, MEA, simplicity, complexity, random strategies, with salience |
| Drools | Java objects | object patterns, accumulate, time windows | Java code, insert, update | PHREAK; salience and agenda groups |
| OPA / Rego | input document and data | Datalog-inspired declarative rules | none: only produce a decision | on-demand query for the decision requested (e.g. allow); without effects order does not matter |
| Sigma | log events | field selections and a Boolean condition; correlation rules with event_count, temporal or temporal_ordered over a window and grouping fields | generate an alert | translated to the target SIEM query |
| YARA | file or process-memory bytes | strings and regular expressions with a Boolean condition over them | mark the object | all strings searched simultaneously with an Aho–Corasick automaton, then conditions evaluated |
| ModSecurity with OWASP CRS | HTTP request | operators over request variables | add to anomaly score, block | rules evaluated in order by phase; block decided on crossing score threshold |
Three observations. OPA and Datalog occupy the monotone corner: without deleting actions the confluence theorem yields an order-independent result, desirable for access policy. YARA and Rete’s alpha network share the idea of discriminating against many patterns in one pass. CRS deliberately avoids “the first matching rule decides”: each rule adds evidence and a threshold decides, avoiding firing-order brittleness.
The same rules in CLIPS
CLIPS is the most-used classic production system still in use, and clipspy exposes it to Python. This part runs on your machine (runtime=local) because CLIPS is a C library unavailable in the browser; install with pip install clipspy. First, a hidden cell repeats required earlier definitions in the local process: Rete engine, event generator and rules.
CLIPS rules read almost like ours: ?t2&:(< ?t1 ?t2) means “bind ?t2 and check the test”, and ?p2&~?p1 means “different from ?p1”. Facts are ordered (positional), like ours, and IPs are strings. CLIPS does not allow duplicate facts either, so repeated alerts inserted by multiple fuerza-bruta instances for the same login are ignored, as in our engine.
import clips
REGLAS_CLIPS = [
"""(defrule fuerza-bruta
(fallo ?ip ?u1 ?t1)
(fallo ?ip ?u2 ?t2&:(< ?t1 ?t2)&:(<= ?t2 (+ ?t1 60)))
(exito ?ip ?u ?t3&:(< ?t2 ?t3)&:(<= ?t3 (+ ?t1 60)) ?p)
=>
(assert (alerta fuerza-bruta ?ip ?t3)))""",
"""(defrule fuerza-bruta-admin (declare (salience 10))
(fallo ?ip ?u1 ?t1)
(fallo ?ip ?u2 ?t2&:(< ?t1 ?t2)&:(<= ?t2 (+ ?t1 60)))
(exito ?ip "admin" ?t3&:(< ?t2 ?t3)&:(<= ?t3 (+ ?t1 60)) ?p)
=>
(assert (alerta admin-comprometido ?ip ?t3)))""",
"""(defrule lista-negra
(exito ?ip ?u ?t ?p)
(negra ?ip)
=>
(assert (alerta lista-negra ?ip ?t)))""",
"""(defrule viaje-imposible
(exito ?ip1 ?u ?t1 ?p1)
(exito ?ip2 ?u ?t2&:(< ?t1 ?t2)&:(<= ?t2 (+ ?t1 600)) ?p2&~?p1)
=>
(assert (alerta viaje-imposible ?u ?t2)))""",
"""(defrule incidente
(alerta fuerza-bruta ?ip ?ta)
(alerta lista-negra ?ip ?tb)
=>
(assert (incidente ?ip)))""",
]
def a_clips(hecho):
"""Hecho de Python a hecho ordenado de CLIPS: los valores de texto van como cadenas."""
return "(" + " ".join(f'"{x}"' if isinstance(x, str) and i > 0 else str(x) for i, x in enumerate(hecho)) + ")"
def de_clips(f):
return tuple([f.template.name] + [str(x) if isinstance(x, str) else x for x in f])
env = clips.Environment()
for r in REGLAS_CLIPS:
env.build(r)
env.eval("(set-strategy lex)")
t0 = time.perf_counter()
disparos_clips = 0
for ev in eventos: # un evento cada vez, con su ciclo reconocer-actuar
env.assert_string(a_clips(ev))
disparos_clips += env.run()
t_clips = time.perf_counter() - t0
hechos_clips = {de_clips(f) for f in env.facts()}
motor = Rete(reglas_soc)
t0 = time.perf_counter()
disparos_py = 0
for ev in eventos:
motor.inserta(ev)
disparos_py += motor.dispara()
t_py = time.perf_counter() - t0
hechos_py = set(motor.hechos.values())
print(f"CLIPS: {t_clips:.2f} s, {disparos_clips} disparos")
print(f"Rete propio: {t_py:.2f} s, {disparos_py} disparos -> CLIPS es {t_py / t_clips:.1f} veces más rápido")
print("alertas CLIPS:", dict(Counter(h[1] for h in hechos_clips if h[0] == "alerta")))
print("¿mismos hechos al final?", hechos_clips == hechos_py, f"({len(hechos_py)} hechos)")npm run lab and open the connection link.Both engines end with exactly the same facts and 652 firings, validating ours against a reference implementation. CLIPS is clearly faster (two to three times in our runs) even though each event crosses the Python–C boundary: its Rete is written in C with compact structures; ours pays interpreter cost per comparison. The algorithm fixes the same order of magnitude of work.
Semantic differences lie in the agenda. CLIPS puts salience above any strategy, and its default is not LEX but depth: new activations go above equally prioritized ones. Check the first section’s triage with each strategy and the counter loop with modify:
TRIAJE = [
"""(defrule bloquear
?a <- (alerta ?ip ?tipo abierta)
=>
(assert (bloqueo ?ip)) (retract ?a) (assert (alerta ?ip ?tipo bloqueada)) (anota bloquear))""",
"""(defrule descartar
?a <- (alerta ?ip ?tipo abierta)
(lista-blanca ?ip)
=>
(retract ?a) (assert (alerta ?ip ?tipo descartada)) (anota descartar))""",
"""(defrule escalar
(fase triaje)
?a <- (alerta ?ip fuerza-bruta abierta)
(exito ?ip ?u)
=>
(assert (incidente ?ip ?u)) (retract ?a) (assert (alerta ?ip fuerza-bruta escalada)) (anota escalar))""",
"""(defrule avisar
(incidente ?ip ?u)
=>
(anota avisar))""",
]
traza = []
for estrategia in ["depth", "breadth", "lex", "mea", "complexity"]:
env.clear()
env.define_function(lambda nombre: traza.append(str(nombre)), name="anota")
for r in TRIAJE:
env.build(r)
env.eval(f"(set-strategy {estrategia})")
for h in ['(fase triaje)', '(lista-blanca "10.0.0.7")', '(alerta "10.0.0.7" fuerza-bruta abierta)', '(exito "10.0.0.7" ana)']:
env.assert_string(h)
traza.clear()
env.run(20)
print(f"{estrategia:10s} {' -> '.join(traza)}")
# modify en CLIPS: retira e inserta con un índice nuevo, así que la regla se reactiva
env.clear()
env.build("(deftemplate intentos (slot ip) (slot n))")
env.build("(deftemplate fallo (slot ip) (slot t))")
env.build("""(defrule contar
?c <- (intentos (ip ?ip) (n ?n))
(fallo (ip ?ip))
=>
(modify ?c (n (+ ?n 1))))""")
env.reset()
for h in ['(intentos (ip "10.0.0.7") (n 0))', '(fallo (ip "10.0.0.7") (t 1))', '(fallo (ip "10.0.0.7") (t 2))']:
env.assert_string(h)
print("contar sin consumir el fallo: disparos con límite 50 =", env.run(50),
"| n =", next(f["n"] for f in env.facts() if f.template.name == "intentos"))npm run lab and open the connection link.Rules here have no salience so the strategy alone decides. CLIPS reproduces our sequences: lex and complexity (specificity) escalate; mea discards; and the two strategies our engine does not implement differ too, depth escalates and breadth discards. The counter with modify reaches the 50-firing limit with n = 50: the conflict-resolution section’s loop in a real production engine. Another porting difference: in CLIPS, modify exists only for template facts (deftemplate), and refraction and agenda apply to activations, created and destroyed with each fact change, exactly as in our engine.
When to use a rule engine or a learned model
No general argument decides this; problem properties do. Factors favoring explicit rules:
- Required auditability. If every decision must be justified to a regulator or customer (denying credit, blocking an account), a rule trace gives direct justification; a learned model’s is at best an after-the-fact approximation.
- Existing knowledge changing quickly. A new law, compromise indicator published this morning, company policy: write a rule and deploy in minutes, without labeled data or retraining.
- Few or no examples. A new fraud type has no history to learn; an analyst can still describe it.
- Hard constraints. “Never authorize payment to a sanctioned country” is not a statistical trend: it must always hold.
Factors favoring a learned model: many variables with subtle interactions no one can state, plentiful labeled data, tolerance of individual errors for better average performance, and perception (images, free text, audio), where rules historically failed.
In practice effective systems are often hybrids: a model produces a risk score entering working memory as another fact, and rules decide using it and hard constraints (“score above 0.9 or sanctioned country: block; 0.6 to 0.9: manual review”). Choose the smallest suitable rule tool: if logic is monotone (policies, permissions, reachability), a Datalog-family language such as Rego provides termination and an order-independent result; if state and actions are needed, a production engine, with the conflict-resolution section’s care.
Common mistakes
Exercises
fuerza-bruta rule, without the distinct-accounts test, seeks with . One IP makes 8 failures in 20 seconds (distinct times), then 3 successful logins, all within 60 seconds of the first failure. How many fuerza-bruta activations enter the agenda?JoinNode. It receives a test(token, hecho) deciding whether a token (tuple of facts) and a fact can join. It maintains left memory (left, tokens), right memory (right, facts), the set output of current output tokens (each token + (hecho,)), and comparisons counting calls to test. Activations store their argument, compare it only against opposite memory and return the list of new output tokens. Retractions remove their argument and return the list of output tokens no longer valid. Tests cover every arrival order, comparison count and retractions.class JoinNode:
"""Nodo join de Rete: tokens (tuplas de hechos) por la izquierda, hechos por la derecha."""
def __init__(self, test):
self.test = test # test(token, hecho) -> bool
self.left = [] # memoria izquierda: tokens
self.right = [] # memoria derecha: hechos
self.output = set() # tokens de salida vigentes: token + (hecho,)
self.comparisons = 0 # llamadas a self.test
def left_activate(self, token):
"""Guarda el token y devuelve la lista de tokens de salida nuevos."""
pass
def right_activate(self, fact):
"""Guarda el hecho y devuelve la lista de tokens de salida nuevos."""
pass
def left_retract(self, token):
"""Quita el token y devuelve la lista de tokens de salida que dejan de valer."""
pass
def right_retract(self, fact):
"""Quita el hecho y devuelve la lista de tokens de salida que dejan de valer."""
passSummary
- Production system: working memory with time tags, instances as rule plus concrete facts, conflict set. With positive insert-only rules and refraction, any strategy reaches the least model.
- Conflict resolution: refraction, recency, specificity and salience; OPS5’s LEX and MEA. Three reasonable strategies produced three triage results. Refraction does not stop
modifyloops, which create new tags. - Rete: alpha network for single-fact tests, beta network of joins with token memories, shared nodes and tree-based retraction. In the lab, comparisons versus naive on events, with the ratio growing with the log. TREAT omits beta memories and Rete/UL unlinks empty joins to scale to hundreds of thousands of rules.
- Expert systems: backward chaining with remembered questions and why/how explanations, as in MYCIN; architecture with reusable shell (EMYCIN) and contextual acquisition (TEIRESIAS). Explanations are calculation traces, not domain justifications.
- Knowledge engineering: acquisition bottleneck and maintenance cost (XCON, 6200 rules in 1987 with half changing annually). In the lab a reasonable rule produced 260 false positives among 274 alerts, and tuning opened a false negative.
- Today: CLIPS, Drools, OPA, Sigma, YARA and CRS are production or rule systems under other names. Rules for auditability, rapid change or hard constraints; models for data and patterns nobody can state; usually both.