Forward chaining: facts, queues and justified conclusions
前向链推理
Compute a least model with indexed rule counters, inspect each proof, and distinguish unfinished work from a query that is not entailed.
forward-chainingAn order is packed. What follows from that fact?
Consider a hypothetical fulfillment desk with two recorded facts: an order exists and stock is available. Its rules say that an order with stock is packed, a packed order with a label is ready, and a ready order has its notification recorded. A separate unconditional rule provides the label. What can this small rulebook establish without guessing anything else?
Forward chaining starts from established facts and applies rules whose conditions have all been established. Newly derived facts can enable more rules. In our desk example, packed enables ready, which enables notified. These symbols describe a simplified logical snapshot. Computing notified does not send a message, move a box or verify a warehouse sensor.
The interesting cases are the gaps and loops. A rule manual → ready cannot establish manual merely because ready was derived. Two rules a → b and b → a, with neither fact available, establish neither atom. A loop can carry an existing justification; it cannot manufacture its own starting evidence.
The executable model below keeps the work queue, unfinished-condition counts and first justification for each atom. It answers both “has this query been proved?” and “has this run finished processing every discovered fact?” Those are separate questions when a computation budget interrupts the queue.
Positive rules, a closure and the least model
Let U be the finite set of atom names occurring in the input. Facts F are positive atoms. Each rule has a body B, a finite set of positive atoms, and one positive head h. It asserts
An empty body is true, so an empty-body rule asserts its head unconditionally. Repeating a body atom changes nothing: a AND a means a. This is the propositional definite-clause fragment, with exactly one positive literal per clause. A general Horn clause may have no positive literal; that additional case can express a constraint and is outside this program’s input language. Poole and Mackworth, §5.3
For a current fact set S, define one simultaneous consequence step and its iteration:
These sets only grow. At most the number of distinct input atoms can be added before growth stops. Call the resulting set C. The queue implementation reaches this same closure by handling individual events instead of scanning every rule in rounds. Its intermediate discovery order need not equal the order of the simultaneous sets above.
Why trust a derived atom? Use induction on its first justification. An input fact is a premise. An empty-body head is itself an unconditional premise. Otherwise all parents already have justifications, and the rule’s implication establishes the head in every model of the input. Every discovered atom is therefore a logical consequence, even before the run finishes.
To check what a completed run has missed, assign true to exactly C and false to the other atoms in U. Every fact is true. If a rule’s whole body is true, its head belongs to C because closure has finished. Thus this assignment is a model. Furthermore, the induction above puts every member of C in every model. C is the least model under set inclusion, not merely one model with few true atoms.
Consequently, for an atomic query q, including a fresh name assigned false in this least-model extension,
If q is absent, this model is a concrete countermodel to entailment. That does not establish the negative claim “q is false in the real desk.” Indeed, setting every atom true satisfies every definite rule and fact, so positive definite clauses alone never require an atom to be false. The textbook distinguishes a failed entailment query from knowledge of falsity and gives the least-model argument in §§5.3.1–5.3.2.
This completeness statement concerns positive atomic queries, and hence conjunctions checked atom by atom, over this particular fragment. The program does not parse arbitrary propositional formulas, perform contraposition from negative facts, or establish every formula expressible in propositional logic.
Process each fact once and retain its reason
For every atom, waiting lists the rules containing it in their normalized bodies. remaining[i] starts at that body’s size. A newly discovered atom enters a FIFO queue once. Removing it from the queue decrements only the counters in its waiting list. When a counter reaches zero, that rule fires; its head enters the queue only if it is new.
The counter measures conditions whose queue events have not been processed, rather than conditions not yet known. If P is the set of processed atoms, the invariant is
All facts are discovered first, in input order; then empty-body rules fire in rule order. Waiting lists also follow rule order. fired records each rule reaching zero, including empty-body rules and rules whose heads were already known. proof retains only the first reason for each discovered atom. A rule may fire without adding another proof line.
The complete Python 3.10+ program uses only the standard library. Facts, rules, rule pairs and bodies must be lists or tuples; atom names must be nonempty, case-sensitive strings. The program treats not a or a AND b as one atom name, not syntax for negation or conjunction. It preserves input objects, removes duplicate body occurrences and repeated fact discoveries, and retains duplicate rules with distinct zero-based IDs.
max_pops bounds queue removals, not initialization, rule firings, wall time or total work. It must be a nonnegative integer or None; Booleans are rejected. The query does not change the schedule, and proving it does not stop the loop early. Each call starts afresh; this interface does not resume a saved state.
The three statuses mean: ENTAILED when the query has a recorded proof; NOT_ENTAILED when the queue has drained and the query is absent; UNKNOWN when it is absent but queue work remains. complete means the queue has drained. An interrupted run may already happen to contain the entire mathematical closure, but the interface conservatively reports unfinished processing until every event has been handled.
from collections import deque
def forward_chain(facts, rules, query, max_pops=None):
def atom(x):
if type(x) is not str or not x:
raise ValueError('atoms must be nonempty strings')
return x
def sequence(x):
if type(x) not in (list, tuple):
raise ValueError('use a list or tuple')
return x
atom(query)
if max_pops is not None and (type(max_pops) is not int or max_pops < 0):
raise ValueError('max_pops must be a nonnegative integer or None')
initial = tuple(atom(x) for x in sequence(facts))
normalized = []
for row in sequence(rules):
if len(sequence(row)) != 2:
raise ValueError('a rule is (body, head)')
body, head = row
body = tuple(dict.fromkeys(atom(x) for x in sequence(body)))
normalized.append((body, atom(head)))
waiting, remaining = {}, []
for i, (body, _) in enumerate(normalized):
remaining.append(len(body))
for p in body:
waiting.setdefault(p, []).append(i)
agenda, proof, reasons = deque(), [], {}
processed, fired, visits = [], [], 0
def discover(p, rule_id, parents):
if p in reasons:
return
reasons[p] = (rule_id, parents)
proof.append((p, rule_id, parents))
agenda.append(p)
for p in initial:
discover(p, None, ())
for i, (body, head) in enumerate(normalized):
if not body:
fired.append(i)
discover(head, i, ())
while agenda and (max_pops is None or len(processed) < max_pops):
p = agenda.popleft()
processed.append(p)
for i in waiting.get(p, ()):
visits += 1
remaining[i] -= 1
if remaining[i] == 0:
fired.append(i)
body, head = normalized[i]
discover(head, i, body)
complete = not agenda
status = ('ENTAILED' if query in reasons else
'NOT_ENTAILED' if complete else 'UNKNOWN')
return {'status': status, 'complete': complete, 'known': tuple(reasons),
'processed': tuple(processed), 'pending': tuple(agenda),
'remaining': tuple(remaining), 'fired': tuple(fired),
'visits': visits, 'proof': tuple(proof)}
FACTS = ('order', 'stock')
RULES = (
(('order', 'stock'), 'packed'),
(('packed', 'label'), 'ready'),
(('ready',), 'notified'),
(('notified',), 'ready'),
((), 'label'),
(('manual',), 'ready'),
(('ready',), 'ready'),
)
if __name__ == '__main__':
for cap in (0, 2, 4, 6):
result = forward_chain(FACTS, RULES, 'notified', cap)
print(cap, result['status'], result['complete'],
len(result['processed']), result['visits'], result['known'])
full = forward_chain(FACTS, RULES, 'manual')
print('manual:', full['status'], full['remaining'], full['fired'])
print('proof:', full['proof'])
print('no seed:', forward_chain([], [(('a',), 'b'), (('b',), 'a')], 'a')['status'])
The counter-and-dependency idea has a direct research reference: Dowling and Gallier’s 1984 paper, §4 and Algorithm 2, presents linear-time Horn satisfiability procedures with explicit representation assumptions. Their language also handles clauses without a positive head. Our program computes positive definite consequences and supplies a finite teaching trace; it is not a transcription of their Pascal procedure.
The AIMA Python implementation at a fixed commit offers another comparison. Its pl_fc_entails uses counts and an agenda, while clauses_with_premise recomputes the relevant list by scanning clauses. This chapter builds that dependency index once, uses FIFO discovery and exposes proofs and budget status. The upstream code and MIT license were read; the upstream implementation and tests were not run or copied.
Let f count input fact occurrences, r count rules, n count distinct input atoms and L count body occurrences before deduplication. Assuming constant-time atom operations and expected constant-time Python hash-table operations, building the index and completing the run take expected time. Every atom is popped at most once, every normalized body occurrence is visited at most once, and every rule fires at most once. Storage, including normalized input and trace, is references/counters. This is not a worst-case bound for hostile hash collisions or arbitrarily long names: parsing, hashing and comparing name characters add their own cost. The original paper likewise states its indexed-symbol assumption explicitly in §4.2.
A proof can finish before the queue does
Here the symbols mean: order = order recorded, stock = stock available, packed = packing recorded, label = label available, ready = ready status recorded, notified = notification recorded, and manual = manual approval recorded. The seven rules in the program are a teaching policy, not a claim about real fulfillment processes.
The two facts and empty-body rule first discover order, stock, label. Processing order leaves rule 0 waiting for stock. Processing stock discovers packed. Processing label still leaves rule 1 waiting for the queued packed event. Processing packed discovers ready; processing ready discovers notified and fires the harmless self-rule. Finally notified fires the back-edge to the already known ready.
For query notified, the counts are:
| Pop cap | Verdict | Queue drained? | Pops | Body visits |
|---|---|---|---|---|
| 0 | UNKNOWN | No | 0 | 0 |
| 2 | UNKNOWN | No | 2 | 2 |
| 4 | UNKNOWN | No | 4 | 4 |
| 5 | ENTAILED | No | 5 | 6 |
| 6 | ENTAILED | Yes | 6 | 7 |
At cap 5, the proof of notified already exists, but its outgoing event is still queued. Query manual on that same prefix returns UNKNOWN; at cap 6 it returns NOT_ENTAILED. There are eight normalized body occurrences overall, but only seven are visited, because manual is never processed. Full fired order is (4, 0, 1, 2, 6, 3); rule 5 keeps count 1.
The proof output has six lines in discovery order. The first two cite input facts; label cites rule 4 with no parents; packed cites rule 0 and parents order, stock; ready cites rule 1 and parents packed, label; notified cites rule 2 and parent ready. Every nonempty reason points to earlier proof lines, so a separate checker can replay those justifications without trusting the queue counters.
Over these seven atom names, the rulebook has exactly two classical models: the six derived atoms are true in both, while manual may be false or true. The least model selects false for manual only to witness that it is not entailed. Deleting the stock input and rerunning leaves exactly order and label derived. An explanation trace from the old run does not automatically retract itself when a premise is removed.
For a reproducible experiment, reverse a chain of n rules p0 → p1 → … → pn in the input and provide fact p0. The dependency index still gives exactly n body visits and n+1 pops. Compare a baseline that scans all rules repeatedly in that unfavorable order: it repeatedly examines rules whose conditions have not changed. Count operations rather than drawing timing conclusions from one tiny run.
Where this rulebook stops helping
Positive accumulation fits dependency checks and materialized deductions when the rules and observations are reliable and the task needs many consequences. If there is one narrow query in a large irrelevant rulebook, goal-directed backward reasoning may avoid unrelated work. Those methods need their own handling of recursion; a naïve recursive procedure can revisit the same unmet goal indefinitely. Their separate chapters are listed in the symbolic-reasoning catalogue.
The present proof record stores one justification, not all alternative proofs and not a shortest proof. It supports auditing the conclusion of this run, but does not solve deletion maintenance. If a premise disappears, a recorded reason may fail even though another valid reason survives. Recompute the closure for this small implementation; maintaining all affected supports is a different algorithm.
A rule engine that sends messages or changes inventory has effects beyond adding mathematical atoms. Repeated execution, timing, conflicting rules and failed actions require explicit application semantics. Likewise, treating “not derivable” as false is an additional closed-world convention, not a consequence of the classical entailment result above. Negative conditions or rule retraction cannot simply be inserted into this monotone counter procedure.
The finite propositional bound also does not transfer unchanged to rules with variables and term-building functions. A function can generate increasingly nested terms and an unbounded stream of ground facts; fair scheduling is needed to avoid starving other enabled work. Poole and Mackworth, §15.6.1 explains this boundary. Here strings are indivisible names: there is no grounding, matching variables or calling a general first-order prover.
Finally, forward chaining differs from forward checking in constraint search. This program adds justified propositions until closure. Forward checking removes incompatible variable values after a tentative assignment and may need to undo those removals during backtracking. Their similar names describe different states and correctness conditions.
Predict, trace and challenge the implementation
1. Change the query to label and set the pop cap to zero. Is the result UNKNOWN?
Answer: No. Initialization fires empty-body rule 4 and records label, so the verdict is ENTAILED, with complete=False, zero pops and zero body visits. A cap on queue removals does not suppress initial facts or empty-body rules.
2. Use fact a and two copies of the rule (a AND a) → b. How many discoveries and visits occur?
Answer: There are two atom discoveries, a then b, and two body visits. Each rule body normalizes to one occurrence of a; the two rules retain separate IDs and both fire when a is processed. Only the first provides b’s retained reason. Without deduplicating body occurrences consistently, a counter or waiting list could incorrectly leave the head blocked.
3. Does ready → notified together with notified → ready prove either atom by itself?
Answer: No. With no initial facts and no empty-body rules, the queue starts empty and the closure is empty. Assigning both atoms false satisfies both implications, giving a countermodel to either entailment. Add fact ready, and both become derivable; the first-discovery check prevents repeated enqueueing around the cycle.
4. At cap 5, manual is absent and every atom in the final closure has already been discovered. Why report UNKNOWN for manual?
Answer: The queue still contains notified, so this implementation has not certified completion of its event processing. Absence in an unfinished run is conservatively UNKNOWN. One more pop drains the queue and establishes NOT_ENTAILED. A separate fixed-point check could detect closure earlier, but this program does not perform one, and NOT_ENTAILED would still not mean that the desk’s manual approval is known false.
Check the proof and the missing-query countermodel
The repository tests use two separate references. One enumerates classical assignments and intersects all models; a completed closure must equal that intersection and must itself satisfy the rulebook. The other rescans every rule after each processed event, avoiding the implementation’s dependency index and decrementing counters. It compares the entire budget result, including pending events, rule IDs, visits and retained reasons.
The semantic cases include all 256 subsets of the eight possible definite rules over two atoms, each with four possible fact sets and three queries, including a fresh atom. A further 301 rulebooks containing at most two of the 24 possible three-atom rules are checked with all eight fact sets. Randomized cases add repeated body atoms, duplicate rules and reordered inputs. These finite checks accompany the general least-model argument; they are not a proof that an arbitrary rule engine or external action system is correct.
Make a prediction, then check
After5pops the desk has discovered notified, but its event is pending. What should querying manual return?
Learning objectives
- Construct a least model from positive definite rules, using all-true and missing-query countermodels to distinguish non-entailment from known falsity.
- Implement dependency indexing and event counters, audit first proofs, cycles, empty rules and budget prefixes, and state the cost model for expected linear work.
Prerequisites & connections
Explore related knowledge →References
- Artificial Intelligence: Foundations of Computational Agents, 3e — 5.3 Propositional Definite Clauses
David L. Poole; Alan K. Mackworth · 2023 - Linear-Time Algorithms for Testing the Satisfiability of Propositional Horn Formulae
William F. Dowling; Jean H. Gallier · 1984 - AIMA Python: PropDefiniteKB and pl_fc_entails
AIMA Python contributors - Artificial Intelligence: Foundations of Computational Agents, 3e — 15.6 Function Symbols and Data Structures
David L. Poole; Alan K. Mackworth · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent finite-state oracles, bilingual review and second-agent cross-checks; not independent human peer review.
- Reread both complete locales:4 displays,6 anchors,4 answers, main table and full Python correspond. The hypothetical desk describes logical records, not real message sending. Separates definite/general Horn, least models/real-world truth, one proof/all support and chaining/constraint forward checking.
- Eight tests passed:256 two-atom rule subsets×4 fact subsets×3queries with complete semantic models and independent event rescanning for caps0–3;301 three-atom programs with at most2 of24 candidate rules×8 fact sets against all classical models and their least intersection;500 random programs with duplicates×7caps and shuffled rule/fact order; per-line proof validity, immutable inputs, invalid containers/names/Boolean budgets, unseeded cycles, empty input and chain lengths0/1/2/10/100/500.
- Recomputed6 derived atoms/2models,7 visits of8body occurrences, fired(4,0,1,2,6,3) and manual remainder1. At cap5 notification is proved with pending work; cap6 drains the queue, and manual is UNKNOWN at cap5. Invariant uses body minus processedP, not knownK. Empty-rule initialization is outside the pop budget; duplicate body atoms normalize while rule IDs remain distinct.
- Separately checked soundness by first-reason induction, the saturated set as a model contained in all models, and completeness for positive atomic queries. All-true always models definite clauses, so an absent query does not prove its negation. Finite atoms ensure termination; every indexed body position is visited once. Complexity explicitly counts f/r/n/rawL, expected hashing, name-character costs and the full trace, without a worst-case arbitrary-name linear claim.
- Strict MDX with repository display-math plugins, remark-math and strict KaTeX was actually React-rendered to static HTML:4displays/4strong answers each, no math errors or emphasis remnants outside code. This is a per-article precheck, not a whole-site build, browser acceptance or human expert review.
- Read both complete articles, metadata, code and all8 author tests; reran all8 successfully. Six anchors,4 displays,4 answered exercises, full code and main table correspond between locales.
- Independent goal-directed finite AND/OR proof-tree oracle memoizes both goal and ancestor set and excludes repeated atoms on a branch. It differs from the author classical-world enumeration and event rescanning. A finite positive proof can have repeated ancestor segments removed, so unseeded cycles do not establish facts. Matched2,783 programs and54,807 budget/query runs.
- A separate static audit computes each rule firing time from the last processed premise position, then sorts by time/rule ID rather than rerunning an agenda. Checked116,963 proof lines,67,591 firings,109,719 body visits and81,452 pops. Verified remaining=body minus processed, first reasons, earlier premises, known=processed+pending, budgets and statuses.
- Main cap5 is ENTAILED/completeFalse/5pops/6visits; cap6 is completeTrue with7visits. manual is UNKNOWN at cap5 and NOT_ENTAILED after completion. Empty rules initialize before the budget, duplicate premises normalize while rule IDs persist, and unseeded cycles provide no proof. An atom named not a is still not syntactic negation.
- Separately checked discovery-induction soundness, the saturated set as a model contained in every model, positive-query completeness and non-entailment versus negation. Each of finitely many atoms enters the queue at most once; all-true always satisfies definite clauses. Cost bounds include input, full proof trace, empty-input constant and expected-hash/name-character assumptions, without a worst-case arbitrary-string linear claim.
- Independently strict-compiled MDX with repository math plugins and KaTeX and actually React-rendered both articles:4 displays,6 headings and4 strong answers each; no KaTeX errors or emphasis remnants outside code. This is per-article static rendering, not browser UI acceptance or a whole-site build.
- Promotion preserves full prose, equations, program and exercises. Tests load published articles only, with draft fallback/skip paths removed and the first-order review assertion updated to checked; algorithm and independent oracle logic are unchanged. Final review binds both MDX SHA-256 hashes.
- Initial Astro collection validation rejected draft kind=algorithm outside the repository’s three-template enum. Published metadata now uses concept (concepts and algorithms); prose/code/equations are unchanged and the schema was not broadened. Collection/build checks were rerun after correction.
- The content gate also found the required research anchor missing. Preserved the six reviewed sections and all mathematics/programs, adding a paired research-check section verified against the actually run256×4×3 and301×8 semantic populations and randomized tests; there are now7stable anchors. Required-section checks were not relaxed.
- Static links found no symbolic catalogue section anchor; replaced the paired link with the supported volume=symbolic filter, without fabricating unwritten pages. The second agent independently reread the added research paragraphs and confirmed256×4×3 and301×8 match actual tests; concept metadata and7anchors introduced no further issue.
- Navigation-only reread: linked the completed Horn and forward/backward chaining articles directly. All claims, code, formulas, exercises, prior source checks and evidence remain unchanged.
Source locations checked:
- Artificial Intelligence: Foundations of Computational Agents, 3e — 5.3 Propositional Definite Clauses · Actually read official3e §5.3 lines16–59 (definite syntax, empty bodies and exactly one positive literal), §5.3.1 lines86–109 (query failure versus falsity), §5.3.2 lines123–158 and177–197 (bottom-up atomic consequences, soundness, indexed complexity, fixed point and least-model completeness), and top-down comparison lines300–307. Own example, event-counter invariant and budget interface are independently derived.
- Linear-Time Algorithms for Testing the Satisfiability of Propositional Horn Formulae · Read original18-page UPenn-hosted paper: printed267 abstract/definition and1984 header; printed269§1 reduced Horn clauses; printed274–277§§4.1–4.2/Algorithm2 on dependency lists, counters, queue and representation. Actually viewed local p267.png,p276.png,p277.png; original page267 header corrects OCR261. p276 explicitly states pre-indexed atoms and discusses symbol-table cost; p277 charges each negative occurrence once. Did not reproduce paper Pascal, figures or examples, or claim testing arbitrary Horn constraints.
- AIMA Python: PropDefiniteKB and pl_fc_entails · Read already independently downloaded official aima/logic.py bytes at pinned bbf6bc296bc8cc21848e62d55a511ec7ad82d285, SHA217bbb63bfec21354a2ad0511f92593773b78ef134406dbfbf3ce2061c5bec0a, lines545–590 for PropDefiniteKB/clauses_with_premise/pl_fc_entails. The helper recomputes its list and agenda uses list.pop; this article instead preindexes and uses deque FIFO. Read pinned MIT license copyright2016 aima-python contributors. Web GitHub page fetch failed; actual local raw source from the preceding verified official download was read, not a successful GitHub HTML fetch or upstream test run.
- Artificial Intelligence: Foundations of Computational Agents, 3e — 15.6 Function Symbols and Data Structures · Read official3e §15.6 text on function symbols and infinitely many terms; §15.6.1 lines105–120 on fair selection, starvation and an unbounded consequence sequence. Restricted article claim to why the finite propositional bound does not carry over, without copying the source example or claiming general first-order implementation.
- Artificial Intelligence: Foundations of Computational Agents, 3e — 5.3 Propositional Definite Clauses · Independently read official §5.3 syntax/empty-body rules, §5.3.1 query semantics and failure versus falsity, §5.3.2 bottom-up derivation, fixed-point model and least-model completeness. In web extraction, relevant lines17–59,86–108,110–158,179–197. Completeness is restricted to positive atomic queries in the article, not arbitrary consequences.
- Linear-Time Algorithms for Testing the Satisfiability of Propositional Horn Formulae · Independently read original UPenn-hosted PDF §4 Algorithm2 and §4.2, printed275–277 (web lines329–439), including counters/dependencies, false sentinel and the pre-indexed-symbol representation condition. Actually viewed author-rendered original pages267/276/277; verified 1984, printed267–284 and counter update. No claim to reproduce or execute the original Pascal or to implement arbitrary Horn satisfiability.
- AIMA Python: PropDefiniteKB and pl_fc_entails · GitHub HTML and raw web fetches independently failed. Independently inspected local previously downloaded pinned official bytes at /tmp/aiwiki-next-dpll/aima-logic.py, SHA217bbb63bfec21354a2ad0511f92593773b78ef134406dbfbf3ce2061c5bec0a, lines538–582 containing PropDefiniteKB, clauses_with_premise and pl_fc_entails. Confirmed recomputed premise list, counters and list.pop agenda. Independently read /tmp/aiwiki-next-dpll/aima-pinned-license.txt (MIT, copyright2016 contributors). This review verifies local content and matching pinned-download hash, not a fresh successful network retrieval or upstream execution.
- Artificial Intelligence: Foundations of Computational Agents, 3e — 15.6 Function Symbols and Data Structures · Independently read official §15.6 function-term construction and §15.6.1 (web lines105–121) on infinite consequence streams, starvation and fair clause selection. Used only for the finite-program scope boundary; no first-order implementation or general decision-procedure claim.
Related topics