Topic 3 of 5 · 5 min read
Executable tests as graders
Goal: Grade generated code or SQL by executing it against tests or fixtures and report pass@k correctly.
When the task is writing code, the best grader runs the code. A test either passes or fails, and it does not care how the solution is written. This is how HumanEval grades models: functional correctness by unit tests.
Check yourself · 1 of 3
Why is running generated code against tests a stronger grader than reading it?
Why it matters
Reading generated code and judging it by eye is slow and unreliable, because wrong code looks fluent. Running it against tests gives a hard answer. The same idea works for generated SQL: build a small fixture database, run the query and compare the rows.
How to do it
- Write tests that check behavior, not text. Include edge cases: empty input, duplicates, nulls.
- Sandbox the run. Generated code can loop forever, delete files or call the network. Use a container or a restricted process, a time limit, a memory cap, and no network. Never execute it in your own environment.
- Use a fixture for SQL. Create tables and rows in an in-memory database, run the generated query, then compare result sets. Compare as sorted lists unless the task demands an order.
- Handle failure kinds. Record syntax error, runtime error, timeout and wrong result as separate outcomes.
- Sample several attempts. Models are random, so run k samples per problem.
pass@k in one paragraph
pass@k is the chance that at least one of k samples passes. The HumanEval paper gives an unbiased estimator: generate n samples, count c that pass, and compute 1 - C(n-c, k) / C(n, k). Do not draw exactly k samples and call the average pass@k, because that is noisy. Pick k to match use: pass@1 describes a user who takes the first answer, and a larger k describes a system that can run tests and retry.
Before and after
# Weak: checks that the code mentions the function
def grade(code: str) -> bool:
return "def dedupe" in code
def grade(code: str) -> bool:
ns = {}
exec(code, ns) # run only inside a sandbox with a timeout
f = ns["dedupe"]
return f([3, 1, 3, 2]) == [3, 1, 2] and f([]) == []
What goes wrong
- Thin tests. Two happy-path cases pass wrong code. Test authors miss edges too.
- Leaked tests. If the tests appear in the prompt, the model can fit them.
- Unsafe execution. Running untrusted output without a sandbox is a security hole.
- Wrong pass@k. Reporting the best of several runs as pass@1 overstates quality.
Examples
SQL on an in-memory fixture
import sqlite3
def grade_sql(generated: str) -> bool:
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE orders(id INT, user_id INT, total REAL);
INSERT INTO orders VALUES (1,7,40),(2,7,60),(3,9,15);
""")
try:
rows = db.execute(generated).fetchall()
except sqlite3.Error:
return False
return sorted(rows) == [(7, 100.0), (9, 15.0)]
The task was "total spend per user". Different valid queries pass; a query that forgets GROUP BY fails.
Computing pass@k
For one problem you draw n = 10 samples and 3 pass, so c = 3. With k = 1 the estimate is 1 - C(7,1)/C(10,1) = 0.3. With k = 5 it is 1 - C(7,5)/C(10,5), which is about 0.92. Average this over all problems. The k = 5 score is not a claim about the first answer.
Key points
- For code tasks, run the code against tests: behavior is checked, not style or wording.
- Execute generated code only in a sandbox with a time limit, a memory cap and no network.
- For SQL, run the query on a fixture database and compare the result rows, not the query text.
- Record syntax errors, runtime errors, timeouts and wrong results as separate outcomes.
- pass@k is the chance that at least one of k samples passes; use the unbiased estimator from n samples rather than the best of k runs.
Common mistakes
- Running generated code outside a sandbox or without a timeout.
- Writing two happy-path tests and treating a pass as correct code.
- Comparing SQL text with a reference query instead of comparing result rows.
- Reporting the best of several runs as if it were pass@1.
Check yourself · 2 of 3
A generated SQL query returns the right rows but in a different order than the reference. The task did not ask for an order. What should the grader do?
Check yourself · 3 of 3
You draw 10 samples for a problem and 3 pass the tests. How should pass@1 be estimated?
Practice items, not counted towards your mastery.
Start here
- promptfoo: Assertions and metrics (opens in a new tab)DocsFree
Lists the deterministic assertion types (equals, contains, is-json, regex, javascript, python) with config examples.
- JSON Schema (opens in a new tab)StandardFree
The specification and learning material for required fields, types, enums and additionalProperties.
- Evaluating Large Language Models Trained on Code (Chen et al.) (opens in a new tab)PaperFree
Introduces HumanEval, functional-correctness grading by unit tests, and the unbiased pass@k estimator.
More for this topic
- sqlite3: DB-API 2.0 interface for SQLite (Python docs) (opens in a new tab)DocsFree
How to build an in-memory fixture database and run generated SQL against it from a test.