Tabling (SLG resolution)¶
Tabling memoises subgoal calls and their computed answers. when a recursive call encounters a subgoal that is already being evaluated, the caller suspends and waits for answers rather than re-entering the computation. This prevents infinite loops on left-recursive and mutually recursive predicates and is a prerequisite for well-founded semantics.
The implementation lives in clausal.logic.tabling.
Examples on this page are Clausal Prolog (.clausal). The
Python examples run in a seam (.seam) file, Clausal's
Python-syntax surface, which spells the directive -table(path/2).
The problem¶
Plain SLD resolution (depth-first, left-to-right) diverges on left-recursive definitions. Consider transitive closure over an acyclic graph:
:- table(path/2).
edge(1, 2).
edge(2, 3).
edge(3, 4).
path(X, Y) :-
edge(X, Y).
path(X, Y) :-
path(X, Z),
edge(Z, Y).
test("terminates on left recursion") :-
findall(Y, path(1, Y), YS),
YS == [2, 3, 4].
The second clause is left-recursive: the first body goal is path itself. Without tabling, path(1, Y) immediately recurses on path(1, Z), which recurses on path(1, Z2), ad infinitum — even though the graph has no cycles and the answer set is finite.
Other classic programs that require tabling:
- Same generation —
sg(X, Y) :- parent(P, X), sg(P, Q), parent(Q, Y)— the recursivesg(P, Q)generates an unbounded search tree without memoisation. - Mutual recursion —
reach_acallsreach_bwhich callsreach_aon a cyclic graph. Without tabling both predicates, the mutual recursion diverges.
Using tabling¶
Mark a predicate as tabled with the table directive:
Put the directive before the predicate's clauses, by convention (it also takes effect when written after them). Multiple predicates can be tabled in the same module, here two that call each other over a cyclic graph:
:- table(reach_a/2).
:- table(reach_b/2).
link_a(1, 2).
link_b(2, 1).
reach_a(X, X).
reach_a(X, Y) :-
link_a(X, Z),
reach_b(Z, Y).
reach_b(X, X).
reach_b(X, Y) :-
link_b(X, Z),
reach_a(Z, Y).
test("mutual recursion terminates") :-
findall(Y, reach_a(1, Y), YS),
msort(YS, [1, 2]).
Tabled predicates are queried exactly like non-tabled ones — the tabling wrapper is transparent. In a .seam file, query with the goal-position seam:
From a plain .py file (which cannot use --), use solve(goal, module=m) or call — see Python integration.
A tabled call completes its table before its first answer (operator ruling D68, 2026-10-16; XSB's local scheduling), then hands back the answers in table order, the order they were first derived in. So a second call of the same table in the first call's continuation (findall(X-Y, (t(X), t(Y)), L)) sees every answer, and taking only the first answer leaves the table complete. The exceptions: a recursive or mutually recursive call inside the evaluation of a table it depends on, which SLG hands the answers found so far while the table is still being computed; and an answer that carries a constraint (below).
Answer order is table order: the order answers were first derived in, not clause order across re-derivations, and not the standard order of terms. With move(a,b). move(b,a). move(b,c). move(c,d). and the tabled win(X) :- move(X, Y), \+ win(Y). (a .pl module's negation; the seam writes not win(Y)), call/solve of win(X) used to answer c, a, b (the definite answer streamed first, the undefined ones after resolution) and now answers a, b, c (query_wfs still lists its definite answers first). Tabled Scryer returns a table's answers in the standard order of terms (its table is a trie built on library(assoc)), so the first answer of path(a, Y) over e(a, b). e(b, a). is a there and b here.
The following were settled by operator ruling D74, 2026-10-19 (Mike: "all as recommended"): Q1 ships as a recorded limitation, Q2 and Q3 are accepted as documented here. Q4 is accepted and documented under the same ruling but stays provisional (not yet final):
- Constrained answers (Q1) — a recorded limitation. An answer that carries a constraint (
dif/2, CLP,freeze/2on a variable it leaves unbound) is handed over when it is derived, before its table completes, because the table cannot store the constraint (audit finding A12-F001,todo/tabled-answers-drop-their-constraints-on-replay-2026-07-05.md). Such answers keep the old weakness: withc(X) :- dif(X, a). c(1). c(2).tabled,findall(X-Y, (c(X), c(Y)), L)gives 7 pairs instead of 9. A cut over such a call raisespermission_error(cut, incomplete_table, c/1). - CLP(Q) constraints are kept in the table, modulo entailment. An answer whose variables carry CLP(Q) state is stored with its residue: the constraints projected onto the answer's variables, as
dump/3writes them. Every answer handed out from the table posts them again on its fresh variables, so withp(X) :- {X >= 1, X =< 5}tabled,(p(X), sup(X, S))givesS = 5on the first call and on every later one, andp(X), X = 6fails; a negation over the table ({X >= 10}, \+ p(X)in a.plmodule,not p(X)in the seam) reads each row against the caller's constraints. Answers are kept modulo entailment (answer subsumption): a new answer whose constraints entail those of a stored answer of the same shape (a variant, before the constraints) is not new, the stored one covers it. The solver decides the entailment. Sop(X) :- {X >= 0}. p(X) :- p(Y), {X >= Y + 1}.completes with the one answerX >= 0(each laterX >= kis covered), and the same constraints written in another order or basis are one answer. A stored answer is never replaced: a more general answer that comes later is kept beside the ones it covers (operator ruling 2026-11-03). Termination is not guaranteed for recursion through CLP(Q) answers. It holds when every answer derived from some point on is covered by a stored one (a recursion that tightens its constraints). One that loosens them (p(X) :- p(Y), {X >= Y - 1}, each answer more general than the last) does not terminate, nor does one with infinitely many incomparable answers, as with any tabled predicate that has infinitely many answers. Not compared: a stored residue over a variable outside the answer (the CLP(Q) port writesX =\= 1with such a slack variable), which is kept as a separate answer. An answer whose constraints are all CLP(Q) waits for its table to complete like any other; one that also carriesdif/2,freeze/2or CLP(FD) constraints is still handed over live (the limitation above), and those constraints are not stored yet. - An error during evaluation arrives with no answers before it (Q2). The table is computed before any answer is returned, so an exception raised anywhere in its evaluation reaches the caller first:
fib(N, F)withNunbound, whose third clause raisesinstantiation_errorinis/2, used to returnfib(0, 0)andfib(1, 1)first and now raises at once. XSB and SWI behave the same; tabled Scryer swallows the error. - A table that never completes never answers (Q3). A tabled predicate with infinitely many answers (
nat(0). nat(N) :- nat(M), N is M + 1.) never gives a first answer: the call runs, and its table grows, until memory runs out.once(nat(X))hangs. Bound the generator (M < 1000), or do not table it; an opt-in per-predicate streaming mode istodo/tabled-streaming-mode-per-predicate-2026-10-16.md. - A tabled side effect runs once (Q4) — provisional under D74. A leader whose evaluation read only complete tables, and derived no conditional answer, runs no confirming second pass over its clauses. So a tabled body that reads its own side effect from the same pass (an
assertz/1in one clause, read by a clause that ran before it) gives the untabled program's answers, with the side effect run once. Accepted and documented, not yet final: this may still change. Tabling with side effects is undefined in XSB too.
Invalidation¶
Tabled answers are cached for the lifetime of the module. If the underlying clauses change (via assertz, asserta, or retract on a tabled predicate — which must be declared dynamic), all cached answers for that predicate are automatically invalidated. The next query recomputes from scratch.
To invalidate manually, call the builtins:
:- table(path/2).
edge(1, 2).
path(X, Y) :-
edge(X, Y).
test("abolish, then recompute") :-
path(1, 2),
abolish_table(path, 2), % clear one predicate's cache
abolish_all_tables, % clear all
path(1, 2).
From Python, in a .seam file, the same builtins run in goal position: if --abolish_table(path, 2): ... (the seam writes the zero-arity goal with parentheses, abolish_all_tables()). The Database object also has abolish_table(functor, arity) / abolish_all_tables() methods, but Database is internal (see Public API).
Design
Three-path dispatch¶
A tabled predicate's dispatch function is wrapped so that each call takes one of three paths based on the table state:
| Path | Condition | Behaviour |
|---|---|---|
| COMPLETE | Table entry exists and is complete | Yield all cached answers directly. No dispatch call. |
| CONSUMER | Table entry exists but still evaluating | Yield currently known answers, then suspend. The leader will resume this consumer when new answers arrive. |
| LEADER | No table entry for this subgoal | Create a new table entry, drive the original dispatch, collect answers, then run the completion phase to resume suspended consumers. |
Variant checking¶
Subgoal identity is determined by variant checking: two calls are the same subgoal if they are variants, equal up to a consistent renaming of their variables (ISO/XSB). p(X, Y) and p(Y, X) are one subgoal; p(X, X) is another. make_subgoal_key(args, trail) normalises the arguments via _normalize_for_key, which:
- derefs bound variables
- replaces an unbound
Varwith(_VAR, n),nits number in order of first occurrence across the whole call (sop(X, X)keys as((_VAR, 0), (_VAR, 0))andp(X, Y)as((_VAR, 0), (_VAR, 1))); an attributed variable is a variable - type-tags
bool/float/complexleaves so1,Trueand1.0stay distinct keys - recursively normalises lists, cells (plain tuples), dicts and sets
The same key tells answers apart: w(f(_, _)) and w(f(X, X)) are two answers of a tabled w/1, and w(f(X, Y)), w(f(Y, X)) one.
The table store maps (functor, arity, variant_key) → TableEntry.
Answer freezing¶
when a solution is found, the current arg bindings are frozen — fully dereferenced into a tuple — and stored in the TableEntry. Duplicate answers (by value) are suppressed via a set. Later consumers unify the original query args against each stored answer. An answer that leaves a variable unbound (v(_)) is stored renamed apart and every replay gets a fresh copy of it (TableEntry.row), as a clause is renamed apart on each call: a binding made through one replay is never seen by the next, and findall(X-Y, (v(X), v(Y)), L) gives [_A-_B, _C-1, 1-_D, 1-1] for v(_). v(1).. The sharing within one answer (f(X, X)) is kept. Ground answers, the common case, are stored and replayed as they are.
TableEntry¶
class TableEntry:
status: str # "evaluating" | "complete"
answers: list[tuple] # frozen answer tuples, in discovery order
answer_set: set # for O(1) duplicate detection
suspended: list # SuspendedConsumer instances
conditions: list # parallel to answers: frozenset[frozenset[DelayedNegation]] | _FAILED
_current_delays: set # accumulates DelayedNegation during current derivation
scc_deps: set # evaluating ancestors consumed (mutual recursion / SCC completion)
conditions[i] is a disjunction of delay sets, one inner set per derivation of the answer: it holds an empty inner set when some derivation is delay-free (the answer is true), only non-empty inner sets when every derivation is conditional (WFS undefined), or the _FAILED sentinel when every derivation was invalidated. Read it through truth_value(i) (True, Undefined or False) and delays_for(i) (the union of the live delay sets) rather than directly.
SuspendedConsumer¶
class SuspendedConsumer:
generator # the consumer's StepGenerator
parent # routing key for intercepting yields
args # call args (for unification with new answers)
trail # the consumer's Trail
answers_seen # index into entry.answers — how many already yielded
Implementation
Trampoline-mode wrapper¶
The primary implementation (make_tabled_wrapper_trampoline) wraps a trampoline-mode dispatch function. It follows the trampoline protocol: yields (target, value) tuples.
Leader path:
- Create a
TableEntrywith status"evaluating". Push it onto the leader context stack. - Spawn a
StepGeneratorover the original dispatch. - Drive it via the trampoline protocol. Each time the inner dispatch yields a solution, freeze the args, snapshot
entry._current_delaysas the answer's condition set, andadd_answerto the table. Nothing is yielded to the leader's caller yet: the leader re-runs the dispatch until no new answer appears (a fixpoint), then hands back every answer from the table, in table order (complete first, operator ruling D68, 2026-10-16; XSB's local scheduling). If the leader consumed an ancestor that is still evaluating, it is a member of that ancestor's SCC: it stays"evaluating", and the answers it hands back come from an incomplete table, so a cut over that call raisespermission_error(cut, incomplete_table, F/N). A later call of such a dormant member re-leads it: it replays its known rows to the caller, then re-runs to a fixpoint of its own. A re-lead whose clauses can read nothing that changed since a quiet pass of theirs (no table changed, no clause written, the same leader below it on the stack) skips that re-run, which would only repeat the pass (operator ruling 2026-11-03; "Idle re-leads" inclausal/logic/tabling.py). Every table gains the same answers in the same order either way.CLAUSAL_TABLING_SEMINAIVE=0turns the skip off. - when the inner dispatch is exhausted, enter the completion phase.
- After completion, run
_resolve_conditionsto simplify delayed negations (WFS). - Pop the leader from the context stack and mark
"complete".
Consumer path:
- Yield all currently known answers from the table entry.
- Register a
SuspendedConsumeron the entry. - Yield
(parent, _TABLING_SUSPEND). The trampoline intercepts this sentinel and sendsDONEto the consumer's parent, so the parent's while-loop exits normally. - when the leader resumes the consumer (sending
_TABLING_RESUME), yield any answers accumulated since the last suspension. - If the table is still evaluating, re-suspend for another round.
Completion phase:
After the original dispatch is exhausted, the leader resumes each suspended consumer via a mini-trampoline:
- Send
_TABLING_RESUMEto the consumer's generator. - Drive the consumer, intercepting yields directed at the consumer's (dead) parent:
(parent, None)→ consumer found a solution → freeze andadd_answer; if new, yield to leader's caller.(parent, DONE)→ consumer finished.(parent, _TABLING_SUSPEND)→ consumer re-suspends for the next round.- Other
(gen, value)→ sub-call from consumer body → forward through the mini-trampoline. - Repeat until a fixpoint: no new answers are discovered in a full round.
- Send
DONEto any remaining suspended consumers for cleanup. - Run
_resolve_conditions(entry, table_store)to resolve WFS delayed negations. - Pop the leader context stack.
- Mark the table entry
"complete".
Simple-mode wrapper¶
make_tabled_wrapper_simple provides a simpler variant for simple-mode dispatch. It uses fixpoint iteration instead of suspension:
- Create a
TableEntry. - Repeatedly run the original dispatch until no new answers appear (fixpoint).
- Mark complete.
- Yield all answers.
Consumer calls during evaluation yield currently known answers and return (no suspension mechanism in simple mode).
Simple-mode adapter¶
_trampoline_to_simple_adapter bridges a trampoline-mode tabled wrapper to simple-mode callers. It creates a StepGenerator root and drives a mini-trampoline, yielding None per solution (simple protocol). It intercepts _TABLING_SUSPEND by sending DONE to the suspended generator.
Sentinels¶
| Sentinel | Direction | Meaning |
|---|---|---|
_TABLING_SUSPEND |
consumer → trampoline | "Park me; I'm waiting for more answers" |
_TABLING_RESUME |
leader → consumer | "Wake up; check for new answers" |
_FAILED |
internal | Marks an invalidated conditional answer (WFS) |
_TABLING_SUSPEND and _TABLING_RESUME are distinct from the trampoline's DONE sentinel. The trampoline and solutions() function intercept _TABLING_SUSPEND and convert it to DONE so that non-tabling-aware code (callers of the tabled predicate) never sees these sentinels.
Database integration¶
Directive handling¶
The table(pred/arity) directive (the seam's -table(pred/arity)) is parsed by the import hook alongside dynamic and discontiguous. It calls db.mark_tabled(functor, arity), which records the predicate in Database._tabled.
The target must be a predicate the declaring module compiles — one with clauses there, or a dynamic one that will get them. table on an imported predicate, on a seam -specialize alias, or on a clause-less declaration is refused at load by compiler_v2._refuse_untablable_target, because marking Database._tabled in a module that never compiles the predicate wraps nothing at all.
Compilation pipeline¶
Tabled predicates are wrapped with make_tabled_wrapper_trampoline in compiler._install — the one place a compiled dispatch function is installed, reached by module load and by every runtime recompile alike. ensure_tabled_wrapper makes it idempotent, so the load-time second pass (compiler_v2 step 6) does not stack a second wrapper on the first.
Installing there is what makes tabling survive assertz/asserta/retract: those recompile the predicate, and a recompile that installed the raw dispatch would silently drop memoisation — and, for a left-recursive predicate, termination with it.
Table store¶
Database._table_store is a dict mapping (functor, arity, variant_key) → TableEntry. It is exposed as db.table_store (read-only property).
Auto-invalidation¶
when assertz, asserta, or retract modify a tabled predicate's clauses, the database automatically clears all table entries for that predicate:
compiler._install abolishes as well, when it re-establishes the wrapper on a recompile. That covers the mutation paths that never call Database.assertz/retract — the retract/1 builtin deletes straight out of the owning database's clause list and clears the dispatch, and the next call recompiles through _install.
Why generators make tabling natural¶
The architecture doc notes that tabling is easier on generators than on a WAM. Here is why concretely:
Suspension is free. when a consumer needs to wait for more answers, it simply yields a sentinel and its execution state is frozen in the generator frame. On a WAM, this requires explicitly saving the entire environment stack, choice points, and register file.
Resumption is a send. The leader resumes a consumer by calling generator.send(_TABLING_RESUME). The consumer picks up exactly where it left off. On a WAM, this requires restoring the saved state and re-entering the engine loop at the right instruction pointer.
The trampoline handles routing. The existing trampoline protocol already decouples generators from the call stack. The tabling wrapper just adds a new sentinel (_TABLING_SUSPEND) that the trampoline intercepts. No changes to the core trampoline or compiler were needed.
Well-founded semantics¶
when a program recurses through negation — e.g. win(X) :- move(X, Y), \+ win(Y). (ISO notation, as in a .pl module; the seam writes not win(Y), and Clausal Prolog refuses \+ from 2.0, see below) with symmetric moves — standard NAF gives unsound answers because it checks immediately whether the negated goal succeeds, but that goal is still being evaluated (circular dependency). Well-Founded Semantics (WFS) provides a principled three-valued semantics (true / false / undefined) that handles this correctly.
How it works¶
when evaluating \+ P(args) (.pl; the seam's not P(args)) where P is tabled:
- Complete table: standard NAF — check if any answer matches, negate.
- Evaluating table (cycle detected): delay the negation. The derivation continues conditionally — the answer is recorded with a
DelayedNegationcondition attached.
After the SLG leader finishes driving all consumers and no new answers appear, _resolve_conditions runs:
- Delayed
\+ P(args)targeting a completed table with no matching answer → negation true → condition removed (answer becomes unconditional). - Delayed
\+ P(args)targeting a completed table with an unconditional matching answer → negation false → answer invalidated. - Remaining conditional answers form unfounded sets — truth value undefined.
Example: symmetric game¶
From release 2.0, Clausal Prolog refuses \+/1 (with once/1, forall/2,
call_nth/2, setup_call_cleanup/3 and call_cleanup/2; operator rulings
2026-11-28), so a tabled negation is written in
the seam, whose negation is not Goal, as in the two examples
here, or in a .pl (full ISO) module as \+ win(Y):
-table(win/1)
move(1, 2),
move(2, 1),
win(X) <- (move(X, Y), not win(Y))
# Both answers are undefined; a plain query yields them unmarked.
test("both positions answer") <- (findall(X, win(X), XS), msort(XS, [1, 2]))
win(1) depends on not win(2), and win(2) depends on not win(1). Both are unfounded — WFS assigns truth value undefined to both.
Example: asymmetric game¶
-table(win/1)
move('a', 'b'),
move('b', 'a'),
move('a', 'c'),
win(X) <- (move(X, Y), not win(Y))
test("a wins, b and c do not") <- findall(X, win(X), ['a'])
win(c)= false (no moves fromc)win(a)= true (viamove(a, c),not win(c)succeeds)win(b)= false (not win(a)fails becausewin(a)is true)
Truth value inspection¶
TableEntry.truth_value(i) returns True, False, or the strong-Kleene Undefined singleton for the i-th answer based on its conditions. The query_wfs() function in clausal.logic.solve returns results annotated with "_truth" keys.
Compiler integration¶
The compiler detects a negated call to a tabled predicate (\+ p(...) in a .pl module, not p(...) in the seam) and emits:
_m = trail.mark()
if _naf_tabled("pred", arity, (arg0, ..., argN), trail, _table_store):
k_stmts
trail.undo(_m)
_naf_tabled is a plain function (not a generator) — it returns True (negation succeeds, possibly conditionally) or False (negation fails). It works identically from both simple and trampoline compiled code.
Non-tabled predicates fall through to the existing inline NAF codegen (no behavior change).
Data structures¶
DelayedNegation(functor, arity, key, frozen_args)— represents a conditional dependency.TableEntry.conditions— list parallel toanswers, each entry a set of delay sets (one per derivation). An empty inner set = unconditional._FAILEDsentinel = invalidated.TableEntry._current_delays— accumulates delays during the current derivation.- Leader context stack — thread-local stack of
TableEntryobjects.push_leader/pop_leader/current_leaderhelpers._naf_tabledattaches delays to the current leader.
Limitations¶
- Variant-only tabling. Two calls are the same subgoal only if their arguments are structurally identical (modulo unbound variables). Subsumption-based tabling (where
p(1, X)subsumesp(1, 2)) is not implemented. - No answer subsumption. All answers are kept. There is no mechanism for lattice-based answer combination (e.g., keeping only the maximum).
- First-answer cost. A tabled call computes its whole table before its first answer, so taking only the first answer (the seam's
once, or ISOonce/1in a.plmodule) of a large table pays for all of it, and a call whose table is infinite never answers (Q3 above; operator ruling D74, 2026-10-19). - Side effects during incomplete evaluation. Python code called from within a tabled predicate may observe intermediate state when the table is still evaluating. This is documented, not prevented.
Test coverage
Tests are in tests/test_tabling.py (46 tests), tests/test_slg_termination.py (20 tests), and tests/test_wfs.py (31 tests).
Unit tests (test_tabling.py):
- TableEntry state management, duplicate suppression, ordering
- Key computation: ground scalars, bound/unbound vars, lists, compounds, variant matching
- Answer freezing and unification
- Simple-mode wrapper: basic dispatch, cache hit
- Trampoline-mode wrapper: basic, multiple answers, adapter
- Database integration: table store, abolish, auto-invalidation on assertz/retract
Integration tests (test_tabling.py):
- Tabled fibonacci (fib/2): basic, zero, one, cache hit, ground query success/failure
- Cyclic path (1→2→3→1): termination, all pairs, per-node queries, ground queries, table completion
- Multiple tabled predicates (anc/2 + desc/2): mutual use, correctness
- Import hook: directive metadata, predicate wrapping, non-tabled predicates unaffected
- Abolish and recompute
SLG termination tests (test_slg_termination.py):
- Left-recursive transitive closure on an acyclic graph — the canonical example that diverges without tabling
- Same generation (Bancilhon et al. 1986) — reflexive, sibling, cousin, cross-level, negative cases
- Mutual recursion through two tabled predicates on a cyclic graph
WFS tests (test_wfs.py):
- DelayedNegation: equality, hashing, repr
- TableEntry conditions: default unconditional, with delays, truth values (true/false/undefined)
- Leader context stack: empty, push/pop, nesting
- _naf_tabled: complete table (match/no match), skips failed, evaluating table delays, no entry, var args
- _resolve_conditions: unconditional passthrough, resolve to true, resolve to false, unfounded self-reference, multiple delays partial resolution
- Positive-only regression: tabled fib and cyclic path still work
- Complete table NAF: immediate check on complete table
- Symmetric win/move: both win(1) and win(2) are undefined
- Asymmetric win/move: win(a) is true
- No negation cycle: tabled with NAF but no cycle → standard behavior
- query_wfs API: returns list with truth annotations
Fixtures:
- tests/fixtures/tabled_fib.seam — tabled fibonacci
- tests/fixtures/tabled_path.seam — tabled cyclic path (1→2→3→1)
- tests/fixtures/tabled_left_rec.seam — left-recursive path on acyclic graph (1→2→3→4)
- tests/fixtures/tabled_same_gen.seam — same-generation problem
- tests/fixtures/tabled_mutual_rec.seam — mutual recursion via alternating link types
- tests/fixtures/wfs_win.seam — symmetric win/move (WFS: both undefined)
- tests/fixtures/wfs_win_asym.seam — asymmetric win/move (WFS: win(a) true)
See also: Well-Founded Semantics — three-valued semantics for programs with negation cycles · Constraints — attributed variables, the mechanism underlying tabling suspension · Meta-Interpreters — iterative deepening as a pure-Prolog alternative to tabling for cyclic programs · Scryer Prolog Embedding — Scryer also provides tabling via library(tabling) · Trealla Prolog Embedding — fast lightweight alternative (no tabling support).