Algorithm Search⌘K

Algorithmintro

Backward chaining

Also called goal-driven inference.

Start from the goal, pick a rule that concludes it, and prove the conditions of that rule as subgoals in the same way, depth first, until every subgoal is a known fact.

Solves
Horn-SAT
Time
O(s^(n+1)) worstO(1) best
Space
O(n) extra
Where
n = the number of atoms; s = the total number of atom occurrences in the rules
Properties
deterministic
Origin
Edward H. Shortliffe, 1976

Backward chaining is the inference method of goal-driven rule systems. To prove a goal, it picks a rule whose conclusion is the goal and proves the conditions of the rule as new goals, depth first and from left to right, until each open goal is a known fact. This page treats it as the control method of rule-based expert systems such as MYCIN, on propositional rules: it adds a loop check on the goal stack and memo tables for proved and failed goals, and it shows the cost of the search. With variables and unification the same search is SLD resolution, the proof procedure of Prolog, and the page on it gives the first-order theory. The propositional decision problem itself is Horn-SAT, which forward chaining solves in linear time.

In plain words

You want to know one thing, and you have rules of the form "if these things are true, then that thing is true". Look for a rule whose "then" part is the thing you want. Its "if" parts become new questions, and you answer each of them the same way. A question that is a known fact is answered at once. If a rule fails, try the next rule for the same question. Keep a list of the questions that you are working on now. If a question comes back while you are still working on it, do not start it again, or you go around in a circle forever. Write down the answers you found, so that you do not do the same work twice.

The problem

The input is a finite set PP of propositional definite rules a←b1,…,bma \leftarrow b_1, \ldots, b_m, where a fact is a rule with m=0m = 0, and a goal atom gg. The semantics is the least model MM of PP: the least set of atoms that contains the head of each rule whose body atoms it contains, or M=⋃kTPk(∅)M = \bigcup_k T_P^k(\emptyset) for the immediate consequence operator TPT_P. The task is to decide whether g∈Mg \in M, which is the same as deciding that the Horn clause set P∪{←g}P \cup \{\leftarrow g\} is unsatisfiable. This is a P-complete problem that has a linear-time algorithm; backward chaining is chosen for its focus on the goal, not for its worst case.

The algorithm

The procedure is depth-first search over the rules. SS is the stack of goals that are open now, and depth(x)\mathrm{depth}(x) is the position of xx on SS, from 00 at the bottom. A call returns a truth value and low\mathit{low}, the smallest depth of a stack atom that a loop check met during the call, or ∞\infty.

  1. BACKWARD-CHAIN(P, g)
  2. 1proved ← ∅, failed ← ∅, S ← an empty stack
  3. 2return the truth value of PROVE(g)
  4. PROVE(a)
  5. 3if a ∈ proved then return (true, ∞)
  6. 4if a ∈ failed then return (false, ∞)
  7. 5if a is on S at depth d then return (false, d) ▷ loop check
  8. 6k ← the size of S; push a on S; low ← ∞
  9. 7for each rule a ← b_1, …, b_m of P, in order do
  10. 8for j ← 1 to m do
  11. 9(ok, c) ← PROVE(b_j); low ← min(low, c)
  12. 10if not ok then continue with the next rule at L7
  13. 11pop a from S; add a to proved; return (true, ∞)
  14. 12pop a from S
  15. 13if low ≥ k then add a to failed; return (false, ∞) ▷ the failure did not use the stack below a
  16. 14return (false, low) ▷ the failure used a goal below a: do not store it

Line L13 stores a failure only when no loop check below aa hit a goal that was open before aa. A failure that line L14 reports depends on the current stack: the same atom can be provable when it is asked from another place. MYCIN added one more case to line L7: when no rule concludes a goal that is marked askable, ask the user.

Example

The rules, in this order, are g←dg \leftarrow d, d←dd \leftarrow d, g←a,bg \leftarrow a, b, a←ga \leftarrow g, a←ca \leftarrow c, b←ab \leftarrow a, and the fact cc.

