Backtracking for constraints
约束回溯搜索
Find every feasible schedule, reject closed conflicts early, and keep exhausted search separate from an assignment budget.
backtracking-cspReject a conflict before filling the rest of the schedule
Four lab activities, preparation A, a sensor lesson B, demonstration C and assembly D, must fit into slots 0, 1 and 2. Each lasts exactly one slot. A can use slots 0 or 1; C can use 1 or 2; B and D can use any slot. A must precede C, A and B share a host and cannot coincide, and the venue has two interchangeable workstations. At most two activities may occupy any slot.
There are complete assignments before checking the rules. Start with A = 0 and then try B = 0. The shared-host rule already fails. Choosing times for C and D cannot repair it, so the search can discard that entire branch immediately.
Backtracking builds one assignment at a time, detects conflicts as soon as the relevant variables are assigned, and restores the previous partial assignment before trying another value. Berkeley describes fixed variable ordering and early conflict checks as the two basic ideas. The schedule here is the original example used in the constraint-satisfaction chapter; this chapter examines the solver rather than changing the model. CS188, section 2.2
The default order A, B, C, D finds 15 valid schedules. A different variable order finds exactly the same set but can do more work. The first schedule is not necessarily the most convenient one; feasibility and preference remain separate questions.
A failed complete constraint rules out every extension
Let be a partial assignment and the scope of constraint . A constraint can be evaluated directly once every variable in its scope has a value. If it rejects those values, every extension retaining them also fails:
Here is the set of assigned variables, not a variable’s set of allowed values; restricts the assignment to the constraint’s scope. Extending supplies missing variables but does not change existing bindings. This is why pruning a conflict is sound. Poole and Mackworth give the same extension argument before their all-solutions search. Section 4.2
The converse is false. A partial assignment may violate no fully assigned constraint and still have no solution extending it. For three variables with domains {0,1}, requiring each pair to differ leaves no solution: three distinct values cannot fit into a two-value set. Assigning only A = 0 has not closed a binary constraint, so this particular check detects nothing yet. It does not certify that a complete extension exists.
Choose a fixed ordering . At depth , exactly the first variables are assigned. Each branch selects one value for . Once a constraint passes with its entire scope assigned, it remains true along all extensions of that branch. We can therefore check each constraint at the depth where its last variable becomes assigned, instead of repeatedly checking it below that depth.
Soundness follows because every emitted full assignment has passed every constraint. For completeness, take any valid full assignment . Follow the branch choosing at each level. Its prefixes cannot violate a constraint, so none is pruned. With finite domains and no exhausted budget, the search reaches and emits . Distinct paths in the fixed-order tree give distinct full assignments. No solution is emitted twice.
Fixing a variable order also avoids exploring permutations of the same bindings. Assigning A = 0 and then B = 1 describes the same partial assignment as doing those two bindings in the reverse order. A scheduling variable’s value is a time slot; the order in which the solver assigns variables is not the chronological order of the real activities.
Track candidates, checks and the reason for stopping
The complete Python 3.10+ program accepts a dictionary from nonempty variable names to finite domains of distinct integer labels. Each constraint is (scope, allowed_rows): a tuple of variable names and a finite collection of permitted value tuples in that scope’s order. The function validates and copies this representation before searching. It neither learns nor removes domain values. Duplicate allowed rows are harmless; duplicate domain values are rejected to avoid emitting duplicate assignments.
The model is fixed during a call. A supplied order must list every variable exactly once. A scope cannot repeat variables or mention an undeclared name. Rows must have the right length and use their variables’ domain values. Booleans are rejected as domain values, relation values or budgets. The helper table creates relation rows for this example by enumerating the relevant domains; building such tables is preprocessing, not part of the reported search work.
budget limits candidate assignments, including those immediately rejected. None permits exhaustive search. attempts counts those assignments, checks counts actual relation-membership checks, rejected counts candidates rejected by their first failing closed constraint, and nodes counts calls on consistent partial assignments, including the root and solutions. Checking a false zero-variable constraint or noticing an empty domain can terminate before entering the search, with zero nodes.
The result has status='exhausted' only when the finite search or a preprocessing contradiction is complete. With no returned solutions, that establishes unsatisfiability of the supplied model. status='budget' means unexplored candidates remain; the returned solutions are valid but the list may be incomplete. An empty list under that status is not an unsatisfiability proof. The budget excludes input validation, relation construction and copying outputs.
from itertools import product
def backtrack(domains, constraints, order=None, budget=None):
# Domains contain distinct integer labels; relations list allowed scoped tuples.
if type(domains) is not dict or any(type(v) is not str or not v for v in domains):
raise ValueError('domains must map nonempty variable names to finite domains')
domains = {v: tuple(values) for v, values in domains.items()}
for values in domains.values():
if any(type(x) is not int for x in values) or len(set(values)) != len(values):
raise ValueError('each domain needs distinct integer labels, not booleans')
order = tuple(domains) if order is None else tuple(order)
if len(order) != len(domains) or set(order) != set(domains):
raise ValueError('order must list every variable exactly once')
if budget is not None and (type(budget) is not int or budget < 0):
raise ValueError('budget must be None or a nonnegative integer')
rank = {v: i for i, v in enumerate(order)}
closing = [[] for _ in order]
constants = []
for scope, rows in constraints:
scope = tuple(scope)
if len(set(scope)) != len(scope) or any(v not in domains for v in scope):
raise ValueError('a scope must contain distinct declared variables')
allowed = set()
for row in rows:
row = tuple(row)
if len(row) != len(scope) or any(type(x) is not int or x not in domains[v]
for v, x in zip(scope, row)):
raise ValueError('relation rows must match their scoped domains')
allowed.add(row)
if scope:
closing[max(rank[v] for v in scope)].append((scope, allowed))
else:
constants.append(allowed)
solutions, partial = [], {}
stats = {'attempts': 0, 'checks': 0, 'rejected': 0, 'nodes': 0}
for allowed in constants:
stats['checks'] += 1
if () not in allowed:
return {'status': 'exhausted', 'solutions': [], **stats}
if any(not values for values in domains.values()):
return {'status': 'exhausted', 'solutions': [], **stats}
def visit(depth):
stats['nodes'] += 1
if depth == len(order):
solutions.append(partial.copy())
return True
variable = order[depth]
for value in domains[variable]:
if budget is not None and stats['attempts'] >= budget:
return False
stats['attempts'] += 1
partial[variable] = value
try:
valid = True
for scope, allowed in closing[depth]:
stats['checks'] += 1
if tuple(partial[v] for v in scope) not in allowed:
stats['rejected'] += 1
valid = False
break
if valid and not visit(depth + 1):
return False
finally:
del partial[variable]
return True
exhausted = visit(0)
return {'status': 'exhausted' if exhausted else 'budget',
'solutions': solutions, **stats}
DOMAINS = {'A': (0, 1), 'B': (0, 1, 2), 'C': (1, 2), 'D': (0, 1, 2)}
def table(scope, rule):
return scope, tuple(row for row in product(*(DOMAINS[v] for v in scope)) if rule(*row))
CONSTRAINTS = (
table(('A', 'C'), lambda a, c: a < c),
table(('A', 'B'), lambda a, b: a != b),
table(('A', 'B', 'C', 'D'), lambda *times: all(times.count(t) <= 2 for t in (0, 1, 2))),
)
for order in [('A', 'B', 'C', 'D'), ('D', 'B', 'C', 'A')]:
result = backtrack(DOMAINS, CONSTRAINTS, order)
print(order, len(result['solutions']), {k: v for k, v in result.items() if k != 'solutions'})
for budget in (0, 5, 10, 34):
result = backtrack(DOMAINS, CONSTRAINTS, budget=budget)
print('budget', budget, result['status'], len(result['solutions']), result['attempts'])
print('first:', backtrack(DOMAINS, CONSTRAINTS)['solutions'][0])
The two full searches give:
| Order | Solutions | Assignments | Checks | Rejected | Nodes |
|---|---|---|---|---|---|
| A, B, C, D | 15 | 34 | 32 | 7 | 28 |
| D, B, C, A | 15 | 66 | 81 | 21 | 46 |
The first order attempts 2 values at depth 1, 6 at depth 2, 8 at depth 3 and 18 at depth 4. Two B choices violate the shared-host rule, two C choices violate precedence, and three complete schedules exceed workstation capacity. The second order leaves A until last, delaying both binary constraints. It explores more partial assignments, while the solution set remains unchanged.
Comparing 34 candidate assignments with 36 complete schedules mixes units. A complete-enumeration baseline tests 36 full schedules; with the same constraint order and short-circuiting, it performs 81 relation checks. The first backtracking order performs 32 such checks but also manages recursion and partial bindings. These measurements explain this finite example, not a guaranteed runtime speedup for every CSP.
The budget runs return:
| Assignment budget | Status | Solutions returned | Assignments tried |
|---|---|---|---|
| 0 | budget | 0 | 0 |
| 5 | budget | 1 | 5 |
| 10 | budget | 4 | 10 |
| 34 | exhausted | 15 | 34 |
Reaching exactly the final required assignment does not force a budget status: the loops can finish without requesting another candidate. The first solution is {A:0,B:1,C:1,D:0}. Under the chapter’s separate preference cost , it costs 2. The minimum cost is 0, reached by three other solutions. Listing feasible schedules in a fixed order is not an optimization algorithm.
The finally block removes the current binding on normal completion, a budget return or an exception. The program saves a copy of each solution: saving repeated references to the same mutable dictionary would let later backtracking erase or alter earlier answers. It does not change the caller’s domain lists or relation rows.
Ordering changes when a conflict becomes visible
Let be the domain size of the th variable in the chosen order. Without pruning, the maximum number of candidate assignments is
If each domain has at most values, this is . If every domain has one value, it is , so the branching-factor qualification matters. With constraints of maximum arity , a conservative search-time bound is under unit-cost labels and expected constant-time set lookup, plus preprocessing and output costs. Creating and hashing a scoped tuple costs time proportional to its arity; a membership check is not free regardless of scope size.
The recursive working assignment and stack use space. The function also stores normalized domains, relation tables and the list of all solutions. If solutions are returned, output storage is ; auxiliary plus copied-input storage is therefore . A generator could stream solutions, but its caller would still need to decide whether to retain them. Deep instances can exceed Python’s recursion limit even when their domains are finite.
The default order is fixed and the check waits until a scope is complete. Forward checking and arc consistency can remove unsupported future values earlier; they require their own reversible domain state. Minimum-remaining-values ordering uses current domains to select the next variable. Neither filtering nor dynamic ordering is implemented here, and this solver’s fixed-depth closing lists cannot simply be reused after changing the order mid-search.
If a propagation routine temporarily deletes a value, backtracking must restore the correct domain when leaving that branch. Restoring only the most recent assignment would be insufficient. The present implementation changes no domains, making its smaller restoration obligation explicit. Poole and Mackworth separate the search procedure from subsequent consistency algorithms. Sections 4.2–4.3
The all-variable capacity relation in the schedule is checked only after D under the default order. A specialized capacity propagator could sometimes reject earlier. The relation table is exact, but a correct representation does not by itself select the strongest propagation algorithm. Likewise, a poor model can be solved perfectly: accidentally demanding that all four activities occupy different slots would make this three-slot schedule impossible, even though the actual venue allows two at once.
Distinguish a witness from an exhausted search
- With A = 0 and B = 0, which closed constraint rejects the branch? Why is it safe to skip every C and D choice? Does A = 0 by itself prove that a solution exists?
- A run with budget 0 returns no solutions and
budget. Another run with an empty domain returns no solutions andexhaustedat budget 0. Why are these conclusions different? - Reproduce the 34/32 and 66/81 assignment/check counts. Does changing variable order change the preferred time slot of an activity or the set of feasible schedules? What would be needed to choose the cheapest schedule?
- Explain why the solution dictionary is copied and why the binding is deleted in a
finallyblock. What must be added if the solver begins pruning values from future domains?
Worked answers
- Answer: The scope
(A,B)is fully assigned and violates A ≠ B. Extensions cannot change those values, so none can be valid. A = 0 passes the checks currently available but does not, by that fact alone, certify a completion. In the two-value triangle, even a locally unchecked prefix has no completion. - Answer: The first run has declined to inspect the remaining candidate assignments, so both satisfiable and unsatisfiable models are possible. An empty domain makes a total assignment impossible before search starts; this is already a proof for the model. With zero variables and no false zero-variable constraint, the one complete assignment is the empty dictionary, even at budget 0.
- Answer: The earlier table gives the observed counts; delay A to postpone both precedence and shared-host checks. This changes search order and work, not what the slot labels mean or which full assignments satisfy the fixed relations. To minimize the stated cost, compare all feasible solutions or add a sound optimization method with a separate proof of its pruning rule. The lexicographically first feasible schedule costs 2; the best cost is 0.
- Answer: Each answer needs its own stable mapping, while the working mapping is reused and emptied during unwinding.
finallyalso handles early budget returns and exceptions. Domain filtering would require a trail or equivalent saved state that restores every deletion attributable to that branch; undoing one variable binding would no longer be enough.
Use full enumeration to check a faster search
The two references motivate conflict pruning and the equivalence of assignment orders. This chapter’s code, budget contract, finite tables and exact counts are original. The tests enumerate every full assignment independently, then materialize all possible prefixes and sort their domain-index paths to obtain a separate reference for budgeted visitation. They check all 24 orders of the schedule at every relevant budget, all 4,096 combinations of binary relations on a three-variable triangle, and random higher-arity tables.
For a larger problem, report the variable/domain representation, constraint order, variable/value ordering, propagation method, stopping condition and distinct work counters. Preserve a small solved instance as an oracle. An empty result, a timeout, and a proof that no schedule exists are different outcomes that the interface should keep distinguishable.
Make a prediction, then check
At budget 5, the schedule solver returns one solution with status budget. What follows?
Learning objectives
- Prove conflict pruning, completeness and unique output from partial-assignment invariants, and separate model semantics from search order.
- Audit budgets, work counts and restoration, distinguishing a solution witness, exhausted unsatisfiability and an incomplete list.
Prerequisites & connections
Explore related knowledge →References
- CS188: 2.2 Solving Constraint Satisfaction Problems
UC Berkeley CS188 course staff - Artificial Intelligence: Foundations of Computational Agents, third edition, 4.2 Solving CSPs by Searching
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 locales for the fixed-order tree, scope closure, one-way extension implication, budget/empty-domain/nullary cases, finally restoration, solution copies and input/output space. Display formulas, full code, six anchors and four answers correspond.
- Eight tests passed: all 24 variable orders and every relevant budget against sorted explicit-prefix sets; 4,096 binary triangle relation triples × six orders against independent full enumeration; 100 higher-arity random tables, empty domains/variables, nullary relations, invalid inputs and input preservation. Recomputed 15 schedules, 34/32 and 66/81 work counts, first cost 2 and three optima of cost 0.
- A second AI agent reread both complete articles, the code, all eight tests and final metadata. Checked the one-way conflict-extension implication, persistence of satisfied closed constraints, fixed-order completeness and unique output, local consistency versus extendability, solver order versus model semantics, and the distinct units for attempts, checks, rejections and recursive nodes. The parent clarified the ambiguous English Boolean-input sentence to reject Booleans specifically as domain values, relation values or budgets; the peer reread the revised sentence.
- All eight draft tests passed. Built an additional reference from immutable paths and an explicit event stack, without the article's mutable recursive assignment or the author's sorted-prefix-set oracle. Compared all 24 schedule orders at budgets None and 0 through 68, totaling 1,680 cases; then checked 300 random models with zero through five variables, empty domains, nullary through higher-arity constraints and duplicate allowed rows at nine budget configurations each. All 4,380 complete results matched, including solution order, every counter and status.
- Dynamically traced 4,332 actual non-nullary relation checks: every scoped variable was assigned, the current depth was exactly the scope's last-variable depth, and no relation was rechecked for the same prefix. Audited binding sets at 3,189 recursive returns, including normal completion and budget exits; every retained working-dictionary reference was empty after outer completion. Injected an exception during a fourth-level relation check and confirmed all enclosing finally blocks restored an empty working dictionary. Returned solution dictionaries had distinct identities.
- Separately enumerated all 36 complete schedules directly from A<C, A≠B and at-most-two-per-slot semantics, without reading generated relation tables, reproducing 15 solutions and 81 short-circuited checks in the declared constraint order. The two search orders yield attempts/checks/rejected/nodes of 34/32/7/28 and 66/81/21/46; the first solution costs 2 and three solutions attain minimum 0. Checked exact-final-attempt exhaustion, the empty assignment at zero budget with zero variables, preprocessing proofs from empty domains or false nullary relations, and the distinction between a budget-limited empty list and unsatisfiability.
- Checked the unpruned candidate sum, the d>1 qualification, scoped tuple construction and hashing costs, separate preprocessing/output costs, O(n) recursive working space and O(Sn) retained output, with Python recursion limits acknowledged. Both complete Python blocks are byte-identical to example.py, with two matching display equations, six anchors and four answered exercises. This is AI technical cross-review; the peer edited neither drafts nor repository and does not claim human peer review, browser visual QA or a universal runtime speedup.
- Additional AI reread after terminology alignment: checked both openings and every activity, capacity and ordering reference. A is preparation, B a sensor lesson, C a demonstration and D assembly; they are consistently lab activities using two interchangeable workstations. The parent changed the remaining physical table capacity phrase to workstation capacity, and the peer reread it; other table references denote relation or result tables. No wording still treats all four activities as demonstrations or calls the workstations demonstration tables. Lexicographic solution order remains distinct from real activity time order. Both code blocks remain byte-identical to the original example.py. This pass reviewed wording and refreshed hashes without rerunning the previously passed full checks.
- Root integrated the complete bilingual drafts; migrated tests read only formal src/content/articles files. All 112 search checks and 109 article Python programs passed, with paired code, display formulas, major anchors and sources. Draft-stage written/temp-path notes describe their earlier phase; current hashes are registered after actual checking. No independent human peer review is claimed.
Source locations checked:
- CS188: 2.2 Solving Constraint Satisfaction Problems · Read section 2.2 lines 86–88: commutativity of variable assignments permits fixed ordering, and incompatible candidates backtrack. Original four-activity schedule and budgeted program are distinct from the course map and pseudocode. Does not adopt unconditional speedup wording.
- Artificial Intelligence: Foundations of Computational Agents, third edition, 4.2 Solving CSPs by Searching · Read section 4.2 lines 14–26, 31–64, 66–77: generate-and-test/all-solutions distinction, why an already violated constraint invalidates extensions, removing completed constraints from further tests, and answer-set invariance under variable ordering. Own closing-depth buckets, finite relation tables, restoration and budget contract independently derived.
- CS188: 2.2 Solving Constraint Satisfaction Problems · Independently opened and read section 2.2, lines 86–88 and 93–97: fixed variable ordering is justified by commuting assignments, and conflicts with assigned values motivate backtracking. The draft correctly treats ordering as solver work order, not the schedule's time order, and does not import the course's unconditional speedup wording. This peer read the page text; no review of the embedded pseudocode image is claimed.
- Artificial Intelligence: Foundations of Computational Agents, third edition, 4.2 Solving CSPs by Searching · Independently opened section 4.2 and read lines 14–26 on generate-and-test and conflict extensions; Figure 4.1's extracted pseudocode and explanation, lines 31–64, including removal of completed constraints; and lines 66–77 on ordering and answer-set invariance. Also followed the adjacent section 4.3 link and read its prose on consistency/domain deletion (lines 49–58 and 83–84), confirming the distinction from assignment-only restoration. The scope-bucket implementation, budget semantics and numerical schedule results are identified as the chapter's own work.
Related topics