Arc consistency: remove values without a partner
弧一致性
Implement AC-3 with oriented binary relations, verify its greatest fixed point and distinguish local support from global satisfiability.
arc-consistencyA value can lose its last compatible partner
Suppose four components A, B, C and D must use compatible operating modes. Mode numbers are labels, not quality scores. Their current domains are A={0,1,2}, B={0,1,2}, C={0,1} and D={1}. Four tables specify the allowed mode pairs:
| Scope | Allowed pairs |
|---|---|
| (A,B) | (0,0), (1,1), (2,2) |
| (B,C) | (0,0), (1,0), (2,1) |
| (C,D) | (0,1) |
| (B,D) | (1,1), (2,1) |
C cannot use mode 1 because D has no compatible mode for it. Once C=1 disappears, B=2 loses its only partner in C. The B–D table separately rules out B=0, leaving B=1. That forces A=1. We reach the unique configuration (A,B,C,D) = (1,1,0,1) by removing impossible values before enumerating the 18 original complete assignments.
Arc consistency makes this partner check precise. Its deletion rule is local: a value can be removed when one neighboring constraint offers no support. This chapter assumes the variables and constraints have already been modeled, as in constraint satisfaction, and focuses on running that check until no further deletion is justified.
Mackworth’s 1977 paper presents AC-3 as a worklist algorithm that revisits potentially affected arcs instead of restarting a full scan after every change. Original paper, printed pp.104–106
The arrow says which domain to revise
Let and be the current domains, and let contain the allowed pairs in the order (u,v). The directed arc is consistent when every value at its tail has a compatible value at its head. The reverse arc uses the transposed relation:
The two arrows ask different questions. If the only allowed pair is (0,1), revising X→Y can retain X=0 and revising Y→X can retain Y=1. Using the same ordered pair table for both directions would incorrectly look for (1,0) in the reverse check. The transpose convention is explicit in Mackworth, printed pp.100–101.
REVISE(u,v) changes only the tail’s domain:
The support comes from the current head domain. A value that was supported earlier may lose support after a later deletion. Checking each arc once is therefore insufficient.
After a successful revision of u→v, reconsider incoming arcs w→u, because values of w may have lost partners in u. Arcs u→w do not gain new obligations when their tail shrinks. We can omit v→u specifically: each removed u-value had no partner anywhere in the current , so it could not have been supporting any remaining v-value. This exception assumes the two directions refer to the same relation and its transpose. Mackworth, printed p.105
The implementation keeps one relation per unordered variable pair. If several constraints apply to that pair, it first orients all their rows consistently and intersects their allowed pairs:
This preserves complete solutions, because the same pair must satisfy every constraint at once. Keeping the constraints separate and asking each for a different support is weaker. For bits P and Q, equality and inequality each support every individual value; their intersection is empty. Intersection of simultaneously required relations is discussed in Mackworth, printed p.108. A worklist keyed only by variable pairs must not silently overwrite one constraint with another.
AC-3 starts with every directed arc in a queue. It removes an arc, revises its tail and enqueues affected incoming arcs that are not already pending. We use FIFO order. This is a binary specialization of the support-and-reconsideration pattern described by Poole and Mackworth, §4.3.
Termination follows from finite domains: each successful revision deletes at least one value, no value is reintroduced, and only successful revisions add new work. The initial queue and every added set of arcs are finite.
Deletions preserve every full solution. If a solution uses u=a, it also uses some v=b satisfying the u–v relation. Inductively, that solution’s values are still present, so a cannot lack support and be deleted. When the queue empties, no arc can remain inconsistent: every arc started pending, and any later change that could invalidate its support scheduled a new check.
There is a stronger, useful claim. Call an arc-consistent subdomain vector when every is a subset of the original domain and all directed support conditions hold within . Empty domains are allowed in this definition. The final vector contains every such :
To prove this, assume has survived every deletion so far. A value in has a support in , which is still present, so the next revision cannot remove it. At termination is itself arc-consistent and contains every candidate : it is the greatest arc-consistent subdomain vector, ordered by inclusion in each coordinate. It need not equal the values that occur in full solutions.
Keep the queue, domains and work counts separate
The Python 3.10+ code below uses finite integer domains and fixed binary relation tables. Domains are ordered tuples with distinct values. Constraints are a tuple or list of (u,v,frozenset_of_pairs) records on distinct, known variables; unary restrictions must already be reflected in the domains.
The function operates on working domains. A fixed relation table may contain integers no longer in those domains; they are simply never considered as supports. This permits rerunning the function on its output domains with the same tables. It differs from the previous chapter’s model validator, which rejected rows outside the declared original domains. Malformed rows, Boolean values masquerading as integers, self-arcs and unknown variables are rejected here.
Inputs are not changed. Pair orientation follows variable insertion order; pair processing order follows the first occurrence in the constraint sequence. Domains keep their input order. The membership sets do not determine traversal order. Identical ordered input therefore gives identical counters and deletion records.
This version deliberately continues until the queue is empty even if a domain becomes empty. It returns the full fixed point, including empty domains, which makes the greatest-subdomain claim testable. A solver that stops at the first empty domain already has a valid contradiction, but its returned domains need not be the full fixed point.
from collections import deque
from collections.abc import Mapping
def ac3(domains, constraints):
if not isinstance(domains, Mapping):
raise TypeError("domains must be a mapping")
if not isinstance(constraints, (tuple, list)):
raise TypeError("constraints must be a tuple or list")
current = {}
for x, values in domains.items():
if not isinstance(x, str) or not x:
raise ValueError("variable names must be nonempty strings")
if not isinstance(values, tuple):
raise TypeError("domains must be tuples")
if any(type(value) is not int for value in values):
raise TypeError("domain values must be integers, not bools")
if len(set(values)) != len(values):
raise ValueError("domain values must be distinct")
current[x] = list(values)
rank = {x: i for i, x in enumerate(current)}
merged = {}
for constraint in constraints:
if not isinstance(constraint, tuple) or len(constraint) != 3:
raise TypeError("a constraint must be (tail, head, allowed)")
u, v, allowed = constraint
if not isinstance(u, str) or not isinstance(v, str):
raise TypeError("constraint variables must be strings")
if u not in current or v not in current or u == v:
raise ValueError("a binary constraint needs two distinct known variables")
if not isinstance(allowed, frozenset):
raise TypeError("allowed pairs must be a frozenset")
for row in allowed:
if not isinstance(row, tuple) or len(row) != 2:
raise ValueError("each allowed pair must have length two")
a, b = row
if type(a) is not int or type(b) is not int:
raise TypeError("pair values must be integers, not bools")
if rank[u] > rank[v]:
u, v = v, u
allowed = frozenset((b, a) for a, b in allowed)
key = (u, v)
merged[key] = merged[key] & allowed if key in merged else allowed
relations = {}
neighbors = {x: [] for x in current}
for (u, v), allowed in merged.items():
relations[u, v] = allowed
relations[v, u] = frozenset((b, a) for a, b in allowed)
neighbors[u].append(v)
neighbors[v].append(u)
queue = deque(relations)
pending = set(queue)
stats = {"revisions": 0, "pair_checks": 0, "deleted": 0, "pushes": len(queue)}
changes = []
while queue:
u, v = queue.popleft()
pending.remove((u, v))
stats["revisions"] += 1
kept, removed = [], []
for a in current[u]:
supported = False
for b in current[v]:
stats["pair_checks"] += 1
if (a, b) in relations[u, v]:
supported = True
break
(kept if supported else removed).append(a)
if removed:
current[u] = kept
stats["deleted"] += len(removed)
changes.append((u, v, tuple(removed)))
for w in neighbors[u]:
arc = (w, u)
if w != v and arc not in pending:
pending.add(arc)
queue.append(arc)
stats["pushes"] += 1
result = {x: tuple(values) for x, values in current.items()}
return {"domains": result,
"status": "domain-wipeout" if any(not d for d in result.values())
else "arc-consistent",
"stats": stats, "changes": changes}
domains = {"A": (0, 1, 2), "B": (0, 1, 2), "C": (0, 1), "D": (1,)}
constraints = (
("A", "B", frozenset(((0, 0), (1, 1), (2, 2)))),
("B", "C", frozenset(((0, 0), (1, 0), (2, 1)))),
("C", "D", frozenset(((0, 1),))),
("B", "D", frozenset(((1, 1), (2, 1)))),
)
result = ac3(domains, constraints)
print(result["domains"])
print(result["stats"])
print(result["changes"])
bits = {f"V{i}": (0, 1) for i in range(5)}
unequal = frozenset(((0, 1), (1, 0)))
ring = tuple((f"V{i}", f"V{(i + 1) % 5}", unequal) for i in range(5))
print("ring", ac3(bits, ring)["status"], ac3(bits, ring)["stats"])
duplicate_domains = {"P": (0, 1), "Q": (0, 1)}
same = ("P", "Q", frozenset(((0, 0), (1, 1))))
different = ("Q", "P", unequal)
print("separate", ac3(duplicate_domains, (same,))["domains"],
ac3(duplicate_domains, (different,))["domains"])
print("combined", ac3(duplicate_domains, (same, different))["domains"])
The first three output lines are:
{'A': (1,), 'B': (1,), 'C': (0,), 'D': (1,)}
{'revisions': 12, 'pair_checks': 34, 'deleted': 5, 'pushes': 12}
[('C', 'D', (1,)), ('B', 'D', (0,)), ('B', 'C', (2,)), ('A', 'B', (0, 2))]
revisions counts popped arcs, including checks that delete nothing. pair_checks counts tested mode pairs, stopping at the first support for each tail value. pushes includes the initial queue; it equals revisions after complete exhaustion. changes records only actual deletions. When B loses values twice, A→B may already be waiting in the queue; the pending set prevents a duplicate entry.
The five-cycle reports 10 revisions, 30 pair checks and no deletions. Running equality and inequality separately leaves both bit domains intact; running them together empties both. These are observed counts for the displayed order, not timing measurements. Reordering domains or constraints can change the work while leaving the fixed point unchanged.
Let be the variable count, , the number of input constraint records, their total number of table rows before merging, and the number of directed arcs after merging. Let be the largest initial domain size, or 0 when there are no variables. Under ordinary hash-table behavior and constant-cost integer operations, preparation plus propagation has the safe upper bound .
For the propagation term, each directed arc enters initially and at most once per subsequent head-domain shrink event, giving at most entries. A revision costs including loop overhead when a domain is empty. This recovers the customary propagation bound for , while keeping zero-domain and initialization costs visible. CS188, §2.3 states the customary bound. Generating relation tables is additional work if they were not supplied in advance.
Additional storage is references, including normalized/transposed tables, domains, the pending queue, result and deletion log. Every logged value is deleted once; the log does not copy complete domains on each revision. Large integer arithmetic and pathological hashing fall outside the constant-cost assumptions.
No empty domain is not a satisfiability certificate
The status domain-wipeout proves the original CSP has no solution, provided the domains and constraints describe it correctly. A remaining isolated variable in another component can keep its values even when one component has emptied. The returned tuple of domains still represents a contradiction as soon as any coordinate is empty.
The status arc-consistent says that all remaining domains are nonempty and every directed support condition holds. It does not say that a complete assignment has been found. In the five-cycle, each bit has a different-colored neighbor available on either side, but alternating two colors around an odd ring is impossible. The greatest arc-consistent subdomains are the full original domains even though no value appears in a full solution. Poole and Mackworth, §4.3 explains why nonempty arc-consistent domains can be inconclusive.
For this pure binary model, if every variable ends with one value, those values do form a solution: each binary support check now has only that one neighbor value available. With zero variables and no binary constraints, the empty assignment is the sole solution. Neither statement extends automatically to omitted higher-arity constraints.
Merging duplicate pair constraints can make local filtering stronger than processing them independently. That is intentional here and is part of the specified consistency target. If a different system keeps distinct constraint records, it must document its support semantics and revisit the appropriate records after changes. The reverse-arc omission in this code cannot be transplanted blindly to a differently keyed worklist.
AC-3 handles binary relations. A global constraint with three or more variables needs a specified decomposition or a suitable generalized propagator. Also, deletions made after a search decision apply to that branch; this standalone function copies its inputs and does not manage a backtracking trail. Those concerns belong in forward checking and constraint propagation.
Predict a deletion before running the queue
- In the compatibility example, why does removing C=1 eventually remove A=2? State the direction of each reconsidered arc.
Answer: C=1 was B=2’s only support in the B–C relation. Shrinking C requires B→C to be checked again, which removes B=2. Shrinking B requires A→B to be checked again; A=2 then has no matching B=2. The arrows point toward the domain that lost a possible support.
- Let X and Y both have domain
{0,1}and let the only allowed pair in order(X,Y)be(0,1). What are the final domains? Why is it wrong to reuse the same ordered table in reverse?
Answer: X becomes {0} and Y becomes {1}. The reverse table must contain (1,0) in order (Y,X). Using (0,1) for Y→X would test the wrong compatibility relation and could erase a valid solution.
- Equality and inequality on the same pair each retain both bit values when processed alone. What happens when both are required, and why is conjunction different from the two separate support witnesses?
Answer: The oriented allowed tables have empty intersection. Neither value has a partner satisfying both relations, so both domains empty after complete propagation. A value’s equality support and its inequality support are different partners; no single chosen partner can satisfy both.
- AC-3 removes nothing from a two-color cycle. What changes when the cycle length changes from five to six? Would keeping only values appearing in full solutions be the same operation as AC-3?
Answer: Both cycles remain arc-consistent with all bit values present. The five-cycle has no solution; the six-cycle has two alternating colorings. Removing values absent from every full solution would empty the five-cycle domains, which is stronger than arc consistency and requires reasoning beyond its local support condition.
Check the fixed point as well as the solution set
An implementation that never deletes anything preserves all solutions, so preservation alone is a weak test. Our independent oracle enumerates every combination of subdomains, selects the arc-consistent combinations by directly testing all support conditions, and takes their coordinatewise union. That union is arc-consistent: each retained value came from a candidate containing a support that is also in the union. It therefore gives the greatest target without reproducing the AC-3 queue or deletion loop.
The tests compare AC-3 with that oracle and separately enumerate complete solutions to check preservation. They cover all 4,096 choices of three binary tables on a Boolean triangle, duplicate constraints with reversed scopes, disconnected and empty domains, order changes and the exact work counts. These small exhaustive checks establish concrete cases and regressions; the arguments above explain the general finite-domain contract.
Read Mackworth’s original paper, §§4–6 for the distinction between consistency properties and algorithms that enforce them. Poole and Mackworth, §4.3 places domain filtering in a broader CSP workflow. The component tables, Python implementation, proofs as presented and tests here are original; no source pseudocode, diagram or course solution has been copied.
Make a prediction, then check
Revising u→v removes values from u. In this implementation with merged pair constraints and transposed reverse relations, which arcs need reconsideration?
Learning objectives
- Interpret support and transposed relations by directed scope, merge constraints on the same pair and recheck incoming arcs after deletions.
- Prove finite-domain termination, full-solution preservation and the greatest arc-consistent subdomains, distinguishing empty-domain contradictions from inconclusive nonempty output.
- Check AC-3 against independent full-solution and all-subdomain enumeration oracles, and explain reproducible revision, pair-check and deletion counts.
Prerequisites & connections
Explore related knowledge →References
- Consistency in Networks of Relations
Alan K. Mackworth · 1977 - Artificial Intelligence: Foundations of Computational Agents, 3e — 4.3 Consistency Algorithms
David L. Poole; Alan K. Mackworth · 2023 - CS188 — 2.3 Filtering
University of California, Berkeley; CS188 course staff
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 languages for directed arcs, transposition, pairwise intersections, incoming requeue and reverse-exclusion assumptions, continuation after empty domains, solution preservation/greatest-subdomain proofs, local versus global support, and initialization/zero-domain/table/log cost accounting. Four display equations, Python and six anchors match; each locale has four answered exercises.
- Eight independent tests passed: all4,096 Boolean-triangle relation networks, enumerating64 subdomain vectors each (262,144 total), selecting arc-consistent candidates and taking their union to verify the greatest fixed point; separate full-assignment enumeration checks equality of solution sets. Also256 duplicated reverse-relation cases,150 random models including empty/disconnected domains,384 main-example order/orientation variants,two-color cycles of3–9 vertices,idempotence,input preservation and invalid inputs.
- Executed the full example: (1,1,0,1),12 arc revisions/34 pair checks/5 deletions/12 pushes; five-cycle10/30/0/10 despite unsatisfiability; equality/inequality each prune nothing alone but empty both domains together. Determinism applies to fixed ordered input, with no claim of equal work across different orders.
- Both temporary MDX articles compiled individually with current project math plugins and KaTeX strict:error/throwOnError:true, and were actually rendered with React renderToStaticMarkup: four display equations and four strong answer labels per locale; the Chinese parenthetical term uses strong, with no literal ** or KaTeX errors. The final targeted stock-phrase rescan passed. Only /tmp/aiwiki-next-arc-consistency was written, review written; no whole-site build, repository/shared registry edits, human expert review or browser-page acceptance claimed.
- A second AI agent reread both complete articles, example.py, metadata, source notes and all eight tests. Checked transposed direction, intersections of same-pair raw relations, affected incoming arcs and the reverse exception, initial empty/disconnected domains, propagation to a full fixed point, working-domain tables containing outside values, solution preservation and the greatest arc-consistent subdomain proof. No mathematical or bilingual issue remained.
- The independent reference treats value deletion as a proposition: deleting all original supports on one neighbor entails deleting the value, with empty-support rules as initial facts. Support counters and premise indexes compute the least Horn closure; its complement is the greatest retained domain vector. This does not use an AC-3 arc queue/REVISE loop or the author's all-subdomain union oracle.
- All 4,096 Boolean-triangle networks and 512 additional models matched the Horn reference. Additional models have zero through five variables; domain lengths zero through three drawn from {-2,-1,0,2,5}; zero through ten relations including reversed/parallel pairs; and tables that may contain outside value 99. Per model checked solution preservation, lack of current support for every logged deletion, idempotence, pushes=revisions, revisions≤e(d+1) and a pair-check bound. Separately verified that an initially empty domain propagates only within its connected component and checked the zero-variable model.
- Actually ran all eight author tests successfully and independently reproduced the main example's 12 revisions/34 pair checks/5 deletions/12 pushes. Checked complexity terms for initialization, input rows, empty-domain overhead, pending deduplication and the deletion log, with e explicitly counting directed arcs. Greatest subdomains permit empty coordinates and are not conflated with projections of complete solutions.
- Independently compiled both MDX articles and rendered static React HTML using project display-math plugins and strict:error/throwOnError:true KaTeX. Each has four display equations and four strong answer labels, with no KaTeX errors or leftover emphasis markers; both Python blocks match example.py. No author file/repository edits, whole-site check/build or browser visual QA. This is AI technical cross-review, not human peer review.
- Promotion preserves full prose, equations, program and exercises. Test loading alone changes from temporary drafts to repository articles; implementation and oracle logic are unchanged. Final review binds both MDX SHA-256 hashes.
Source locations checked:
- Consistency in Networks of Relations · Read author-hosted20-page original PDF extracted text: printed pp.100–101 (Pji(vj,vi)=Pij(vi,vj), directed graph), p.103§4 (node/arc definitions), p.104§6 (REVISE tail-only support and need for repeated checks), p.105 (requeue incoming arcs and why immediate reverse is exempt), p.106 AC-3 (initial all-arcs set, pending deduplication, no forced early empty-domain return), p.108§7.2.1 (conjunction represented by relation intersection). Own code is FIFO with explicit tables/working domains; full fixed-point proof and conditional cost accounting are independently written. PDF text has OCR artifacts; source claims do not rely on ambiguous numeric/copyright OCR, and no scanned-page visual verification is claimed.
- Artificial Intelligence: Foundations of Computational Agents, 3e — 4.3 Consistency Algorithms · Actually reopened and reread §4.3 lines49–58 (support),83–84 (worklist requeue),119–138 (fixed reduced domains and possible empty/nonempty outcomes). Used for the support/fixed-point context and distinction from satisfiability. The source’s general CSP propagation presentation is specialized here to merged binary relations; the article does not reproduce its GAC pseudocode or adopt its space complexity without accounting for stored explicit tables.
- CS188 — 2.3 Filtering · Actually reopened/read §2.3 lines88–93 (two directed arcs, tail revision, incoming updates, pending deduplication),110–114 (AC-3 label and e directed arcs/d maximum-domain O(ed^3) convention). Did not inspect/copy the pseudocode image or map examples. Unlike the page’s early-backtrack option, this implementation runs to exhaustion even after emptying a domain to make its greatest-fixed-point output contract explicit.
- Consistency in Networks of Relations · Independently read the author-hosted original PDF: printed pages 100–101 for reversed predicates, 103 for support definitions, 104 for repeated REVISE, 105–106 for affected incoming arcs and the justified reverse-arc exception. Visually inspected printed pages 103 and 106 via locally rendered images from the same author PDF during the companion forward-checking work. For this review additionally extracted and read printed page 108 section 7.2.1 on intersection of simultaneously required relations. Source notes correctly distinguish the author's OCR-text check from scanned-page visual verification; the peer's additional visual scope is limited to pages 103 and 106.
- Artificial Intelligence: Foundations of Computational Agents, 3e — 4.3 Consistency Algorithms · Independently read section 4.3 lines 49–58 on per-value support and domain deletion, 83–84 on reconsidering affected arcs, and 119–138 on termination outcomes and nonempty arc-consistent domains that may lack a solution. These passages support the consistency-versus-satisfiability boundary; the draft's largest merged-binary subdomain proof was checked independently rather than attributed as a verbatim theorem.
- CS188 — 2.3 Filtering · Independently opened section 2.3 and read lines 88–93 on directed arcs, tail support and incoming updates, plus lines 110–114 on AC-3 and the O(ed^3) convention. The draft correctly specifies a different output contract from early contradiction return: complete worklist exhaustion even after a domain empties.
Related topics