All predicatesShow sourceprolog_auto_table.pl -- Automatic tabling

This library provides the XSB compatible directive auto_table/0, which tables enough predicates of the file in which it appears to make sure that every cycle in the static call graph of the file contains a tabled predicate. It uses library(prolog_call_cycles) to find the recursion in the static call graph of the file. In addition, auto_table_learn/3 learns which predicates to table and in which mode by running goals.

For each strongly connected component of the call graph, the analysis selects a set of predicates to table such that removing these predicates breaks all cycles (a feedback vertex set). Among the possible sets it chooses the one with the lowest estimated number of tabled variants. This estimate is based on how the predicates are called inside the component: calls with fresh variables or ground arguments create few variants, while calls with arguments that are built from data, notably accumulators, create many. Left recursion (recursion where no call to a non-built-in predicate precedes the recursive call) is always reported, as it is guaranteed to loop under Prolog's SLD resolution.

Like XSB, a predicate is also tabled if it is called through tnot/1.

A tabled goal that waits for an incomplete table suspends by capturing its continuation using shift/1. It cannot do so through findall/3 and the other predicates that collect all solutions, aggregate_all/3 or a predicate defined in C (see the barrier key of call_graph_sccs/2). Recursion through such a predicate is therefore not tabled: if its call passes a proper subterm or a computed value of the head it is assumed to terminate, otherwise nothing in the strongly connected component is tabled and auto_table/0 prints a warning.

The analysis is static. Calls through meta-calls that cannot be resolved at compile time are not seen. Tabling guarantees termination only if the number of call variants and answers is finite.

Source auto_table is det
Source auto_table(+Options) is det
Directive that tables predicates of the current file such that each loop in the static call graph of the file contains at least one tabled predicate. The analysis is performed after the file has been loaded completely. Options:
cycles(+Which)
One of all (default) or left. If left, only left recursive cycles are broken.
structural(+Bool)
If true (default false), assume that directly recursive calls on a proper subterm of an argument of the head terminate. This is true if the argument is sufficiently instantiated when the predicate is called. Without this option, this is only assumed if a mode declaration says the argument is input (+ or ++). Mode declarations are given using mode/1 or using PlDoc structured comments, e.g. `%! len(+List, -Len)`.
verbose(+Bool)
If true (default), print a message for each predicate that is tabled.

When the file is reloaded, the predicates tabled by the previous analysis are untabled before the new analysis is performed.

Compatibility
- XSB. XSB only provides auto_table/0. As with XSB, :- mode declarations avoid tabling directly recursive predicates whose recursion decreases an input argument. The XSB dialect maps XSB :- mode declarations to mode/1.
Source auto_table_file(+File, +Module, +Options) is det[private]
Analyse File and table the predicates selected by the analysis.
Source auto_table_analysis(:Spec, -Analysis:dict, +Options) is det
Determine the predicates to table for Spec, which is one of file(File), module(Module) or goal(Goal). The latter analyses the predicates reachable from Goal. The options files(FileOrFiles) and module(ModuleOrModules) restrict these to the predicates defined in the given files or modules (see call_graph/2). Analysis is a dict with the keys below. Options are those of auto_table/1 plus the options of call_graph/2.
selected
List of PI-Reason for each predicate that must be tabled, where Reason is one of tnot or cycle.
sccs
List of dicts describing each strongly connected component, holding the keys members, tabled (predicates in the SCC that were already tabled), selected (predicates selected for tabling), cost (estimated cost of the selection), left_recursion (list of left recursion dicts, see left_recursion/3), terminating (directly recursive predicates that are not tabled because their recursion is known to terminate), barriers (edges through a barrier for suspending a tabled goal that are not known to terminate; if this is not empty, nothing is selected) and cuts (if the SCC contains tabled predicates, the edges of the SCC whose call can be pruned by a cut, which raises an error if the call is to an incomplete table; see the pruned key of call_graph_sccs/2).
Source tnot_called(+Graph, -PIs) is det[private]
PIs is the set of predicates in scope that are called through tnot/1 and are not yet tabled.
Source analyse_scc(+Options, +TNot, +ModeDB, +SCC, -Result) is det[private]
Source barrier_edge(+Edge) is semidet[private]
True if the call of Edge is made through a barrier for suspending a tabled goal, e.g., findall/3. A cycle through it cannot be broken by tabling: a tabled goal in it that waits for an incomplete table raises an error.
Source progress_edge(+Edge) is semidet[private]
True if the call of Edge passes a proper subterm or a computed value of the head, so the recursion through it is assumed to terminate.
Source illegal_cuts(+SCC, +Tabled, +TNot, +Selected, -Cuts) is det[private]
If the SCC contains tabled predicates, Cuts is the list of edges in the SCC whose call can be pruned by a cut. Each tabled predicate is reachable from every call in the SCC, so such a cut may prune a call to an incomplete table, which raises a permission error.
Source terminating_edge(+Structural, +ModeDB, +Edge) is semidet[private]
True if Edge is a directly recursive call that decreases an argument that is declared as input (+ or ++) by a mode declaration (see mode_db/3). If Structural is true, any directly recursive call that decreases an argument is considered terminating.
Source mode_terminating(+ModeDB, +Edge) is semidet[private]
True if the predicate has mode declarations and, for each of them, Edge passes a proper subterm of the head at an input argument.
Source mode_db(+Structural, +SCCs, -ModeDB) is det[private]
ModeDB is an assoc mapping the directly recursive predicates of SCCs that recurse on a proper subterm to their mode declarations, a non-empty list of terms Name(Ind, ...), where Ind is a mode indicator such as +, - or ?. Mode declarations are taken from the first of these sources that provides them:
  1. A mode/1 declaration, as reported by the predicate property mode(Head). This also covers XSB :- mode declarations (see library(dialect/xsb)).
  2. PlDoc structured comments. If PlDoc was active while loading, these are available as '$mode'/2 facts. Otherwise the source file is cross-referenced using xref_source/2.