step call stack before the call what happens
1 PROVE(g)(g) empty push gg at depth 0, try g←dg \leftarrow d
2 PROVE(d)(d) gg push dd at depth 1, try d←dd \leftarrow d
3 PROVE(d)(d) g,dg, d loop check: dd is at depth 1, return (false, 1)
4 back in dd gg no rule left, low=1≥1\mathit{low} = 1 \ge 1: store dd as failed
5 PROVE(a)(a) gg rule g←a,bg \leftarrow a, b; push aa at depth 1, try a←ga \leftarrow g
6 PROVE(g)(g) g,ag, a loop check: gg is at depth 0, return (false, 0)
7 PROVE(c)(c) g,ag, a rule a←ca \leftarrow c; cc is a fact: store cc as proved
8 back in aa gg store aa as proved
9 PROVE(b)(b) gg push bb, rule b←ab \leftarrow a, PROVE(a)(a) is a memo hit, store bb as proved
10 back in gg empty store gg as proved; the answer is true

In step 6 the call for aa meets gg, a goal that was open before it. If aa had then failed, line L14 would not have stored the failure, since aa could still follow from gg by another rule of gg.

Correctness

The correctness proof shows an invariant: every atom in proved is in MM, no atom in failed is in MM, and a call that returns (false,l)(\mathit{false}, l) has no proof tree that avoids the stack atoms at depth ll or more. A proof tree of least size has no atom twice on one path, so the loop check of line L5 loses no proof. When low≥k\mathit{low} \ge k, the set of avoided atoms is empty, so the atom is not in MM and line L13 may store it. The top call starts with the empty stack, so it returns true exactly when g∈Mg \in M. The stack holds distinct atoms, so the search stops.

Proof: Backward chaining with a loop check and memo tables decides the least modelfull

Let PP be a finite set of propositional definite rules a←b1,…,bma \leftarrow b_1, \ldots, b_m (a fact has m=0m = 0) and let MM be its least model. We use the procedure of the page: PROVE(a)(a) works with a goal stack SS, a set proved and a set failed, and returns a pair (ok,low)(\mathit{ok}, \mathit{low}). The depth of an atom on SS is its position, counted from 00 at the bottom.

Proof trees

A proof tree for aa is a finite tree whose root carries aa, in which a node with atom xx has children y1,…,ymy_1, \ldots, y_m for some rule x←y1,…,ymx \leftarrow y_1, \ldots, y_m of PP. An atom aa is in MM exactly when it has a proof tree; this is the usual reading of M=⋃kTPk(∅)M = \bigcup_k T_P^k(\emptyset) by induction on kk. For a set XX of atoms, aa is XX-provable when it has a proof tree in which no node carries an atom of XX. So a∈Ma \in M exactly when aa is ∅\emptyset-provable, and an atom of XX is never XX-provable.

Lemma 1. If aa is XX-provable, then aa has a proof tree that avoids XX and in which no atom occurs twice on one path from the root.

Proof. Take an XX-avoiding proof tree of least size. If an atom xx occurs at a node uu and again at a node vv below uu, replace the subtree at uu by the subtree at vv. The result is a smaller XX-avoiding proof tree, a contradiction. □\square

Invariant

Lemma 2. At every moment, proved ⊆M\subseteq M and failed ∩ M=∅\cap\, M = \emptyset. Each call PROVE(a)(a) that returns (true,∞)(\mathit{true}, \infty) has a∈Ma \in M. Each call that returns (false,l)(\mathit{false}, l) has the property that aa is not XX-provable for X={x∈S:depth(x)≥l}X = \{ x \in S : \mathrm{depth}(x) \ge l \}, where SS is the stack at the time of the call.

