Program synthesis: specifications and counterexamples
程序合成
Enumerate a small program grammar and use a finite-domain verifier to refine ambiguous examples.
program-synthesisA problem to solve
Two input-output examples say that 0 should become 1 and 1 should become 2. The program “add one” fits. So does “square, then add one.” Examples communicate something about intent, but they need not identify a unique program.
Program synthesis searches a defined language for a program satisfying a specification. The specification may be a logical property, a reference implementation or examples. A synthesis system needs both a space to search and a way to decide whether a candidate is good enough. The two are separate design choices. Program Synthesis
Definitions and guarantees
Let be a bounded set of programs, a declared input domain, and the reference behavior. The goal here is:
The learner initially sees only a sample . Counterexample-guided inductive synthesis alternates between finding a candidate consistent with and checking it against the full specification. A failing input is added to before searching again. The SKETCH paper presents a synthesize-verify loop for finite programs, and the synthesis survey explains the broader oracle-guided pattern. Combinatorial Sketching for Finite Programs Program Synthesis
In this example the grammar contains a variable, constants zero and one, addition and multiplication:
An abstract syntax tree counts each variable, constant and operator as one node. The program enumerates all trees up to a node bound in size order. It does not execute generated Python text: only these trusted tree constructors are evaluated.
A verifier checks every input in the finite domain. Every counterexample is new because the candidate already fits the accumulated samples. With a finite grammar and exact verifier, the loop either finds a correct candidate or establishes that none exists in that grammar for the declared domain. At most new failing inputs can be added. A timeout or an incomplete verifier would require a different result status.
A minimal implementation
The reference squares an integer and adds one. Search initially receives just the two examples, while the verifier has all five declared inputs. We cache the finite reference table to make the separation explicit; this is a teaching example, not a claim that such a small task needs an elaborate synthesizer.
def expressions(max_nodes):
if type(max_nodes) is not int or not 1 <= max_nodes <= 7:
raise ValueError("teaching bound: 1..7 AST nodes")
by_size = {1: [("x",), ("const", 0), ("const", 1)]}
for size in range(2, max_nodes + 1):
by_size[size] = []
for op in ("+", "*"):
for left_size in range(1, size - 1):
right_size = size - 1 - left_size
for left in by_size.get(left_size, []):
for right in by_size.get(right_size, []):
by_size[size].append((op, left, right))
return [e for size in range(1, max_nodes + 1) for e in by_size[size]]
def run(expr, x):
if expr[0] == "x":
return x
if expr[0] == "const":
return expr[1]
left, right = run(expr[1], x), run(expr[2], x)
return left + right if expr[0] == "+" else left * right
def show(expr):
if expr[0] == "x":
return "x"
if expr[0] == "const":
return str(expr[1])
return "(" + show(expr[1]) + " " + expr[0] + " " + show(expr[2]) + ")"
def first_counterexample(expr, reference, domain):
# Verification sees the whole declared finite domain.
for x in domain:
if run(expr, x) != reference[x]:
return x
return None
def synthesise(target, domain, examples, max_nodes=5):
domain = tuple(domain)
if not 1 <= len(domain) <= 16 or any(type(x) is not int for x in domain):
raise ValueError("domain must contain 1..16 integers")
if len(set(domain)) != len(domain):
raise ValueError("domain values must be distinct")
reference = {x: target(x) for x in domain}
if any(type(y) is not int for y in reference.values()):
raise ValueError("reference outputs must be integers")
examples = tuple(examples)
samples = dict(examples)
for x, y in examples:
if type(x) is not int or type(y) is not int or x not in reference or y != reference[x]:
raise ValueError("examples must agree with the reference on the domain")
candidates = expressions(max_nodes)
trace = []
while True:
# Search sees only the samples accumulated so far.
candidate = next((e for e in candidates
if all(run(e, x) == y for x, y in samples.items())), None)
if candidate is None:
return None, trace
counterexample = first_counterexample(candidate, reference, domain)
trace.append((show(candidate), counterexample))
if counterexample is None:
return candidate, trace
samples[counterexample] = reference[counterexample]
if __name__ == "__main__":
domain = (-2, -1, 0, 1, 2)
expression, trace = synthesise(lambda x: x*x + 1, domain, [(0, 1), (1, 2)])
for candidate, counterexample in trace:
print(candidate, "counterexample:", counterexample)
print("verified on:", len(domain), "inputs")
print("three-node bound:", synthesise(lambda x: x*x + 1, domain, [(0, 1)], 3)[0])
(x + 1) counterexample: -2
(1 + (x * x)) counterexample: None
verified on: 5 inputs
three-node bound: None
The first candidate fails at −2: adding one gives −1, whereas the reference gives 5. A five-node expression then passes the full five-input domain. Under a three-node grammar, no expression meets the same specification. This failure is a statement about the grammar bound, not about the possibility of writing the desired function.
There are 3 one-node, 18 three-node and 216 five-node trees in this grammar. If candidates of at most nodes are retained and the domain has inputs, a straightforward upper bound for the repeated search is , with storage as a conservative bound. Small size bounds are essential; the candidate count grows rapidly.
The evaluator run is for trees constructed by expressions, not arbitrary untrusted ASTs. The reference must be deterministic, and the initial examples must agree with it. A real tool should report whether it checked a finite domain, solved a symbolic condition or merely ran selected tests.
Limits and alternatives
Finite verification does not automatically prove correctness over every integer, let alone every behavior of a language with exceptions, state or concurrency. For the returned arithmetic expression a separate algebraic argument may establish more, but that is not what the finite verifier certified.
A different grammar can express a different set of solutions. Restricting the grammar helps search but can exclude the intended program; expanding it creates more candidates and ambiguity. A shortest consistent program is a preference within that space, not a guarantee of the user’s intended behavior.
Modern synthesis combines enumeration, constraints, probabilistic guidance and learned proposals in different ways. A generated candidate can still be checked independently. The quality of a proposal mechanism and the strength of its verifier should be evaluated separately.
Exercises with answers
1. Why do the initial two examples not identify the intended program?
Both x+1 and x*x+1 agree at 0 and 1.
2. What does the counterexample −2 reveal?
x+1 gives −1, while x*x+1 gives5.
3. How many nodes does 1+(x*x) contain?
Five: two operators and three leaves.
4. Does failure at a three-node bound prove no program can solve the task?
No. A five-node program solves the declared specification.
Research and next steps
Read the synthesis survey’s specification and oracle-guided sections, then the original finite-program SKETCH loop. The important contract is what the verifier quantifies over and which programs the search can express.
Continue with automated theorem proving, inductive logic programming and SAT solving.
Make a prediction, then check
What does the three-node failure establish?
Learning objectives
- Separate a grammar, observed examples and a complete specification.
- Explain finite-domain verification and grammar-relative failure.
Prerequisites & connections
Explore related knowledge →References
- Program Synthesis
Sumit Gulwani; Oleksandr Polozov; Rishabh Singh · 2017 - Combinatorial Sketching for Finite Programs
Armando Solar-Lezama; Liviu Tancau; Rastislav Bodik; Vijay Saraswat; Sanjit Seshia · 2006
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit finite models, executed programs, independent mathematical/exhaustive references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.
- Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
- Verified8 tests: grammar counts3/18/216, ambiguity at0/1, counterexample−2, finite-domain extrapolation failure, tighter grammar failure and invalid iterator examples. Materialized examples before checking to prevent iterator consumption bypass.
- Compared both locale arguments, definitions, assumptions, formulas, code, results and all four exercises. Original finite teaching programs; no published system or research benchmark reproduction claimed. Catalogue IDs corrected before freezing.
- Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Program Synthesis · Physical13–15/17 specification and challenge passages;49–52 oracle-guided/CEGIS loop and verifier assumptions.
- Combinatorial Sketching for Finite Programs · Author MIT copy; abstract and physical2/7/9 counterexample synthesize-verify passages, finite program scope; no tool benchmark reproduction.
Related topics