Source xref_modes(+PIs, -Pairs) is det[private]
Find PlDoc mode declarations for PIs by cross-referencing the files that define them. Files that were not cross-referenced before are cleaned afterwards.
Source node_costs(+Nodes, +Edges, -Costs) is det[private]
Costs is an assoc mapping each node to a cost term c(Variants, NotExported, Arity). Variants estimates the number of tabled variants if this node is tabled, based on the argument abstraction of the calls to the node. The other two fields implement XSB's tie breaking: prefer exported predicates and predicates with a low arity.
Source feedback_vertex_set(+Nodes, +Edges, +Costs, -FVS, -Cost) is det[private]
Find a set of nodes FVS with minimal total Cost such that the graph Nodes/Edges without FVS has no cycles. We use branch and bound: find a shortest cycle in the remaining graph; one of its nodes must be in the FVS. If the search exceeds its budget we use the best solution found so far, starting with a greedy one.
Source greedy_fvs(+Graph, +Costs, -FVS) is det[private]
Greedy approximation: repeatedly remove the node of a cycle that has the best ratio between the number of edges it is involved in and its cost, then remove redundant nodes.
Source reduce_graph(+Graph0, -Graph) is det[private]
Remove vertices without incoming or outgoing edges, as they cannot be part of a cycle.
Source find_cycle(+Graph, -Cycle) is semidet[private]
Find a shortest cycle in Graph. Cycle is a list of vertices.
Source auto_table_learn(:Goals, +Options) is det
Source auto_table_learn(:Goals, -Result:dict, +Options) is det
Run Goals (a goal or list of goals) to learn which predicates must be tabled. The first phase runs Goals without (additional) tabling while observing the recursion: a call that is a variant of one of its ancestors is a loop. Such a call is recorded and fails, so the run continues. This also finds recursion that is not visible to the static analysis, such as recursion through meta-calls or recursion in the data interpreted by a meta-interpreter. The observed loops are combined into a graph for which we compute a feedback vertex set using the observed number of call variants as cost.

auto_table_learn/2 prints the result. Options:

modules(+Modules)
Observe the predicates of the given modules. Default are all modules of class user.
predicates(+PIs)
Observe the given predicates.
time_limit(+Seconds)
Time limit for each run of a goal. Default 60. This option is ignored if library(time) is not available, which is the case in single threaded versions and WASM.
inference_limit(+Count)
Inference limit for each run of a goal. Default infinite.
max_depth(+Depth)
Treat recursion deeper than Depth as a loop. Default 10,000.
ancestor_depth(+Depth)
Only check the nearest Depth ancestors for variants. Default 1,000.
hot(+Count)
Report statistics for the Count predicates with the most call variants. Default 10.
search(+Bool)
If true (default), run the second phase (see below).
objective(+Objective)
What to optimise in the second phase. One of time (CPU time), memory (table space) or balanced (default, the sum of both relative to the initial configuration).
max_runs(+Count)
Maximum number of configurations to try. Default 50.
modes(+Modes)
Tabling modes to try. Default [variant,subsumptive].
apply(+Bool)
If true, leave the program tabled according to the best configuration. Default false, restoring the original tabling.
output(+File)
Write the table directives for the best configuration to File.

The second phase searches for the best configuration, a mapping from predicates to variant, subsumptive or not tabled. It starts with the predicates that were already tabled plus the selected predicates of the first phase. Each configuration is evaluated by running Goals with fresh tables, measuring CPU time and table space. A configuration is rejected if a goal does not complete or produces different answers than the initial configuration. If the initial configuration fails, e.g., because a cut prunes a call to an incomplete table, the search starts from the original tabling. If that fails too, the best configuration is the original tabling. The search moves are: untable all tabled predicates that are not involved in any observed loop (if this fails, try halves), untable a single predicate, switch between variant and subsumptive tabling, and table a predicate that is often called with the same arguments.

Result is a dict with the keys below.