Proof. By induction on the number of calls that have returned. Take a call PROVE(a)(a) with stack SS, ∣S∣=k|S| = k, and assume the claim for all calls that returned before it.

  • Line L3: a∈a \in proved ⊆M\subseteq M.

  • Line L4: a∈a \in failed, so a∉Ma \notin M, so aa is not XX-provable for any XX.

  • Line L5: a∈Sa \in S at depth dd, the result is (false,d)(\mathit{false}, d), and a∈Xa \in X, so aa is not XX-provable.

  • Line L11: the rule a←b1,…,bma \leftarrow b_1, \ldots, b_m had all inner calls return true, so each bj∈Mb_j \in M by the induction hypothesis, and a∈Ma \in M. Adding aa to proved keeps the invariant.

  • Lines L12 to L14: every rule a←b1,…,bma \leftarrow b_1, \ldots, b_m of aa had an inner call PROVE(bj)(b_j) that returned (false,c)(\mathit{false}, c) with c≥lowc \ge \mathit{low}. That call ran with the stack SS plus aa on top, at depth kk. By the induction hypothesis bjb_j is not XjX_j-provable, where XjX_j is the set of atoms of S∪{a}S \cup \{a\} at depth at least cc.

    Let ll be the value that the call returns: l=∞l = \infty when low≥k\mathit{low} \ge k (line L13) and l=lowl = \mathit{low} otherwise (line L14). Let XX be the set of atoms of SS at depth at least ll. In both cases Xj⊆X∪{a}X_j \subseteq X \cup \{a\}: if low≥k\mathit{low} \ge k, then c≥kc \ge k and Xj⊆{a}X_j \subseteq \{a\}; if low<k\mathit{low} < k, then c≥low=lc \ge \mathit{low} = l and XjX_j holds only atoms of SS at depth at least ll, and maybe aa.

    Assume that aa is XX-provable. By Lemma 1 it has an XX-avoiding proof tree in which aa does not occur below the root. The root uses some rule a←b1,…,bma \leftarrow b_1, \ldots, b_m, and the subtree of each bjb_j avoids X∪{a}⊇XjX \cup \{a\} \supseteq X_j. So the failed bjb_j of that rule is XjX_j-provable, a contradiction. So aa is not XX-provable.

    When low≥k\mathit{low} \ge k, X=∅X = \emptyset, so a∉Ma \notin M, and line L13 keeps the invariant when it adds aa to failed. □\square

Termination

Lemma 3. Every call stops, and the stack never holds more than nn atoms, where nn is the number of atoms of PP.

Proof. Line L6 pushes aa only after line L5 found that aa is not on SS, so the atoms on SS are distinct and the recursion depth is at most n+1n + 1. Each call makes at most one inner call for each body atom of each rule of aa. So the tree of calls is finite. □\square

Theorem

BACKWARD-CHAIN(P,g)(P, g) stops, and it returns true exactly when g∈Mg \in M. This holds also when the memo tables are kept from earlier goals.

Proof. The run stops by Lemma 3. The top call runs with the empty stack. If it returns true, g∈Mg \in M by Lemma 2. If it returns (false,l)(\mathit{false}, l), then gg is not XX-provable for X=∅X = \emptyset, so g∉Mg \notin M. Lemma 2 does not depend on the content of the memo tables at the start, only on the invariant, which holds for the empty tables and is kept by every call. ■\blacksquare

Why a failure under a loop is not stored

If line L14 stored aa as failed, the invariant would break. In the program g←qg \leftarrow q, g←sg \leftarrow s, q←gq \leftarrow g, ss, the call PROVE(q)(q) inside PROVE(g)(g) meets gg on the stack and fails with low=0<1\mathit{low} = 0 < 1. But q∈Mq \in M, because g∈Mg \in M through ss. The procedure stores nothing for qq, and a later query for qq succeeds.

Complexity

The stack holds at most nn distinct atoms, so the recursion depth is at most n+1n + 1, and each call makes at most one inner call for each atom occurrence in the rules of its goal. So the number of calls is at most O(sn+1)O(s^{n+1}), and the extra space is O(n)O(n) for the stack and the memo tables. The worst case is exponential. In the rules ai←aja_i \leftarrow a_j for all i≠ji \ne j among nn atoms, with no facts, every failure meets a goal deeper in the stack, so line L14 stores nothing, and the search walks every simple path from a1a_1. The number of calls is at least (n−1)!(n-1)!; the implementation makes 11743 calls for n=7n = 7. A goal that is a fact is decided in O(1)O(1) time.

The problem has better algorithms. Forward chaining with counters decides g∈Mg \in M in time linear in the size of PP. SLG resolution (tabling) keeps the goal-directed search but stores answers in tables, which makes it polynomial. With variables, the question whether an atom follows from a Datalog program is EXPTIME-complete in combined complexity; see Datalog evaluation.

Properties

  • Goal directed. Only rules that can help with the goal, or with its subgoals, are ever looked at.
  • Sound and complete for propositional definite rules, with the loop check. Without it, the search does not stop on a rule such as a←aa \leftarrow a.
  • Order dependent cost. The answer does not depend on the order of the rules or of the body atoms, but the number of calls does.
  • Explainable. The stack at each moment is a chain of reasons, which is why MYCIN could answer the user's question "why do you ask this?".

