Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 40 ยท Unification and Backtracking

Tracing and Debugging Prolog: trace, spy, Ports and Error Messages

Debug Prolog programs with trace, spy and debug/3. Learn the four-port model (call, exit, redo, fail), read typical error messages and fix singleton and instantiation errors.

Sooner or later a Prolog program gives an answer you did not expect, or none. Because execution is a search, you cannot step through it like a loop. Prolog systems provide a tracer that shows every goal the engine tries, and learning to read it makes the search model from the last lessons concrete.

Prolog is read-only on this site, so the traces below show what SWI-Prolog prints (variable numbers such as _123 differ from run to run). The Python stand-in includes a four-port tracer you can run.

The four-port model

The classic Prolog debugger sees every predicate call as a box with four ports:

flowchart LR
    C["Call"] --> P["predicate"]
    P --> E["Exit"]
    F["Fail"] --- P
    R["Redo"] --> P
    P -.->|"no more clauses"| F

Control enters through Call or Redo and leaves through Exit or Fail.

Port When it fires
Call the goal is started for the first time
Exit the goal succeeded; control passes to the next goal
Redo a later goal failed, so we backtrack into this goal for another solution
Fail the goal has no (more) solutions; control goes back to the previous goal

A goal that succeeds twice is entered once through Call, left through Exit, re-entered through Redo, left through Exit, re-entered through Redo again, and finally leaves through Fail.

Tracing with trace/0

PROLOG
parent(tom, bob).
parent(bob, ann).
parent(bob, pat).
grandparent(X, Z) :- parent(X, Y), parent(Y, Z).
PROLOG
?- trace, grandparent(tom, W).
   Call: (12) grandparent(tom, _10) ? creep
   Call: (13) parent(tom, _20) ? creep
   Exit: (13) parent(tom, bob) ? creep
   Call: (13) parent(bob, _10) ? creep
   Exit: (13) parent(bob, ann) ? creep
   Exit: (12) grandparent(tom, ann) ? creep
W = ann ;
   Redo: (13) parent(bob, _10) ? creep
   Exit: (13) parent(bob, pat) ? creep
   Exit: (12) grandparent(tom, pat) ? creep
W = pat.

The number in parentheses is the recursion depth of the call. At each step the tracer asks ? and waits: press Enter or c ("creep") to go one step, s to skip the sub-computation of this goal, l to leap to the next spy point, a to abort, n to end tracing, and h for help. Use notrace. (or nodebug.) to turn tracing off. Reading the lines top to bottom reproduces the search tree: parent(tom, Y) called, exited with bob, then parent(bob, W); and the Redo line shows backtracking into parent(bob, W) for the second answer.

Spy points

Tracing everything creates too much noise. Put a spy point on one predicate and let the program run until it reaches it:

PROLOG
?- spy(parent/2).
% Spy point on parent/2
?- grandparent(tom, W).

Now the debugger stops only at calls of parent/2. Remove it with nospy(parent/2). or all spies with nospyall. With leash(-all) you ask the tracer not to stop at ports, so it prints the trace without waiting.

debug/3: leave messages in your code

For permanent diagnostics add debug/3 calls. They print only when the topic is enabled, so they cost nothing otherwise:

PROLOG
grandparent(X, Z) :-
    parent(X, Y),
    debug(family, "middle person is ~w", [Y]),
    parent(Y, Z).
PROLOG
?- debug(family).
true.

?- grandparent(tom, W).
% middle person is bob
W = ann ;
% middle person is bob
W = pat.

Turn it off again with nodebug(family). The related assertion(Goal) raises an error with a backtrace when a condition you believed true is false; use it to document invariants.

Plain format or print_message lines also work, with the drawback that you must delete them later. For nested terms print/1 and portray_clause/1 produce readable output: portray_clause(foo(X, Y, bar(X))) prints foo(A, B, bar(A)). with variables renamed to letters.

Reading error messages

Most errors have three parts: an error type, the culprit and context. The ones you will see most:

Message Meaning and usual cause
Unknown procedure: foo/2 no clauses for foo/2: typo, wrong arity or file not loaded
Arguments are not sufficiently instantiated a variable reached is or a comparison before it was bound: reorder goals
Type error: evaluable expected, found foo/0 or ...integer expected wrong kind of value in arithmetic
No permission to modify static procedure you defined a built-in such as append/3 in a way that collides; rename or use :- redefine_system_predicate only if you must
Syntax error: Operator expected missing full stop, comma or a space between functor and (
Stack limit exceeded runaway recursion; see search trees
Warning: Singleton variables: [X] variable used once in a clause: often a typo
Warning: Clauses of foo/2 are not together discontiguous clauses; group them or declare :- discontiguous foo/2.

Example:

PROLOG
?- X is Y + 1.
ERROR: Arguments are not sufficiently instantiated

The fix is to give Y a value first: Y = 4, X is Y + 1.

A debugging checklist

  1. Test the smallest goal at the prompt first. Call each helper predicate alone.
  2. Check the database with listing(name/arity).
  3. Trace only the failing query, with a spy on the predicate you suspect.
  4. Look for Fail lines where you expected Exit. The goal printed just before the first unexpected Fail is usually the culprit.
  5. Compare the arguments printed at Call with what you assumed (wrong order is very common).
  6. Check the clause order and base cases, then add facts that make the failing case simple.

Try it: a four-port tracer

This stand-in prints the same four ports for the family program. Every line begins with the depth (indentation). Compare it with the real trace above.

Python Call, Exit, Redo and Fail (mini-Prolog stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The final Fail lines appear after all answers have been found: Prolog still had to confirm there were no more. Notice that Redo: parent(bob,_Z) appears between the two answers: that is the second answer being fetched by backtracking.

Try it: a mistake and its fix

A common bug is a comparison before a binding. In real Prolog it raises an instantiation error; the stand-in reproduces the situation by raising its own error.

Python Wrong goal order (mini-Prolog stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which port fires when Prolog backtracks into a goal to find another solution?

    Redo re-enters a goal that may have more solutions after a later failure.
  2. 2. How do you turn tracing on and off?

    trace/0 starts the tracer, notrace/0 stops it. spy/1 sets a breakpoint on one predicate.
  3. 3. What usually causes 'Arguments are not sufficiently instantiated'?

    is/2 and comparison operators need bound variables on the evaluated side. Reorder the goals so a generator runs first.
  4. 4. What is debug/3 good for?

    debug(Topic, Format, Args) is silent unless debug(Topic) was called, so you can leave it in the code.

Summary

  • The tracer shows the Call, Exit, Redo and Fail ports of every goal; trace/0 starts it, spy/1 stops only at chosen predicates.
  • Read a trace top to bottom to follow the search tree; a Fail where you expected Exit is the clue.
  • debug/3, listing/1, portray_clause/1 and assertion/1 are the everyday helpers.
  • Learn the common errors: unknown procedure, instantiation, type, syntax, stack limit and singleton warnings.

Next: Recursion in Prolog