selected
List of predicates that must be tabled to break all observed loops.
loops
List of observed loops. Each loop is a list of predicate indicators.
barrier_loops
List of Loop-Barrier for the observed loops that pass a barrier for suspending a tabled goal, such as findall/3 or a predicate defined in C (see shift/1). Tabling cannot break these loops, so their predicates are not selected.
predicates
List of dicts with statistics for each predicate that is involved in a loop. Keys are pi, calls, variants, args (number of distinct values per argument), tabled (whether the predicate was already tabled) and loops (number of loop detections).
goals
List of Goal-Status, where Status is the result of running the goal: true, false, time_limit_exceeded, inference_limit_exceeded or an error.
hot
Statistics for the predicates with the most call variants.
config
The best configuration found by the second phase, a list of PI-Mode, where Mode is variant or subsumptive.
runs
List of dicts describing each configuration that was tried.
directives
List of table directives for the best configuration.
Source candidate_predicates(+Options, -PIs) is det[private]
Find the predicates we observe while learning.
Source discover(+Goals, +Candidates, -Discovery, +Options) is det[private]
Run Goals with all Candidates wrapped to observe the recursion.
Source ancestor_variant(+Stack, +I, +Head, +MaxCheck, -Path, -Frame) is semidet[private]
True if Stack contains a call to predicate I that is a variant of Head. Path is the list of predicate indexes from that ancestor to the current call and Frame is the frame that runs the ancestor.
Source frame_barrier(+Frame, +AncFrame, -Barrier) is semidet[private]
True if a frame between Frame and its ancestor AncFrame runs a barrier for suspending a tabled goal (see shift/1): a predicate with the attribute shift_barrier, such as findall/3, or a predicate defined in C that called Prolog. Barrier is its predicate indicator.
Source deep_loop(+Stack, +I, +State, +Loops)[private]
The recursion exceeded max_depth. Record the shortest repeating sequence of predicates on top of the stack as a loop.
Source canonical_cycle(+PIs, -Cycle) is det[private]
Rotate a cycle such that it starts with its smallest element and remove the duplicate end.
Source run_goal(+Limits, :Goal, -Status) is det[private]
Source limits(+Options, -Limits) is det[private]
Limits is a term limits(Time, Inferences) holding the limits for a single run of a goal. Each is a number or infinite.
Source call_with_limits(+Limits, :Goal)[private]
Run Goal as once/1 subject to Limits (see limits/2). Raises the exception time_limit_exceeded or inference_limit_exceeded if a limit is exceeded.
Source scale_limits(+Limits0, +Run, -Limits) is det[private]
Limit a run of a new configuration to three times the time and inferences used by Run, the best configuration so far.
Source loop_predicates(+Loops, +Candidates, +State, -Preds) is det[private]
Source hot_predicates(+State, +N, -Hot) is det[private]
Hot is a list of statistics dicts for the N predicates with the most call variants.
Source learned_selection(+Discovery, -Selected) is det[private]
Compute the predicates to table from the observed loops. Loops through predicates that are already tabled are considered broken. The predicates of a loop through a barrier for suspending a tabled goal (see frame_barrier/3) are not tabled, so the loops through them are not broken.
Source original_tabling(+Candidates, -Original, -Fixed) is det[private]
Original is a list of PI-t(Mode, Extra) for the tabled candidates we may change, where Mode is variant or subsumptive and Extra is a list of additional table options (incremental, shared, ...). Fixed is a list of tabled candidates we do not change: predicates with mode-directed tabling.
Source search(+Goals, +Result0, +Original, +Fixed, -Result, +Options)[private]
Source run_search(+Goals, +Initial, +Result0, +Fixed, +State, -Search)[private]
Hill climbing from the Initial configuration.
Source original_config(+State, -Config) is det[private]
Config is the configuration with the original tabling of the candidates.
Source inverse_moves(+Move, +OldConfig, -Inverse) is det[private]
Moves that undo Move. We do not try these after accepting Move.
Source accept(+Objective, +New, +Current, +Initial) is semidet[private]
True if we accept New over Current. This is the case if New is better or New is about as good and tables fewer predicates.
Source better(+Objective, +New, +Current, +Initial) is semidet[private]
True if New is better than Current. Time measurements need to improve by at least 5% to compensate for noise.
Source moves(+Config, +Ctx, -Moves) is det[private]
Generate the moves for Config, in the order we try them.
Source variant_order(+PIs, +Result, -Ordered) is det[private]
Order PIs by increasing number of observed call variants. Small tables are the cheapest to try removing.
Source table_space(-Count, -Bytes) is det[private]
Count the tables and the memory they use. We sum the sizes of the tables rather than using the table_space_used statistics because the space of abolished tables is not always reclaimed immediately. The size of a table includes its compiled answer representation.
Source apply_config(+Config, +State) is det[private]
Make the tabling of the predicates we manage agree with Config. The managed predicates are those in Config, those that were tabled originally and those of previously applied configurations.
Source directives(+Config, -Directives) is det[private]

Undocumented predicates

The following predicates are exported, but not or incorrectly documented.

Source auto_table(Arg1)
Source auto_table_learn(Arg1, Arg2, Arg3)