Variants and improvements

  • Variables. Rules with variables need unification, and the search becomes SLD resolution. Prolog uses it with leftmost selection and without a loop check, so it can run forever on left-recursive rules.
  • Tabling. SLG resolution stores the answers of each subgoal and suspends a goal that loops, in place of failing it. This removes the exponential repetition and also handles negation with the well-founded semantics.
  • Negation as failure. A condition not c\mathit{not}\ c succeeds when the proof of cc fails finitely; see negation as failure.
  • Askable facts. MYCIN and EMYCIN asked the user for the value of a goal that no rule concludes, and combined the answers with certainty factors.
  • Bottom-up with goal focus. The magic sets rewriting lets forward chaining compute only the facts that a backward search would need.

When to use it

Use backward chaining when there is one question, or a few, and most of the rules are irrelevant to it, as in diagnosis and consultation systems that ask the user for data only when a rule needs it. Use forward chaining when new data must trigger all of its consequences, or when the worst case matters.

Pitfalls

  • No loop check. A left-recursive rule such as a←a,ba \leftarrow a, b makes a plain depth-first search run forever.
  • Storing every failure. A failure that met an open goal is only a failure for the current stack. Storing it as a plain failure makes the search incomplete, as the program g←qg \leftarrow q, g←sg \leftarrow s, q←gq \leftarrow g, ss shows: qq fails inside gg, but q∈Mq \in M.
  • Repeated work. Without memo tables the same subgoal is proved again in every place where it occurs, and even with them the loop case can be exponential.
  • Asking too much. In a consultation system the order of the rules decides which questions the user sees and in which order.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

backward_chaining.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Backward chaining for the page https://algorithm.tamnd.com/backward-chaining/. The authors are listed in prov/.
"""Backward chaining over propositional definite rules, with a loop check and memo tables.

A rule is (head, body): head is an atom and body is a tuple of atoms. A fact is
a rule with an empty body. Atoms are any hashable values. The search proves a
goal depth first: to prove an atom, try its rules in the given order and prove
the body atoms from left to right. An atom that is already on the current goal
stack is not tried again (the loop check). Atoms that were proved are stored.
An atom whose failure did not depend on an atom of the stack above it is stored
as failed; other failures are not stored, because the same atom can succeed
later from another stack.

BackwardChainer(rules).prove(goal) returns True exactly when goal is in the
least model. The field calls counts the calls of the inner procedure.
"""

INF = float("inf")


class BackwardChainer:
    def __init__(self, rules):
        self.rules = {}
        for head, body in rules:
            self.rules.setdefault(head, []).append(tuple(body))
        self.proved = set()  # @line L1
        self.failed = set()
        self.depth = {}  # the atoms on the goal stack, with their depths
        self.calls = 0
        self.trace = []

    def prove(self, goal):
        return self._prove(goal)[0]  # @line L2

    def _prove(self, a):
        """Return (ok, low): low is the smallest stack depth of an atom that a loop check met, or INF."""
        self.calls += 1
        if a in self.proved:  # @line L3
            self.trace.append(("memo true", a))
            return True, INF
        if a in self.failed:  # @line L4
            self.trace.append(("memo false", a))
            return False, INF
        if a in self.depth:  # @line L5
            self.trace.append(("loop", a))
            return False, self.depth[a]
        k = len(self.depth)  # @line L6
        self.depth[a] = k
        low = INF
        for body in self.rules.get(a, []):  # @line L7
            ok = True
            for b in body:  # @line L8
                ok, c = self._prove(b)  # @line L9
                low = min(low, c)
                if not ok:  # @line L10
                    break
            if ok:
                del self.depth[a]  # @line L11
                self.proved.add(a)
                self.trace.append(("proved", a))
                return True, INF
        del self.depth[a]  # @line L12
        if low >= k:  # @line L13
            self.failed.add(a)
            self.trace.append(("failed", a))
            return False, INF
        self.trace.append(("failed for now", a))
        return False, low  # @line L14


def backward_chain(rules, goal):
    """True exactly when goal follows from the definite rules."""
    return BackwardChainer(rules).prove(goal)
test_backward_chaining.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/backward-chaining/. The authors are listed in prov/.

import random
import unittest
from itertools import combinations

from backward_chaining import BackwardChainer, backward_chain


