Logic programming: Prolog, Datalog and Answer Set Programming
Restricting logic to Horn clauses turns inference into computation. Study forward chaining as a fixed point (Datalog with seminaive evaluation and stratified negation), backward chaining by SLD resolution (Prolog), and stable-model semantics of Answer Set Programming, with direct applications to static program analysis such as the taint analysis underlying CodeQL.
After this lesson you can
- Characterize the least model of a Horn program as the least fixed point of T_P.
- Implement a seminaive Datalog engine with stratified negation.
- Write program analyses (taint and points-to) as Datalog rules.
- Implement SLD resolution and explain Prolog behavior, including cut.
- Model combinatorial problems in ASP and compute stable models with clingo.
Before you start
Motivation: when inference is the program
In the previous lesson you saw that first-order resolution is complete but expensive: a prover saturates clause sets that grow uncontrollably and, since first-order logic is only semidecidable, never knows whether it is close or will never finish. This lesson studies what happens when some expressive power is traded for inference behaving like a program. There is one restriction: each clause has exactly one positive literal. Reasoning then becomes computation rather than blind search, and three families of systems used in production emerge.
- Static program analysis. CodeQL, GitHub’s code-analysis engine, compiles its QL query language to Datalog and evaluates it on a database extracted from code; its authors describe scaling to programs of millions of lines (Avgustinov, de Moor, Peyton Jones and Schäfer, 2016). Doop expresses Java pointer analysis in about 180 Datalog rules and, with exactly the same logical definition and thus precision, is over 15 times faster than Paddle, the BDD-based reference system, on one-call-sensitive analysis of DaCapo benchmarks (Bravenboer and Smaragdakis, 2009). Soufflé compiles Datalog to parallel C++, and its authors report pointer analysis of the OpenJDK 7 library (1.4 million variables, 350,000 objects, 160,000 methods) in under a minute (Jordan, Scholz and Subotić, 2016).
- Prolog. Colmerauer and Roussel created it in Marseille in 1972, in contact with Kowalski, who published in 1974 the procedural reading of Horn clauses on which it rests: “to prove , prove ”. It remains a natural language for parsers, type systems and backtracking search.
- Answer Set Programming. Adding negation with Gelfond and Lifschitz’s stable-model semantics (1988) produces a declarative language for NP-complete combinatorial problems (configuration, planning, scheduling), solved using the same CDCL machinery as modern SAT solvers.
The route goes from semantics to code. First, why Horn clauses have a least model and why that model is an operator ‘s least fixed point; this gives forward chaining. Next backward chaining, the SLD resolution run by Prolog, with two traps (left recursion and cut). Then negation: as finite failure, closed world and Clark completion. You will build a seminaive Datalog engine with stratified negation and use it for taint and pointer analyses. Finally, stable models, the generate–define–test pattern, and how clingo solves them. Normal cells run in the browser; those marked local need pip install clingo ortools, and the quoted measurements come from running clingo 5.8.2 and OR-Tools 9.15.
Definite programs: Horn’s sweet spot
In discrete mathematics you solved Horn-SAT in linear time: with clauses of form , mark as true what must be true and check that no constraint has its whole body marked. No guessing is needed. Logic programming is that idea in first order.
As clauses these are exactly Horn clauses with one positive literal: . Their semantics can be studied using only Herbrand interpretations: the Herbrand universe is the ground terms constructible from constants and function symbols of ; the Herbrand base , all ground atoms with predicates from and arguments in ; and a Herbrand interpretation is simply a subset , the atoms it declares true. models if it satisfies every ground instance of every clause: whenever the body is in , so is the head.
Proof
Let be a ground instance of a clause of with all in . Then each is in every and, since is a model, for every . Hence .
∎All of is always a model (all heads are true), so the family of Herbrand models is nonempty and its intersection is the least of them.
Proof
() If , is true in every model of ; in particular every Herbrand model, and therefore their intersection. () Suppose and let be any model of , not necessarily Herbrand. Define . It is a Herbrand model of : if a ground instance has its in , they are true in , and since satisfies the universal clause it satisfies that instance too, so is true in and in . Therefore , and . Since was arbitrary, .
∎The least model is therefore everything the program says and nothing more: the declarative semantics of a definite program is a unique set of facts. Notice what ensures existence: with a non-Horn clause such as , models and are both minimal and their intersection, , is not a model. The single positive literal guarantees a least one.
What does deciding cost? It depends on function symbols. With them, definite programs compute any computable function (Tärnlund, 1977), and is only semidecidable, as in general first order. Without function symbols, are the program constants and is finite: that is Datalog. Its complexity is well characterized (Dantsin, Eiter, Gottlob and Voronkov, 2001): with fixed program and varying data (data complexity, relevant when the program is an analysis and the data your code), deciding is P-complete; if the program also varies it is EXPTIME-complete, because a relation of arity over constants can have tuples. This is the sweet spot: expressive enough for recursion (transitive closures, reachability, flow analysis) with polynomial evaluation in the data.
Forward chaining: the T_P operator
The most direct way to calculate is Horn-SAT’s: start empty and fire rules until nothing new appears. The operator taking one step is central to the theory.
Herbrand interpretations ordered by inclusion form a complete lattice : a partial order in which any family has a supremum (union) and infimum (intersection). Two observations connect to models. First, directly from the definitions: models if and only if , because both say every head with body in is in . Second, is monotone: if , every body in is in . The least fixed-point theorem does the rest.
The proof has three pieces: monotonicity, characterization of models as pre-fixed points, and taking the limit. You will reconstruct it step by step in the guided exercise. The last statement is arithmetic: each productive application adds at least one atom from a finite set. The theorem gives two readings of one object: as what is true (intersection of models) and what is computed (iterate from empty). Data-driven inference iterating is forward chaining.
The canonical example is a graph’s transitive closure. Relation edge is the data (input tables, the EDB) and path is the derived relation (the IDB):
path(X, Y) :- edge(X, Y).
path(X, Z) :- path(X, Y), edge(Y, Z).
Applying from empty first produces paths of length 1 (the base rule copies edge), then those up to length 2, and on application those up to length . Each application evaluates the recursive body as a join of two relations on shared variable Y, followed by projection onto (X, Z). This motivates the figure’s second half: naive evaluation recalculates all earlier joins on every application even though only joins using a newly derived fact can produce new facts.
Counting joins requires fixing what is counted. Here a join is a pair of tuples matching in the recursive body (one tuple of path with one of edge, or two of path, sharing Y’s value); the base rule has no join. Both evaluations also perform the final application confirming nothing new appears. The cell calculates the same as the figure for its three graphs.
from collections import defaultdict
# Grafos de la figura del punto fijo (mismo orden de nodos que el interactivo)
GRAFOS = {
"cadena": [(i, i + 1) for i in range(7)],
"ciclo": [(0, 1), (1, 2), (2, 3), (3, 0), (3, 4), (4, 5), (5, 6), (6, 7)],
"árbol": [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6), (5, 7)],
}
def tp_path(edge, path, regla):
"""Una aplicación de T_P al programa path :- edge ; path :- (cuerpo recursivo).
Devuelve el nuevo conjunto path y el número de joins del cuerpo recursivo."""
nuevo = set(edge) # regla base: path(X,Y) :- edge(X,Y)
joins = 0
segunda = edge if regla == "lineal" else path # path(X,Y), edge(Y,Z) o path(X,Y), path(Y,Z)
sal = defaultdict(list) # índice hash por la columna del join (Y)
for (y, z) in segunda:
sal[y].append(z)
for (x, y) in path:
for z in sal[y]:
joins += 1
nuevo.add((x, z))
return nuevo, joins
def ingenua(edge, regla):
path, nuevos, joins = set(), [], 0
while True:
siguiente, j = tp_path(edge, path, regla)
joins += j
if siguiente == path: # la última aplicación solo confirma
return path, nuevos, joins
nuevos.append(len(siguiente - path))
path = siguiente
def seminaive(edge, regla):
path = set(edge) # primera aplicación: solo la regla base
delta, nuevos, joins = set(edge), [len(edge)], 0
sal_e = defaultdict(list)
for (y, z) in edge:
sal_e[y].append(z)
while delta:
candidatos = set()
if regla == "lineal": # Δpath ⋈ edge
for (x, y) in delta:
for z in sal_e[y]:
joins += 1
candidatos.add((x, z))
else: # Δpath ⋈ path ∪ (path − Δpath) ⋈ Δpath
sal_p, sal_d = defaultdict(list), defaultdict(list)
for (y, z) in path:
sal_p[y].append(z)
for (y, z) in delta:
sal_d[y].append(z)
for (x, y) in delta:
for z in sal_p[y]:
joins += 1
candidatos.add((x, z))
for (x, y) in path - delta: # el par (Δ, Δ) ya está en el primer término
for z in sal_d[y]:
joins += 1
candidatos.add((x, z))
delta = candidatos - path
path |= delta
if delta:
nuevos.append(len(delta))
return path, nuevos, joins
print(f"{'grafo':8s} {'regla':9s} {'|path|':>6s} {'aplic.':>6s} {'joins ingenua':>14s} {'joins seminaive':>16s} nuevos por aplicación")
for nombre, E in GRAFOS.items():
for regla in ("lineal", "no lineal"):
p1, n1, j1 = ingenua(set(E), regla)
p2, n2, j2 = seminaive(set(E), regla)
assert p1 == p2 and n1 == n2 # mismo punto fijo, mismas iteraciones
print(f"{nombre:8s} {regla:9s} {len(p1):6d} {len(n1):6d} {j1:14d} {j2:16d} {n1}")Three things from the table. Both evaluations reach the same fixed point in the same number of applications: assert checks it, and the Datalog section’s theorem guarantees it. Seminaive makes far fewer joins: on the cyclic graph, 35 versus 184 with the linear rule; on the chain, 21 versus 112. With the linear rule, seminaive uses each path fact exactly once as a join’s left endpoint, so its 21 joins on the 8-node chain are the 28 paths minus the 7 ending at the last node, which has no outgoing edge. The nonlinear rule reduces applications and increases work: on the chain it goes from 7 productive applications to 4 because each concatenates two paths and maximum length doubles, but seminaive makes 56 joins instead of 21, because one long path can be obtained by splitting at many intermediate points. In the tree, where the longest path has length 3, both rules need 3 applications. For more work, the nonlinear rule needs logarithmically many applications in longest path length, interesting when each application is distributed across many processors.
Backward chaining: SLD resolution and Prolog
Forward chaining calculates all of . If you only want to know whether a path from 0 to 7 exists, deriving the cyclic graph’s 38 facts is wasteful, and with function symbols is infinite and cannot be calculated completely. The alternative starts from the question: to prove path(0, 7), find a clause with a matching head and turn it into questions from its body. This is Kowalski’s procedural reading, executed by Prolog.
The name means Selective Linear Definite: linear resolution (each step uses the previous query), with the program’s definite clauses and a selection rule. This is goal-directed inference, or backward chaining, by SLD resolution. Unlike the previous lesson’s general resolution, there is no factoring or resolution between derived clauses: search is a tree, not saturation.
The key word is any: the computation rule does not affect which answers exist (computation-rule independence), only the tree’s shape, which can change from finite to infinite. The theorem does not guarantee that a particular search strategy finds successful branches. Prolog fixes two things: the computation rule always selects the leftmost atom, and the tree is traversed depth-first, trying clauses in written order and backtracking on failure. Depth-first uses memory proportional to a branch rather than the whole tree, but makes Prolog incomplete: if an infinite branch is left of a successful one, Prolog descends forever.
Clause order and left recursion
In the figure, the ancestor program with rule anc(X, Y) :- par(X, Z), anc(Z, Y) (right recursion) gives a finite tree with three answers. With anc(X, Y) :- anc(X, Z), par(Z, Y) (left recursion), the SLD tree still contains all three, because completeness does not depend on order; but the first atom of each resolvent is again anc(ana, _) with a fresh variable, and the leftmost branch is infinite. If the recursive rule comes first, Prolog gives no answers. If second, it gives three and then, searching for a fourth, enters the same infinite branch: the query does not terminate despite no more answers. Declaratively the three programs are equivalent; they share . Procedurally they do not.
There are two remedies. The classic one is rewriting: right recursion or accumulators, as in the parser. The systematic one is tabling (SLG, Chen and Warren, 1996, implemented in XSB and now SWI-Prolog): Prolog remembers ongoing calls and their answers, consumes table answers instead of reentering the same call, and thereby terminates on every Datalog program. Fundamentally it is query-directed forward evaluation, the same idea seen with magic sets.
Cut
Cut ! is a predicate that always succeeds and, when executed, discards all choice points created since the predicate containing it was called: alternative clauses of that predicate and pending alternatives of goals to its left in the body. In the tree it prunes siblings to the right of all nodes between call and cut.
max(X, Y, X) :- X >= Y, !. % corte verde: la segunda cláusula comprueba X < Y
max(X, Y, Y) :- X < Y.
max(X, Y, X) :- X >= Y, !. % corte rojo: la segunda cláusula confía en el corte
max(X, Y, Y).
A cut is green if removing it does not change answers, only avoids useless work; it is red if answers depend on it. The red version looks equivalent and saves one comparison, but max(5, 2, 2) succeeds: the first clause’s head does not unify (the third argument would have to be 5), so the cut never executes, and the second clause read alone says the maximum of any pair is the second. The program is correct only when called with a free third argument. This loses the declarative reading: a clause’s meaning depends on which other clauses were tried first and how it was called.
A minimal Prolog interpreter
The interpreter has three parts. The first represents terms (variables as bindable objects, compounds as tuples), unifies with a trail of bound variables to undo on backtracking, and parses a subset of Prolog syntax with operator precedence. Unification is the previous lesson’s without the occurs check, as in Prolog: X = f(X) creates a cyclic term rather than failing, an efficiency choice the ISO standard leaves undefined.
import re
from collections import defaultdict
class Var:
__slots__ = ("nombre", "ref")
def __init__(self, nombre="_"):
self.nombre, self.ref = nombre, None
def __repr__(self):
return self.nombre
def deref(t):
while isinstance(t, Var) and t.ref is not None:
t = t.ref
return t
# compuestos: tuplas (functor, arg1, ..., argn); átomos: str; números: int; listas: ('.', H, T) y '[]'
def lista(xs, cola="[]"):
for x in reversed(xs):
cola = (".", x, cola)
return cola
def mostrar(t):
t = deref(t)
if isinstance(t, tuple):
if t[0] == ".":
xs = []
while isinstance(t, tuple) and t[0] == ".":
xs.append(mostrar(t[1])); t = deref(t[2])
return "[" + ", ".join(xs) + ("" if t == "[]" else "|" + mostrar(t)) + "]"
if len(t) == 3 and t[0] in OPS:
sep = ", " if t[0] == "," else f" {t[0]} "
return mostrar(t[1]) + sep + mostrar(t[2])
return f"{t[0]}(" + ", ".join(mostrar(a) for a in t[1:]) + ")"
return str(t)
def unificar(a, b, trail):
pila = [(a, b)]
while pila:
a, b = pila.pop()
a, b = deref(a), deref(b)
if a is b:
continue
if isinstance(a, Var):
a.ref = b; trail.append(a) # sin comprobación de ocurrencia, como Prolog
elif isinstance(b, Var):
b.ref = a; trail.append(b)
elif isinstance(a, tuple) and isinstance(b, tuple):
if len(a) != len(b) or a[0] != b[0]:
return False
pila.extend(zip(a[1:], b[1:]))
elif a != b:
return False
return True
def deshacer(trail, marca):
while len(trail) > marca:
trail.pop().ref = None
def renombrar(t, m):
t = deref(t)
if isinstance(t, Var):
if t not in m:
m[t] = Var(t.nombre)
return m[t]
if isinstance(t, tuple):
return (t[0],) + tuple(renombrar(a, m) for a in t[1:])
return t
OPS = {":-": (1200, "xfx"), ",": (1000, "xfy"),
"=": (700, "xfx"), "\\=": (700, "xfx"), "is": (700, "xfx"), "<": (700, "xfx"), ">": (700, "xfx"),
"=<": (700, "xfx"), ">=": (700, "xfx"), "=:=": (700, "xfx"), "=\\=": (700, "xfx"),
"+": (500, "yfx"), "-": (500, "yfx"), "*": (400, "yfx"), "//": (400, "yfx"), "mod": (400, "yfx")}
TOKP = re.compile(r"\s*(%[^\n]*|\d+|[A-Z_][A-Za-z0-9_]*|[a-z][A-Za-z0-9_]*|:-|=:=|=\\=|\\=|=<|>=|//|[-+*=<>!()\[\],|.])")
def leer(texto):
toks, pos = [], 0
while pos < len(texto):
m = TOKP.match(texto, pos)
if not m:
if texto[pos:].strip() == "":
break
raise SyntaxError(texto[pos:pos + 20])
pos = m.end()
if not m.group(1).startswith("%"):
toks.append(m.group(1))
i = 0
def termino(maxp, vs): # precedencia de operadores
nonlocal i
izq, prec_izq = primario(vs), 0
while i < len(toks) and toks[i] in OPS:
op = toks[i]; p, tipo = OPS[op]
if p > maxp or (tipo == "xfx" and prec_izq >= p) or (tipo == "yfx" and prec_izq > p):
break
i += 1
der = termino(p if tipo == "xfy" else p - 1, vs)
izq, prec_izq = (op, izq, der), p
return izq
def primario(vs):
nonlocal i
t = toks[i]; i += 1
if t == "(":
x = termino(1200, vs); i += 1; return x
if t == "[":
if toks[i] == "]":
i += 1; return "[]"
xs = [termino(999, vs)]
while toks[i] == ",":
i += 1; xs.append(termino(999, vs))
cola = "[]"
if toks[i] == "|":
i += 1; cola = termino(999, vs)
i += 1
return lista(xs, cola)
if t.isdigit():
return int(t)
if t[0].isupper() or t[0] == "_":
return Var("_") if t == "_" else vs.setdefault(t, Var(t))
if i < len(toks) and toks[i] == "(":
i += 1
args = [termino(999, vs)]
while toks[i] == ",":
i += 1; args.append(termino(999, vs))
i += 1
return (t,) + tuple(args)
return t
clausulas = []
while i < len(toks):
vs = {}
c = termino(1200, vs)
assert toks[i] == ".", f"esperaba un punto en {toks[i]}"
i += 1
clausulas.append((c, vs))
return clausulas
def conjuncion(t):
t = deref(t)
return conjuncion(t[1]) + conjuncion(t[2]) if isinstance(t, tuple) and t[0] == "," else [t]
class Programa:
def __init__(self, texto):
self.db = defaultdict(list)
for c, _ in leer(texto):
cab, cuerpo = (c[1], conjuncion(c[2])) if isinstance(c, tuple) and c[0] == ":-" else (c, [])
clave = (cab[0], len(cab) - 1) if isinstance(cab, tuple) else (cab, 0)
self.db[clave].append((cab, cuerpo))
print(mostrar(leer("anc(X, Y) :- par(X, Z), anc(Z, Y).")[0][0]))
print(mostrar(leer("q([1, 2|T], N - 1 * 2).")[0][0]))The second part is the engine. Instead of Python recursion, which would limit derivation length to the interpreter’s recursion limit (1000 frames by default), it uses an explicit stack of choice points, each storing the goal, remaining clauses to try and trail mark. Backtracking pops the last, undoes the trail to its mark and tries the next clause. Cut fits naturally: each clause-body goal carries as a barrier the stack height at call time, and executing ! truncates the stack to that height.
class LimiteExcedido(Exception):
pass
def evaluar(t):
t = deref(t)
if isinstance(t, int):
return t
if isinstance(t, tuple) and len(t) == 3 and t[0] in ARIT:
return ARIT[t[0]](evaluar(t[1]), evaluar(t[2])) # dividir por cero lanza una excepción, como en Prolog
raise TypeError(f"no es aritmética: {mostrar(t)}")
ARIT = {"+": lambda a, b: a + b, "-": lambda a, b: a - b, "*": lambda a, b: a * b,
"//": lambda a, b: a // b, "mod": lambda a, b: a % b}
COMPARA = {"<": lambda a, b: a < b, ">": lambda a, b: a > b, "=<": lambda a, b: a <= b,
">=": lambda a, b: a >= b, "=:=": lambda a, b: a == b, "=\\=": lambda a, b: a != b}
def resolver(prog, consulta, max_pasos=200_000, max_prof=5_000, stats=None):
"""Regla de cómputo de Prolog (el objetivo de más a la izquierda) y búsqueda en profundidad.
Generador: produce una vez por respuesta. Objetivos: lista enlazada ((término, barrera), resto, longitud)."""
trail, elecciones = [], [] # punto de elección: (objetivo, resto, cláusulas, siguiente, marca, barrera)
objetivos = None
for g in reversed(consulta):
objetivos = ((g, 0), objetivos, 1 + (objetivos[2] if objetivos else 0))
pasos = 0
def probar(objetivo, resto, clausulas, k, barrera):
while k < len(clausulas):
marca = len(trail)
cab, cuerpo = clausulas[k]
m = {}
if unificar(renombrar(cab, m), objetivo, trail):
if k + 1 < len(clausulas): # quedan alternativas: punto de elección
elecciones.append((objetivo, resto, clausulas, k + 1, marca, barrera))
nuevo = resto
for b in reversed(cuerpo): # el cuerpo va delante del resto (pila de objetivos)
nuevo = ((renombrar(b, m), barrera), nuevo, 1 + (nuevo[2] if nuevo else 0))
return nuevo, True
deshacer(trail, marca)
k += 1
return None, False
def retroceder():
while elecciones:
objetivo, resto, clausulas, k, marca, barrera = elecciones.pop()
deshacer(trail, marca)
nuevo, ok = probar(objetivo, resto, clausulas, k, barrera)
if ok:
return nuevo, True
return None, False
ok = True
while True:
if not ok:
objetivos, ok = retroceder()
if not ok:
return
if objetivos is None: # consulta vacía: una respuesta
yield True
ok = False # y se retrocede para buscar la siguiente
continue
pasos += 1
if stats is not None:
stats["pasos"] = pasos
if pasos > max_pasos:
raise LimiteExcedido(f"más de {max_pasos} pasos")
(g, corte), resto, _ = objetivos
g = deref(g)
nombre = g[0] if isinstance(g, tuple) else g
aridad = len(g) - 1 if isinstance(g, tuple) else 0
if g == "true":
objetivos = resto
elif g == "fail":
ok = False
elif g == "!":
del elecciones[corte:] # el corte: fuera los puntos de elección desde la llamada
objetivos = resto
elif nombre == "=" and aridad == 2:
marca = len(trail)
ok = unificar(g[1], g[2], trail)
if not ok:
deshacer(trail, marca)
objetivos = resto
elif nombre == "\\=" and aridad == 2:
marca = len(trail)
ok = not unificar(g[1], g[2], trail)
deshacer(trail, marca)
objetivos = resto
elif nombre == "is" and aridad == 2:
ok = unificar(g[1], evaluar(g[2]), trail)
objetivos = resto
elif nombre in COMPARA and aridad == 2:
ok = COMPARA[nombre](evaluar(g[1]), evaluar(g[2]))
objetivos = resto
elif nombre == "number" and aridad == 1:
ok = isinstance(deref(g[1]), int)
objetivos = resto
else: # predicado del programa: un paso SLD
clausulas = prog.db.get((nombre, aridad), [])
objetivos, ok = probar(g, resto, clausulas, 0, len(elecciones))
if ok and objetivos is not None and objetivos[2] > max_prof:
raise LimiteExcedido(f"más de {max_prof} objetivos pendientes")
def consultar(prog, texto, maximo=10, **kw):
[(q, vs)] = leer(texto if texto.strip().endswith(".") else texto + ".")
salida = []
for _ in resolver(prog, conjuncion(q), **kw):
salida.append({k: mostrar(v) for k, v in vs.items() if not k.startswith("_")})
if len(salida) >= maximo:
break
return salida
print(consultar(Programa("p(1). p(2). q(2)."), "p(X), q(X)"))Now the figure’s programs and two classics. append shows reversibility: the same relation concatenates lists or splits them depending on which arguments are free. N queens uses select/3 to generate and incremental diagonal checks to prune, the constraint satisfaction lesson’s backtracking pattern written in four clauses.
P = Programa("""
append([], L, L).
append([H|T], L, [H|R]) :- append(T, L, R).
par(ana, bea). par(bea, carlos). par(carlos, dora).
anc(X, Y) :- par(X, Y).
anc(X, Y) :- par(X, Z), anc(Z, Y).
anc_izq(X, Y) :- anc_izq(X, Z), par(Z, Y).
anc_izq(X, Y) :- par(X, Y).
max_verde(X, Y, X) :- X >= Y, !.
max_verde(X, Y, Y) :- X < Y.
max_rojo(X, Y, X) :- X >= Y, !.
max_rojo(X, Y, Y).
""")
print("append(X, Y, [1, 2, 3]):")
for r in consultar(P, "append(X, Y, [1, 2, 3])"):
print(" ", r)
print("anc(ana, Q):", [r["Q"] for r in consultar(P, "anc(ana, Q)")])
try:
consultar(P, "anc_izq(ana, Q)", max_pasos=20_000)
except LimiteExcedido as e:
print("anc_izq(ana, Q):", e, "sin producir ninguna respuesta")
print("max_verde(5, 2, M):", consultar(P, "max_verde(5, 2, M)"), " max_rojo(5, 2, M):", consultar(P, "max_rojo(5, 2, M)"))
print("max_verde(5, 2, 2):", bool(consultar(P, "max_verde(5, 2, 2)")), " max_rojo(5, 2, 2):", bool(consultar(P, "max_rojo(5, 2, 2)")))
REINAS = Programa("""
queens(N, Qs) :- range(1, N, Ns), place(Ns, [], Qs).
place([], Qs, Qs).
place(Unplaced, Safe, Qs) :- select(Q, Unplaced, R), safe(Q, 1, Safe), place(R, [Q|Safe], Qs).
safe(_, _, []).
safe(Q, D, [Q1|Qs]) :- Q =\\= Q1 + D, Q =\\= Q1 - D, D1 is D + 1, safe(Q, D1, Qs).
select(X, [X|T], T).
select(X, [H|T], [H|R]) :- select(X, T, R).
range(N, N, [N]) :- !.
range(M, N, [M|Ns]) :- M < N, M1 is M + 1, range(M1, N, Ns).
""")
for n in (4, 6):
st = {}
sols = consultar(REINAS, f"queens({n}, Qs)", maximo=1000, stats=st)
print(f"{n} reinas: {len(sols)} soluciones, {st['pasos']} pasos; la primera: {sols[0]['Qs']}")
st = {}
print("8 reinas, primera solución:", consultar(REINAS, "queens(8, Qs)", maximo=1, stats=st)[0]["Qs"], f"({st['pasos']} pasos)")Output confirms the tree. append(X, Y, [1, 2, 3]) gives four partitions. anc(ana, Q) gives bea, carlos and dora; the left-recursive version accumulates over 5000 pending goals without one answer (the limit only makes the cell terminate). With red cut, max_rojo(5, 2, 2) succeeds and max_verde(5, 2, 2) does not. Six queens have 4 solutions, all found in 3662 resolution steps (counting built-ins such as is); the first 8-queens solution takes 4335 steps. Notice the cut in range/3: green with respect to answers, but without it, on requesting more answers Prolog would try the second clause with M = N and fail at M < N after a useless step.
Difference lists and a parser
A difference list represents a sequence as a pair of lists S0 and S where S is a suffix of S0: the sequence is what S0 has before S. Predicate expr(V, S0, S) reads “between S0 and S is an expression worth V”, and concatenating fragments costs nothing: one fragment’s S1 is the next one’s S0. This is exactly what Prolog’s DCG notation generates: it writes expr(V) --> term(T), expr_rest(T, V). and adds two hidden arguments when compiling.
The natural subtraction grammar, expr --> expr, [minus], term, is left-recursive and, as seen, does not terminate. Standard rewriting uses an accumulator (expr_rest) that also gives correct associativity: , not .
EXPR = Programa("""
expr(V, S0, S) :- term(T, S0, S1), expr_rest(T, V, S1, S).
expr_rest(Acc, V, [plus|S0], S) :- term(T, S0, S1), A1 is Acc + T, expr_rest(A1, V, S1, S).
expr_rest(Acc, V, [minus|S0], S) :- term(T, S0, S1), A1 is Acc - T, expr_rest(A1, V, S1, S).
expr_rest(V, V, S, S).
term(V, S0, S) :- factor(F, S0, S1), term_rest(F, V, S1, S).
term_rest(Acc, V, [times|S0], S) :- factor(F, S0, S1), A1 is Acc * F, term_rest(A1, V, S1, S).
term_rest(V, V, S, S).
factor(V, [N|S], S) :- number(N), V = N.
factor(V, [lp|S0], S) :- expr(V, S0, [rp|S]).
expr_izq(V, S0, S) :- expr_izq(A, S0, [minus|S1]), term(T, S1, S), V is A - T.
expr_izq(V, S0, S) :- term(V, S0, S).
""")
for frase in ["[2, times, lp, 3, plus, 4, rp, minus, 5]", "[10, minus, 4, minus, 3]", "[2, plus, times, 3]"]:
r = consultar(EXPR, f"expr(V, {frase}, [])")
print(f"{frase:42s} ->", r[0]["V"] if r else "no es una expresión")
# con S libre, la lista de diferencias devuelve qué prefijos de la entrada son expresiones
print("prefijos de [1, plus, 2, times, 3]:", [(r["V"], r["S"]) for r in consultar(EXPR, "expr(V, [1, plus, 2, times, 3], S)")])
try:
consultar(EXPR, "expr_izq(V, [10, minus, 4, minus, 3], [])", max_pasos=20_000)
except LimiteExcedido as e:
print("versión recursiva por la izquierda:", e)The parser evaluates and , and rejects 2 + * 3. The query with free S shows the purpose of the difference: it returns the three prefixes that are expressions (1 + 2 * 3 with value 7, 1 + 2 with value 3 and 1), each with its unconsumed remainder. The left-recursive version again accumulates goals endlessly.
Negation as failure, closed world and Clark completion
Definite clauses cannot say something is false: all of is always a model, so no negative literal follows from a definite program. But in a database, if the table has no flight from Madrid to Ulaanbaatar, the answer is confidently “no”. This convention has two formulations.
Two consequences are immediate. First, nonmonotonicity: with vuela(X) :- ave(X), not pinguino(X) and fact ave(tux) one derives vuela(tux); adding pinguino(tux) removes that conclusion. In classical logic, adding premises never removes conclusions. Second, not A only makes sense with A ground: not par(X, dora) with free X asks whether no X exists, not which X fail the relation, and Prolog answers the first question. This is floundering, avoided by the safety condition your Datalog engine imposes: every variable in a negative literal must occur in a positive literal of the same body, binding it before negation.
What does a normal program mean declaratively? Clark’s first answer (1978): a program enumerates reasons something is true, and negation as failure assumes there are no more reasons. Clark completion turns each predicate’s implications into an equivalence. For a propositional program,
with not read as and if heads no rule; in first order, arguments are equated to fresh variables and body-local variables existentially quantified, and Clark’s equality axioms (distinct terms differ) are added. Clark proved SLDNF sound with respect to : if not A succeeds, . Definite programs also have finite-failure completeness (Jaffar, Lassez and Lloyd, 1983): if , the SLD tree of with a fair computation rule is finite and unsuccessful.
Completion has two defects addressed by the ASP section. It can be inconsistent: p :- not p gives , which has no models. And it is too permissive with positive cycles: p :- q. q :- p. gives , , with two models, and . The second says and are true because they justify one another, which no programmer intended; the least model is the correct reading.
Datalog: bottom-up evaluation, stratification and magic sets
Datalog is logic programming without function symbols, with two database conventions: predicates are split into extensional (EDB, input tables appearing in no head) and intensional (IDB, rule-defined), and every rule is safe. It is always evaluated bottom-up, like , but without applying the operator blindly.
For path’s linear rule there is only one recursive atom and the formula is . For the nonlinear rule there are two: term is and is , so each (delta, delta) pair is combined once, in the second. The opening cell uses the symmetric convention , which also combines it once.
Proof
By induction on : suppose both evaluations coincide through iteration , with . Every fact seminaive adds at iteration is also added by naive evaluation, since it comes from a rule instance with body in (versions and are contained in ). Conversely, let be derived by an instance with body in . If no recursive body atom were in , all would be in (EDBs do not change) and would already be in . Let be the last recursive position whose fact is in . Positions before have facts in , position in and later positions in : exactly the versions in term , which produces .
∎The savings are exactly what the figure measured: naive iteration rediscovers all derivations from the preceding . With linear rules, seminaive performs each derivation once.
Each term is a sequence of hash joins. The engine evaluates the body left to right maintaining partial substitutions; for the next atom it builds a hash table of the relation indexed by columns whose variables are already bound, and for each substitution traverses only its key’s list. Choosing atom order and indexes is the query optimizer’s job; the Doop paper devotes much of its optimization section to reordering variables and adding intermediate relations so seminaive deltas bind every indexed column of large relations.
Stratified negation
With negation, stops being monotone: adding facts can make not false and remove consequences. Datalog’s solution requires never negating something still being computed.
Stratification is calculated from the graph’s strongly connected components: the program is stratifiable if and only if no negative edge connects two predicates in the same component, and a topological order of the component graph gives a valid evaluation order. Within a stratum all negations refer to lower, already complete strata, and evaluation is monotone again. Apt, Blair and Walker (1988) proved the result independent of the chosen stratification and a minimal model of the program; Przymusinski (1988) characterized it as its perfect model.
What if it is not stratifiable? The classic example is games: win(X) :- move(X, Y), not win(Y) (“I win from X if I can move to a losing position for the opponent”). win depends negatively on itself. Evaluating rule by rule from facts derived so far would make the result order-dependent, as the second part of the cell below shows.
Magic sets on one page
Bottom-up evaluation computes all even when the query is path(0, Y). Magic sets (Bancilhon, Maier, Sagiv and Ullman, 1986; Beeri and Ramakrishnan, 1991) rewrite the program so bottom-up evaluation touches only what top-down evaluation would. For the right-recursive rule and a query with first argument bound, add predicate m_path collecting values with which path would be called, and filter each rule with it:
m_path(0). % la consulta: path se llama con X = 0
m_path(Y) :- m_path(X), edge(X, Y). % la regla recursiva llama a path con Y
path(X, Y) :- m_path(X), edge(X, Y).
path(X, Z) :- m_path(X), edge(X, Y), path(Y, Z).
The rewritten program has the same answers to the query and generally a much smaller least model. This is the information Prolog propagates with calls, calculated with bottom-up evaluation’s efficiency and termination; the previous section’s tabling arrives from the other side.
A seminaive Datalog engine
The engine has three parts: a rule parser checking safety, stratification using Tarjan’s algorithm, and seminaive evaluation by strata with hash joins. Each tuple matching a partial substitution from the body’s second literal onward counts as a join, the same count as the first cell for transitive closure.
import re
from collections import defaultdict
TOK = re.compile(r"\s*(:-|not\b|[A-Za-z_][A-Za-z0-9_]*|\d+|[(),.])")
def _tokens(txt):
txt = re.sub(r"%[^\n]*", "", txt)
pos, out = 0, []
while pos < len(txt):
m = TOK.match(txt, pos)
if not m:
if txt[pos:].strip() == "":
break
raise SyntaxError(f"no entiendo: {txt[pos:pos + 20]!r}")
out.append(m.group(1))
pos = m.end()
return out
def es_var(t):
return isinstance(t, str) and (t[0].isupper() or t[0] == "_")
def parse(txt):
"""Lista de reglas (cabeza, cuerpo); cuerpo = [(positivo, (pred, args))]."""
tk, i, reglas = _tokens(txt), 0, []
def atomo():
nonlocal i
pred = tk[i]; i += 1
args = []
if i < len(tk) and tk[i] == "(":
i += 1
while tk[i] != ")":
a = tk[i]; i += 1
args.append(int(a) if a.isdigit() else a)
if tk[i] == ",":
i += 1
i += 1
return (pred, tuple(args))
while i < len(tk):
cab = atomo()
cuerpo = []
if tk[i] == ":-":
i += 1
while True:
pos = True
if tk[i] == "not":
pos = False; i += 1
cuerpo.append((pos, atomo()))
if tk[i] == ",":
i += 1; continue
break
assert tk[i] == ".", f"falta el punto tras {cab}"
i += 1
# seguridad: las variables de la cabeza y de los literales negativos, ligadas por uno positivo
ligadas = {a for p, (_, args) in cuerpo if p for a in args if es_var(a)}
libres = {a for a in cab[1] if es_var(a)} | {a for p, (_, args) in cuerpo if not p for a in args if es_var(a)}
if libres - ligadas:
raise ValueError(f"regla insegura {cab}: variables {sorted(libres - ligadas)} sin ligar")
reglas.append((cab, cuerpo))
return reglas
def estratos(reglas):
"""Componentes fuertemente conexas (Tarjan) del grafo de dependencias, dependencias primero."""
preds = {c[0] for c, _ in reglas}
aristas = defaultdict(set)
for (cp, _), cuerpo in reglas:
for pos, (q, _) in cuerpo:
if q in preds:
aristas[cp].add((q, pos))
indice, bajo, pila, en_pila, comps, cont = {}, {}, [], set(), [], [0]
def tarjan(v):
indice[v] = bajo[v] = cont[0]; cont[0] += 1
pila.append(v); en_pila.add(v)
for w, _ in aristas[v]:
if w not in indice:
tarjan(w); bajo[v] = min(bajo[v], bajo[w])
elif w in en_pila:
bajo[v] = min(bajo[v], indice[w])
if bajo[v] == indice[v]:
comp = set()
while True:
w = pila.pop(); en_pila.discard(w); comp.add(w)
if w == v:
break
comps.append(comp)
for p in sorted(preds):
if p not in indice:
tarjan(p)
for comp in comps: # Tarjan emite las componentes en orden topológico inverso
for p in comp:
for q, pos in aristas[p]:
if not pos and q in comp:
raise ValueError(f"no estratificable: {p} depende negativamente de {q} dentro de un ciclo {sorted(comp)}")
return comps
class Motor:
def __init__(self, reglas, edb):
self.reglas = reglas
self.rel = defaultdict(set, {k: set(v) for k, v in edb.items()})
self.joins = 0 # tuplas que encajan en un join (literal k > 0)
self.iteraciones = [] # hechos nuevos por iteración, estrato tras estrato
def _cuerpo(self, cuerpo, fuentes):
sustituciones = [{}]
for k, (pos, (pred, args)) in enumerate(cuerpo):
if not pos: # negación: su estrato ya está completo
rel = self.rel[pred]
sustituciones = [s for s in sustituciones if tuple(s.get(a, a) for a in args) not in rel]
continue
if not sustituciones:
return []
ligadas = [j for j, a in enumerate(args) if not es_var(a) or a in sustituciones[0]]
idx = defaultdict(list) # join hash: índice por las columnas ya ligadas
for t in fuentes[k]:
idx[tuple(t[j] for j in ligadas)].append(t)
nuevas = []
for s in sustituciones:
for t in idx.get(tuple(s.get(args[j], args[j]) for j in ligadas), ()):
s2, ok = dict(s), True
for a, v in zip(args, t):
if es_var(a) and s2.setdefault(a, v) != v:
ok = False; break
if ok:
if k > 0:
self.joins += 1
nuevas.append(s2)
sustituciones = nuevas
return sustituciones
def _disparar(self, regla, fuentes):
(hp, hargs), cuerpo = regla
return {tuple(s.get(a, a) for a in hargs) for s in self._cuerpo(cuerpo, fuentes)}
def ejecutar(self, seminaive=True):
for comp in estratos(self.reglas):
reglas = [r for r in self.reglas if r[0][0] in comp]
delta = defaultdict(set) # primera iteración del estrato: relaciones completas
for r in reglas:
delta[r[0][0]] |= self._disparar(r, [self.rel[a[0]] for _, a in r[1]]) - self.rel[r[0][0]]
for p, d in delta.items():
self.rel[p] |= d
self.iteraciones.append(sum(map(len, delta.values())))
while any(delta.values()):
nuevo = defaultdict(set)
for r in reglas:
if not seminaive:
nuevo[r[0][0]] |= self._disparar(r, [self.rel[a[0]] for _, a in r[1]])
continue
rec = [k for k, (pos, a) in enumerate(r[1]) if pos and a[0] in comp]
for k in rec: # un literal recursivo desde el delta; el resto, completos
fuentes = [delta[a[0]] if j == k else self.rel[a[0]] for j, (_, a) in enumerate(r[1])]
nuevo[r[0][0]] |= self._disparar(r, fuentes)
delta = defaultdict(set, {p: s - self.rel[p] for p, s in nuevo.items()})
for p, d in delta.items():
self.rel[p] |= d
if any(delta.values()):
self.iteraciones.append(sum(map(len, delta.values())))
return self.rel
E = {(0, 1), (1, 2), (2, 3), (3, 0), (3, 4), (4, 5), (5, 6), (6, 7)} # el grafo con ciclo de la figura
TC = parse("""
path(X, Y) :- edge(X, Y).
path(X, Z) :- path(X, Y), edge(Y, Z).
""")
for modo in (False, True):
m = Motor(TC, {"edge": E})
m.ejecutar(seminaive=modo)
print("seminaive" if modo else "ingenua ", "|path| =", len(m.rel["path"]), " joins =", m.joins, " nuevos por iteración:", m.iteraciones)The general engine reproduces the first cell’s cyclic-graph numbers (38 facts; 184 naive joins and 35 seminaive). For simplicity it uses full version in all non-delta positions instead of on the right: with nonlinear rules it counts (delta, delta) pairs twice, without affecting the result because relations are sets.
import random, time
# 0) Negación estratificada sobre un predicado IDB: alcanzable se calcula entero antes de negarlo.
ALC = parse("""
alcanzable(X) :- origen(X).
alcanzable(Y) :- alcanzable(X), arista(X, Y).
aislado(X) :- nodo(X), not alcanzable(X).
""")
print("estratos, en orden de evaluación:", [sorted(c) for c in estratos(ALC)])
m = Motor(ALC, {"origen": {("a",)}, "arista": {("a", "b"), ("b", "c"), ("d", "e")},
"nodo": {(x,) for x in "abcde"}})
print("aislados:", sorted(x for (x,) in m.ejecutar()["aislado"]))
# 1) Un programa no estratificable: el motor lo rechaza.
JUEGO = parse("win(X) :- move(X, Y), not win(Y).")
try:
estratos(JUEGO)
except ValueError as e:
print("rechazado:", e)
# ¿Qué pasaría si lo evaluáramos igualmente, nodo a nodo y en algún orden?
def evaluar_en_orden(moves, orden):
win = set()
for x in orden: # cada nodo, una vez, mirando lo derivado hasta ahora
if any(y not in win for (a, y) in moves if a == x):
win.add(x)
return win
MOVES = {("a", "b"), ("b", "a"), ("b", "c")}
print("orden a, b, c:", sorted(evaluar_en_orden(MOVES, "abc")))
print("orden b, a, c:", sorted(evaluar_en_orden(MOVES, "bac")))
# 2) Magic sets: la consulta path(0, Y) en un grafo con una componente pequeña y otra grande.
rnd = random.Random(7)
edges = {(i, i + 1) for i in range(0, 9)} # componente de la consulta: 0..9
grandes = list(range(100, 260))
edges |= {(rnd.choice(grandes), rnd.choice(grandes)) for _ in range(320)}
TC_R = parse("""
path(X, Y) :- edge(X, Y).
path(X, Z) :- edge(X, Y), path(Y, Z).
""")
MAGIA = parse("""
m_path(Y) :- m_path(X), edge(X, Y).
path(X, Y) :- m_path(X), edge(X, Y).
path(X, Z) :- m_path(X), edge(X, Y), path(Y, Z).
""")
for nombre, prog, edb in [("completo", TC_R, {"edge": edges}),
("magic sets", MAGIA, {"edge": edges, "m_path": {(0,)}})]:
t0 = time.perf_counter()
m = Motor(prog, edb)
rel = m.ejecutar()
resp = sorted(y for (x, y) in rel["path"] if x == 0)
print(f"{nombre:10s}: |path| = {len(rel['path']):6d} joins = {m.joins:7d} respuestas a path(0, Y): {len(resp)}"
f" ({time.perf_counter() - t0:.2f} s)")In the first program, Tarjan returns the alcanzable component first and aislado second, so alcanzable is complete when not is evaluated, and isolated nodes are d and e, unreachable from a. The engine rejects the game, because win depends negatively on itself within its component. Correctly: evaluation in order a, b, c says a and b win; order b, a, c gives only b. The latter is correct (from c there are no moves, so whoever is at c loses; from b one can move to c, so b wins; from a one can only move to b, winning for the opponent). ASP gives order-independent semantics obtaining it. Magic sets answer path(0, Y) with the same 9 answers deriving 45 path facts and making 144 joins, versus 16,813 facts and 33,523 joins for complete evaluation, which computes the large component’s closure even though the query never reaches it.
Datalog for program analysis
Static analysis reasons about all executions of a program at once. Almost all classic analyses are fundamentally relation closures: which definitions reach a use, which objects a variable may point to, which inputs reach which calls. Datalog expresses them directly. The pattern is always the same: an extractor traverses code and dumps facts (assignments, calls, fields) into EDB relations; rules define the analysis; seminaive evaluation computes it; and queries over IDB relations are findings.
Andersen’s points-to analysis
Andersen’s analysis (1994) calculates, for each variable, the set of memory allocation sites (new) it may point to, ignoring statement order (flow-insensitive) and where each function was called from (context-insensitive). Four statement types suffice for the core of an object language:
| Statement | EDB fact | Rule |
|---|---|---|
v = new C() at site o | alloc(v, o) | pt(V, O) :- alloc(V, O). |
v = w | assign(v, w) | pt(V, O) :- assign(V, W), pt(W, O). |
v.f = w | store(v, f, w) | hpt(O, F, P) :- store(V, F, W), pt(V, O), pt(W, P). |
v = w.f | load(v, w, f) | pt(V, P) :- load(V, W, F), pt(W, O), hpt(O, F, P). |
pt (points-to) says which objects a variable points to, and hpt which objects field f of an object points to. The two are mutually recursive, making Datalog natural: writing the same analysis by hand with worklists requires manually managing what to reprocess when a set grows, exactly what seminaive does. The first two rules in the Doop paper are literally the table’s first two rows, with VarPointsTo instead of pt.
# 1: a = new Conexion() (objeto o1)
# 2: b = new Consulta() (objeto o2)
# 3: c = a
# 4: c.q = b (escritura de campo)
# 5: d = a.q (lectura de campo)
# 6: e = new Consulta() (objeto o3)
# 7: if (...) c = e
# 8: f = c.q
EDB_PT = {
"alloc": {("a", "o1"), ("b", "o2"), ("e", "o3")},
"assign": {("c", "a"), ("c", "e")}, # assign(Destino, Origen)
"store": {("c", "q", "b")}, # store(Base, Campo, Origen): Base.Campo = Origen
"load": {("d", "a", "q"), ("f", "c", "q")}, # load(Destino, Base, Campo): Destino = Base.Campo
}
ANDERSEN = parse("""
pt(V, O) :- alloc(V, O).
pt(V, O) :- assign(V, W), pt(W, O).
hpt(O, F, P) :- store(V, F, W), pt(V, O), pt(W, P).
pt(V, P) :- load(V, W, F), pt(W, O), hpt(O, F, P).
""")
m = Motor(ANDERSEN, EDB_PT)
rel = m.ejecutar()
pts = defaultdict(set)
for v, o in rel["pt"]:
pts[v].add(o)
for v in sorted(pts):
print(f"pt({v}) = {sorted(pts[v])}")
print("campos del montón:", sorted(rel["hpt"]))
print("iteraciones con hechos nuevos:", len(m.iteraciones), " joins:", m.joins)The result has flow insensitivity’s benefit and drawback. Benefit: pt(d) = [o2], because the analysis discovers c and a are aliases (both point to o1) and the write through c on line 4 is visible to the read through a on line 5. Drawback: hpt contains (o3, q, o2) because the analysis believes c may already point to o3 on line 4, although c = e occurs only on line 7. This is imprecision, not unsoundness: the analysis overapproximates (everything that may happen is in the result, plus some that cannot). Doop’s flow- or context-sensitive analyses refine exactly this by adding arguments to relations: call context or receiver object, represented in the paper with its variable-tuple extension.
Taint: from inputs to queries
Taint analysis finds injections: client-controlled data (a source, such as an HTTP parameter) reaches a dangerous operation (a sink, such as the string passed to db.execute) without cleaning. In between may be sanitizers, functions making data safe for a specific sink class: escape_html neutralizes HTML but not SQL quotes, and int() leaves something that cannot contain code in either. With a data-flow graph flow(V, W) (“V’s value reaches W”), the analysis fits in three rules:
taint(S, S, K) :- source(S), kind(K).
taint(S, W, K) :- taint(S, V, K), flow(V, W), not sanitizes(W, K).
alert(S, T, K) :- taint(S, T, K), sink(T, K).
taint(S, W, K) says node W carries data from source S not cleaned for class K. Negation is stratified (sanitizes is EDB), and storing the source in the fact permits reporting the full path. The figure’s graph is a toy web application with three handlers; the next cell evaluates it with the engine.
# buscar: q = req.args["q"]; term = q.strip()
# sql1 = "... LIKE '" + term + "'" + cfg ; db.execute(sql1) html1 = "<h1>" + term ; render(html1)
# perfil: uid = req.args["id"]; n = int(uid); sql2 = "... id=" + str(n); db.execute(sql2)
# comentar: txt = req.form["texto"]; c2 = escape_html(txt); sql3 = "INSERT ... '" + c2 + "'"
# db.execute(sql3); render(c2)
EDB_TAINT = {
"source": {("q",), ("uid",), ("txt",)},
"kind": {("sql",), ("html",)},
"flow": {("q", "term"), ("term", "sql1"), ("cfg", "sql1"), ("sql1", "exec1"),
("term", "html1"), ("html1", "render1"),
("uid", "n"), ("n", "sql2"), ("sql2", "exec2"),
("txt", "c2"), ("c2", "sql3"), ("sql3", "exec3"), ("c2", "render3")},
"sink": {("exec1", "sql"), ("exec2", "sql"), ("exec3", "sql"),
("render1", "html"), ("render3", "html")},
"sanitizes": {("n", "sql"), ("n", "html"), ("c2", "html")}, # int() limpia para los dos; escape_html, solo HTML
}
TAINT = parse("""
taint(S, S, K) :- source(S), kind(K).
taint(S, W, K) :- taint(S, V, K), flow(V, W), not sanitizes(W, K).
alert(S, T, K) :- taint(S, T, K), sink(T, K).
""")
def hallazgos(edb):
m = Motor(TAINT, edb)
rel = m.ejecutar()
return sorted(rel["alert"]), len(rel["taint"]), m.iteraciones
alertas, n_taint, its = hallazgos(EDB_TAINT)
print("hechos taint:", n_taint, " nuevos por iteración (taint, y al final alert):", its)
for a in alertas:
print(" ALERTA", a)
arreglo = {k: set(v) for k, v in EDB_TAINT.items()}
arreglo["sink"].discard(("exec3", "sql")) # consulta parametrizada: el texto ya no es código SQL
print("\ncon la consulta de comentar parametrizada:", hallazgos(arreglo)[0])
mal = {k: set(v) for k, v in EDB_TAINT.items()}
mal["sanitizes"].add(("term", "html")) # escapar HTML en term no arregla la inyección SQL
print("escapando HTML en term: ", hallazgos(mal)[0])There are 20 taint facts in 4 iterations with new facts (6 from sources, one per source and class, then 3, 6 and 5) and three alerts. Two are expected in buscar: parameter q reaches both query and HTML uncleaned. The third is instructive: in comentar, escape_html cleans text for the HTML sink, but not SQL, and the analysis detects this because sanitizers carry their class. Modeling the sanitizer without a class, merely “clean”, would remove that injection from the report: a false negative. perfil has no alert because int() cuts both paths, and settings.TABLA, which also reaches sql1, is not a source. The correct fix for comentar is a parameterized query, not another sanitizer: data travels as a parameter and is never interpreted as SQL, so exec3 stops being a sink. Escaping HTML in term, by contrast, only removes buscar’s HTML alert and leaves SQL.
CodeQL, Doop and Soufflé
Real systems use the same pattern at scale. In CodeQL, an extractor builds a relational database with the program’s syntax tree, control flow and data flow; queries use QL, a logic language with classes and methods compiled to Datalog (Avgustinov and colleagues, 2016), and data-flow libraries offer the taint pattern with sources, sinks and sanitizers (barriers in recent terminology) defined by the query author as predicates. Doop expresses complete Java pointer analysis, including call-graph construction mutually recursive with points-to, in under 2500 lines of Datalog (about 180 rules); its advantage over Paddle comes not from a different algorithm (both compute exactly the same relation) but explicit indexed relations instead of BDDs, and rule optimization around seminaive deltas. Soufflé takes the idea further: it specializes the seminaive evaluator for each program and generates parallel C++, and is used in Java security analysis at Oracle Labs.
Datalog does not solve analysis design: memory abstraction, degree of context sensitivity, or library and reflection models. But it separates that declarative design from efficient execution by the engine.
Answer Set Programming
Return to the unstratifiable game. The question is which atom sets reasonably represent “what the program says” when cycles contain negation. Gelfond and Lifschitz answer with a consistency test: guess a set ; use it to decide every not; if what is then derived is exactly , the assumption supports itself.
The three negation-section examples become:
p :- not q. q :- not p.has two stable models. With , the second rule is deleted (it hasnot pand ), the first becomesp.and the least model is . Symmetrically, . But deletes both rules and its reduct derives , and retains both as facts and derives .p :- not p.has none: with the reduct isp., deriving ; with the rule is deleted and derived.p :- q. q :- p.has one, : the reduct is the program itself and its least model is empty, so is not stable even though it models the completion. Stable models require every atom to have a justification not depending on itself.
Four properties organize the picture; the first two can be proved in three lines.
Proof
We prove it is a model and part 2. Let . If a rule of has a body true in , no not b has , so the rule is in with its positive literals in ; since models , the head is in . Thus is a model. For support, if , fixed-point semantics derives at some application of with a rule of whose positive body is in ; the original rule was not deleted, so its not b have and its full body is true in . That is completion condition .
Part 3 says ASP extends Datalog with stratified negation: on programs Datalog accepts, it gives the same answer. The earlier game, rejected by Datalog, has one stable model , the correct answer; the cell checks it. Part 4 explains the difference between completion and stable models: it appears only with positive cycles such as p :- q. q :- p., so clingo needs more than completion.
The price is complexity: deciding whether a ground normal program has any stable model is NP-complete (Marek and Truszczyński, 1991), and disjunctions in heads raise it to (Eiter and Gottlob, 1995). ASP is therefore a language for search problems, reflected in its programming style.
Generate, define, test
Writing two rules p :- not q. q :- not p. for every possible choice would be tedious. ASP languages have syntactic sugar:
- Choice rules.
{ a; b; c }.allows any subset of{a, b, c}to be true;1 { color(X, C) : col(C) } 1 :- node(X).requires exactly one color per node. They translate to normal rules with auxiliary atoms. - Integrity constraints.
:- cuerpo.equalsf :- cuerpo, not f.with freshf: the only way to avoidf’s paradox is for the body to be false. - Aggregates and optimization.
#count,#sumin bodies and constraints, and#minimize { coste, X : ... }to retain optimal stable models.
With these, an ASP program almost always follows the generate, define, test pattern described by Lifschitz (2002) for planning: one part generates candidates with choice rules, one defines auxiliary concepts with normal rules (including recursion: reachability, closures, induction over time), and one checks integrity constraints. Definition distinguishes ASP from SAT and CP-SAT: defining “X is reachable from Y” in SAT requires manually encoding transitive closure with auxiliary order variables; in ASP it is the two path rules, and stable-model semantics prevents unjustified reachability.
Before clingo, the core from scratch: reduct, least model, brute-force stable-model enumeration and, for comparison, completion-model enumeration.
import itertools, re
ATOMO = r"[a-z]\w*(?:\([^()]*\))?"
def leer_asp(texto):
"""Programa normal cerrado: reglas «h :- b1, not b2.», hechos «h.» y restricciones «:- b1, not b2.»
Cada regla es (cabeza o None, positivos, negativos)."""
reglas = []
for r in re.split(r"\.(?=\s|$)", re.sub(r"%[^\n]*", "", texto)):
r = r.strip()
if not r:
continue
cab, _, cuerpo = r.partition(":-")
pos, neg = set(), set()
for lit in re.findall(r"(not\s+)?(" + ATOMO + ")", cuerpo):
(neg if lit[0] else pos).add(lit[1])
reglas.append((cab.strip() or None, frozenset(pos), frozenset(neg)))
return reglas
def atomos(P):
return sorted({a for h, p, n in P for a in ([h] if h else []) + list(p) + list(n)})
def reducto(P, M):
"""Gelfond-Lifschitz: borra las reglas con algún «not b» y b en M; quita los «not» del resto."""
return [(h, p) for h, p, n in P if not (n & M)]
def modelo_minimo(definido):
"""Encadenamiento hacia delante; None si el cuerpo de una restricción se hace verdadero."""
M, cambio = set(), True
while cambio:
cambio = False
for h, p in definido:
if p <= M:
if h is None:
return None
if h not in M:
M.add(h); cambio = True
return M
def es_estable(P, M):
return modelo_minimo(reducto(P, M)) == set(M)
def modelos_estables(P):
A = atomos(P)
return [set(c) for k in range(len(A) + 1) for c in itertools.combinations(A, k) if es_estable(P, set(c))]
def modelos_completado(P):
"""Modelos soportados: M satisface las reglas y cada átomo de M tiene una regla con el cuerpo verdadero."""
A, sal = atomos(P), []
for k in range(len(A) + 1):
for c in itertools.combinations(A, k):
M = set(c)
cierto = lambda p, n: p <= M and not (n & M)
if all(not cierto(p, n) or (h is not None and h in M) for h, p, n in P) and \
all(any(h == a and cierto(p, n) for h, p, n in P) for a in M):
sal.append(M)
return sal
EJEMPLOS = {
"p :- not q. q :- not p.": "p :- not q.\nq :- not p.",
"p :- not p.": "p :- not p.",
"p :- q. q :- p.": "p :- q.\nq :- p.",
"p :- not q. q :- not p. :- p.": "p :- not q.\nq :- not p.\n:- p.",
"juego a<->b, b->c": "win(a) :- not win(b).\nwin(b) :- not win(a).\nwin(b) :- not win(c).",
}
for nombre, txt in EJEMPLOS.items():
P = leer_asp(txt)
print(f"{nombre:32s} estables: {[sorted(m) for m in modelos_estables(P)]} completado: {[sorted(m) for m in modelos_completado(P)]}")
# Tres colores para un triángulo: generar con bucles pares de negación, comprobar con restricciones
tri = []
for v in "xyz":
for c in "rgb":
otros = [o for o in "rgb" if o != c]
tri.append(f"{c}({v}) :- not {otros[0]}({v}), not {otros[1]}({v}).")
for (u, v) in [("x", "y"), ("y", "z"), ("x", "z")]:
for c in "rgb":
tri.append(f":- {c}({u}), {c}({v}).")
P = leer_asp("\n".join(tri))
est = modelos_estables(P)
print(f"\ntriángulo: {len(atomos(P))} átomos, {len(P)} reglas, {len(est)} modelos estables; uno: {sorted(est[0])}")Stable models match hand calculations, and the only difference from completion is where Fages’ theorem predicts: the positive loop p :- q. q :- p. is not tight, and completion also admits . The game has the unique stable model . The triangle has 6 stable models, the proper colorings: three-negation loops per vertex generate exactly one color per vertex (with two atoms false, the third is forced; with one true, the other two lose their rule), and nine constraints reject colorings with a monochromatic edge. Enumerating candidates is possible here; with a hundred vertices it would not be, which is what clingo is for.
How clingo solves
clingo (Potassco, University of Potsdam) is two chained programs (Gebser, Kaminski, Kaufmann and Schaub, 2012).
Grounding. gringo substitutes constants for variables and produces a ground program. It does not generate every possible instance, per rule, only those whose positive body can become true: it computes an overapproximation of derivable atoms bottom-up with seminaive evaluation and uses their values to instantiate. This is your Datalog engine treating negation conservatively. Ground-program size is ASP’s typical bottleneck: a rule with four variables over a thousand constants can yield instances, and reformulating to reduce variables per rule is the most profitable optimization.
Solving. clasp (Gebser, Kaufmann, Neumann and Schaub, 2007) is a CDCL solver like the CDCL lesson, operating on nogoods (literal sets that cannot all be true together) rather than clauses. Initial nogoods encode Clark completion of the ground program, with an auxiliary atom per rule body, so unit propagation propagates both “the body is true, so is the head” and “the atom is true, so is some supporting body”. By Fages’ theorem that suffices for tight programs. Positive cycles require excluding unfounded sets: a set of atoms is unfounded with respect to an assignment if none has a rule supporting it from outside . Lin and Zhao (2004) proved stable if and only if it models the completion and loop formulas of every loop; for p :- q. q :- p., loop ‘s formula is because no rule supplies external support, eliminating . As there can be exponentially many loops, clasp does not add them in advance: it detects unfounded sets during propagation and learns their nogoods on the fly, along with conflict nogoods from 1-UIP analysis. Optimization with #minimize uses branch and bound (each model adds a constraint improving its cost) or unsatisfiable-core-guided strategies.
ASP with clingo
The three models follow generate, define, test. The first colors the Petersen graph, which needs three colors, and counts all colorings; the second solves a Sudoku and asks for up to two solutions to check uniqueness.
import clingo
def resolver_asp(programa, modelos=0, opciones=()):
"""Devuelve (modelos como listas de símbolos, estadísticas, coste del último modelo)."""
ctl = clingo.Control([str(modelos), *opciones])
ctl.add("base", [], programa)
ctl.ground([("base", [])])
sal, coste = [], None
with ctl.solve(yield_=True) as h:
for m in h:
sal.append(sorted(str(s) for s in m.symbols(shown=True)))
coste = m.cost
st = ctl.statistics
resumen = {k: int(st["solving"]["solvers"][k]) for k in ("choices", "conflicts")}
resumen["átomos"] = int(st["problem"]["lp"]["atoms"])
resumen["reglas"] = int(st["problem"]["lp"]["rules"])
return sal, resumen, coste
# 1) Coloreado del grafo de Petersen
PETERSEN = [(i, (i + 1) % 5) for i in range(5)] + [(i, i + 5) for i in range(5)] + \
[(5 + i, 5 + (i + 2) % 5) for i in range(5)]
COLOR = "\n".join(f"edge({u},{v})." for u, v in PETERSEN) + """
node(X) :- edge(X, _). node(Y) :- edge(_, Y). % definir
col(r; g; b).
1 { color(X, C) : col(C) } 1 :- node(X). % generar: un color por vértice
:- edge(X, Y), color(X, C), color(Y, C). % comprobar: extremos de color distinto
#show color/2.
"""
mods, st, _ = resolver_asp(COLOR)
print(f"Petersen, 3 colores: {len(mods)} coloraciones {st}")
mods2, st2, _ = resolver_asp(COLOR.replace("col(r; g; b).", "col(r; g)."))
print(f"Petersen, 2 colores: {len(mods2)} coloraciones {st2}")
# 2) Sudoku
PISTAS = ["53..7....", "6..195...", ".98....6.", "8...6...3", "4..8.3..1",
"7...2...6", ".6....28.", "...419..5", "....8..79"]
SUDOKU = "\n".join(f"pista({f},{c},{int(ch)})." for f, fila in enumerate(PISTAS, 1)
for c, ch in enumerate(fila, 1) if ch != ".") + """
n(1..9).
1 { v(F, C, N) : n(N) } 1 :- n(F), n(C). % generar
v(F, C, N) :- pista(F, C, N).
bloque(F, C, ((F - 1) / 3) * 3 + (C - 1) / 3) :- n(F), n(C). % definir
:- v(F, C1, N), v(F, C2, N), C1 < C2. % comprobar: filas
:- v(F1, C, N), v(F2, C, N), F1 < F2. % columnas
:- v(F1, C1, N), v(F2, C2, N), bloque(F1, C1, B), bloque(F2, C2, B), (F1, C1) < (F2, C2).
#show v/3.
"""
mods, st, _ = resolver_asp(SUDOKU, modelos=2)
rejilla = {}
for s in mods[0]:
f, c, n = map(int, s[2:-1].split(","))
rejilla[f, c] = n
print(f"\nsudoku: {len(mods)} solución(es) de las 2 pedidas {st}")
for f in range(1, 10):
print(" " + " ".join(str(rejilla[f, c]) for c in range(1, 10)))npm run lab and open the connection link.The Petersen graph has 120 proper three-colorings, matching its chromatic polynomial evaluated at 3, and none with two because it contains cycles of length 5. The Sudoku has a unique solution, and statistics show 0 decisions and 0 conflicts: propagation of the ground program’s nogoods (1173 atoms, 4737 rules) suffices, as constraint propagation solved easy Sudokus in the CSP lesson.
The third model is a deployment problem with security constraints: assign nine services to six servers across two zones, putting internet-exposed services in the DMZ, sensitive-data services outside it, service pairs that cannot share a machine (separation of duties and blast radius), and each server’s CPU capacity, minimizing the cost of servers used. Then the same model in CP-SAT.
import clingo, time
from ortools.sat.python import cp_model
# Servicios: (nombre, CPU, expuesto a internet, maneja datos sensibles)
SERVICIOS = [("web", 4, True, False), ("api", 3, True, False), ("auth", 2, False, True),
("pagos", 3, False, True), ("bd", 5, False, True), ("cola", 2, False, False),
("informes", 3, False, True), ("cache", 2, False, False), ("logs", 2, False, False)]
# Servidores: (nombre, capacidad de CPU, zona, coste)
SERVIDORES = [("s1", 8, "dmz", 3), ("s2", 8, "dmz", 3), ("s3", 10, "interna", 4),
("s4", 10, "interna", 4), ("s5", 6, "interna", 2), ("s6", 12, "interna", 5)]
SEPARAR = [("auth", "pagos"), ("bd", "web"), ("bd", "api"), ("pagos", "informes")]
hechos = "\n".join(
[f"servicio({s}, {c})." for s, c, _, _ in SERVICIOS]
+ [f"expuesto({s})." for s, _, e, _ in SERVICIOS if e]
+ [f"sensible({s})." for s, _, _, d in SERVICIOS if d]
+ [f"servidor({m}, {cap}, {z}, {coste})." for m, cap, z, coste in SERVIDORES]
+ [f"separar({a}, {b})." for a, b in SEPARAR])
REGLAS = """
1 { en(S, M) : servidor(M, _, _, _) } 1 :- servicio(S, _). % generar
usado(M) :- en(_, M). % definir
:- expuesto(S), en(S, M), servidor(M, _, Z, _), Z != dmz. % comprobar: lo expuesto, en la DMZ
:- sensible(S), en(S, M), servidor(M, _, dmz, _). % lo sensible, nunca en la DMZ
:- separar(A, B), en(A, M), en(B, M). % separación
:- servidor(M, Cap, _, _), #sum { C, S : en(S, M), servicio(S, C) } > Cap. % capacidad
#minimize { Coste, M : usado(M), servidor(M, _, _, Coste) }. % optimizar
#show en/2.
"""
t0 = time.perf_counter()
ctl = clingo.Control(["0", "--opt-mode=opt"])
ctl.add("base", [], hechos + REGLAS)
ctl.ground([("base", [])])
mejor, costes = None, []
with ctl.solve(yield_=True) as h:
for m in h:
mejor = sorted(str(s) for s in m.symbols(shown=True))
costes.append(m.cost[0])
t_asp = time.perf_counter() - t0
print("clingo: costes de los modelos encontrados, en orden:", costes)
print(" óptimo demostrado:", int(ctl.statistics["summary"]["exhausted"]) == 1,
" asignación:", ", ".join(s[3:-1] for s in mejor))
# El mismo modelo en CP-SAT: una variable booleana x[s, m] por cada átomo en(S, M)
t0 = time.perf_counter()
mod = cp_model.CpModel()
x = {(s, m): mod.NewBoolVar(f"{s}@{m}") for s, *_ in SERVICIOS for m, *_ in SERVIDORES}
u = {m: mod.NewBoolVar(f"usado_{m}") for m, *_ in SERVIDORES}
for s, c, exp, sens in SERVICIOS:
mod.AddExactlyOne(x[s, m] for m, *_ in SERVIDORES)
for m, cap, z, _ in SERVIDORES:
if (exp and z != "dmz") or (sens and z == "dmz"):
mod.Add(x[s, m] == 0)
for m, cap, z, coste in SERVIDORES:
mod.Add(sum(c * x[s, m] for s, c, *_ in SERVICIOS) <= cap * u[m])
for a, b in SEPARAR:
mod.AddBoolOr([x[a, m].Not(), x[b, m].Not()])
mod.Minimize(sum(coste * u[m] for m, _, _, coste in SERVIDORES))
solver = cp_model.CpSolver()
solver.parameters.num_workers = 1
estado = solver.Solve(mod)
t_cp = time.perf_counter() - t0
asig = sorted(f"{s},{m}" for (s, m), v in x.items() if solver.Value(v))
print("CP-SAT:", solver.StatusName(estado), " coste:", int(solver.ObjectiveValue()), " asignación:", ", ".join(asig))
print(f"tiempo de pared (orientativo, varía con la máquina): clingo {t_asp * 1000:.0f} ms, CP-SAT {t_cp * 1000:.0f} ms")npm run lab and open the connection link.clingo finds models of cost 13, 12 and 11 and proves 11 optimal; CP-SAT reaches the same optimum with another assignment (several cost 11). Check manually: internal services total 19 CPU units, so inside needs two servers totaling at least 19, and the cheapest pair is s3 and s4 (cost 8; s5 and s6 total only 18); outside, web and api fit on one DMZ server (cost 3). The models are almost line-by-line translations, and both answer in milliseconds at this size. Differences appear as size grows. CP-SAT natively reasons with integers, linear sums and linear relaxation, favoring arithmetic-dominated problems (capacity, time, cost). ASP’s strength is definition: recursion, defaults and negation as failure with precise semantics, which require manual encoding in CP-SAT; its weakness is grounding, which can explode on large numeric domains.
Common mistakes
Exercises
Step 1 of 4. Why is monotone?
alcanzable(X) :- origen(X). / alcanzable(Y) :- alcanzable(X), arista(X, Y). / aislado(X) :- nodo(X), not alcanzable(X). / riesgo(X) :- aislado(X), not parcheado(X). / parcheado(X) :- actualizado(X), not riesgo(X)., where origen, arista, nodo and actualizado are EDB. What is the correct diagnosis?p :- not q. q :- not p. and : p :- not p.?p :- q. q :- p. r :- not p., what is true?par(ana, bea). par(bea, carlos). and rules, in this order, anc(X, Y) :- par(X, Y). and anc(X, Y) :- anc(X, Z), par(Z, Y)., you request every answer to anc(ana, Q). What happens?taint(S, W, K) :- taint(S, V, K), flow(V, W), not limpio(W)., with limpio(n) and limpio(c2) (a classless sanitizer). What changes in the findings?seminaive_path(edges) for program path(X, Y) :- edge(X, Y). and path(X, Z) :- path(X, Y), edge(Y, Z). Return (path, joins): the fixed-point set of pairs and number of joins, counting one for each matching pair (delta fact, edge) on variable Y, including the last iteration that produces nothing. Use a hash index of edges by origin. Tests compare naive evaluation (ingenua_path, already written) on random graphs and require exactly one join per path fact whose endpoint has outgoing edges.from collections import defaultdict
def ingenua_path(edges):
"""Evaluación ingenua (referencia). Devuelve (path, joins)."""
path, joins = set(), 0
while True:
nuevo = set(edges)
for (x, y) in path:
for (a, z) in edges:
if a == y:
joins += 1
nuevo.add((x, z))
if nuevo == path:
return path, joins
path = nuevo
def seminaive_path(edges):
"""Devuelve (path, joins) combinando en cada iteración solo el delta con edge."""
edges = set(edges)
path = set(edges)
delta = set(edges)
joins = 0
# tu código: índice de las aristas por su origen y bucle mientras el delta no esté vacío
return path, joinsSummary
- A definite program has a least Herbrand model , exactly what follows from it (van Emden and Kowalski), coinciding with . Without function symbols (Datalog), is finite and computed in polynomial time in the data.
- SLD resolution is sound and complete for any computation rule, but Prolog traverses depth-first and is incomplete: left recursion creates infinite branches. Cut prunes the tree; if red, the program can no longer be read clause by clause.
- Negation as failure implements the closed world and is nonmonotone. Clark completion gives a declarative reading but accepts circular justification.
- Seminaive evaluation combines only deltas and computes the same fixed point with far fewer joins; stratified negation evaluates by strata (strongly connected components in topological order), and magic sets direct bottom-up evaluation toward the query.
- Points-to, data flow and taint are relation closures: a few Datalog rules, and systems like CodeQL, Doop and Soufflé run them on millions of lines.
- A stable model is a set that is the least model of its reduct . ASP programs with generate, define and test, and clingo solves by grounding with seminaive evaluation and searching with CDCL over completion nogoods plus those of unfounded sets.