def least_model_brute(rules):
    """The smallest set of atoms that is closed under every rule, by brute force over all subsets."""
    base = sorted({h for h, _ in rules} | {b for _, body in rules for b in body})
    assert len(base) <= 12
    for k in range(len(base) + 1):
        for subset in combinations(base, k):
            s = set(subset)
            if all(h in s for h, body in rules if all(b in s for b in body)):
                return s
    raise AssertionError("the full base is always closed")


def random_rules(rng, n_atoms, n_rules):
    rules = []
    for _ in range(n_rules):
        head = rng.randrange(n_atoms)
        body = tuple(rng.choice(range(n_atoms)) for _ in range(rng.choice([0, 1, 1, 2, 2, 3])))
        rules.append((head, body))
    return rules


def complete_graph(n):
    """a_i <- a_j for every i != j, and no facts: nothing is provable."""
    return [(i, (j,)) for i in range(n) for j in range(n) if i != j]


class TestBackwardChaining(unittest.TestCase):
    def test_page_example(self):
        rules = [("g", ("d",)), ("d", ("d",)), ("g", ("a", "b")), ("a", ("g",)), ("a", ("c",)), ("b", ("a",)), ("c", ())]
        bc = BackwardChainer(rules)
        self.assertTrue(bc.prove("g"))
        self.assertEqual(
            bc.trace,
            [
                ("loop", "d"),
                ("failed", "d"),
                ("loop", "g"),
                ("proved", "c"),
                ("proved", "a"),
                ("memo true", "a"),
                ("proved", "b"),
                ("proved", "g"),
            ],
        )
        self.assertEqual(bc.failed, {"d"})
        self.assertFalse(bc.prove("d"))

    def test_conditional_failure_is_not_stored(self):
        # From the goal g, q fails because its only route goes back to g, which is on the stack.
        # Later q is asked again from the top and must succeed through g.
        rules = [("g", ("q",)), ("g", ("s",)), ("q", ("g",)), ("s", ())]
        bc = BackwardChainer(rules)
        self.assertTrue(bc.prove("g"))
        self.assertNotIn("q", bc.failed)
        self.assertTrue(bc.prove("q"))

    def test_random_against_least_model(self):
        rng = random.Random(20261115)
        for _ in range(600):
            n = rng.randint(1, 9)
            rules = random_rules(rng, n, rng.randint(0, 14))
            m = least_model_brute(rules)
            shared = BackwardChainer(rules)
            for a in range(n):
                self.assertEqual(backward_chain(rules, a), a in m)
                self.assertEqual(shared.prove(a), a in m)
                self.assertTrue(shared.proved <= m)
                self.assertFalse(shared.failed & m)
                self.assertEqual(shared.depth, {})

    def test_complete_graph_is_exponential(self):
        counts = []
        for n in range(2, 8):
            bc = BackwardChainer(complete_graph(n))
            self.assertFalse(bc.prove(0))
            counts.append(bc.calls)
        self.assertEqual(counts, [3, 11, 49, 261, 1631, 11743])
        for n, c in zip(range(2, 8), counts):
            f = 1
            for i in range(2, n):
                f *= i
            self.assertGreaterEqual(c, f)


if __name__ == "__main__":
    unittest.main()

History

Goal-directed search over rules goes back to the early theorem provers and to Kowalski's procedural reading of Horn clauses (1974), the base of Prolog. Shortliffe's MYCIN (1976) made backward chaining the control method of medical expert systems, and EMYCIN made it a shell for other domains; Buchanan and Shortliffe (1984) collect the work. Tabled resolution, which removes the repeated work, came in the 1990s with SLG resolution of Chen and Warren.

References

  1. Stuart Russell and Peter Norvig, Artificial Intelligence, A Modern Approach, third edition, Prentice Hall (2010), Chapter 7 (backward chaining for propositional definite clauses) and Chapter 9 (backward chaining with variables and logic programming)
  2. Bruce G. Buchanan and Edward H. Shortliffe (eds.), Rule-Based Expert Systems, The MYCIN Experiments of the Stanford Heuristic Programming Project, Addison-Wesley (1984), the chapters on the MYCIN consultation program and its goal-directed control
  3. John W. Lloyd, Foundations of Logic Programming, second edition, Springer (1987), the chapters on SLD resolution, the least Herbrand model and the soundness and completeness of SLD resolution

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example