Tests, independent implementations, and audits
April 19, 2027
Draws on talks by Scott Cunningham and slides by Matthew DeHaven
Course Home Page
testthat, and checks on dataBefore AI
With agents
On 4/7 you checked agent work by reading the diff. Today: checks that run on their own, and checks that do not depend on reading every line.
The hard part is designing checks that still work when production is cheap.
After Scott Cunningham, “Verification is the new bottleneck” (Baylor talk, October 2026).
Do not ask whether one output “looks right.” Ask how your workflow makes errors visible.
The unit of trust is the workflow, not the single answer.
Adapted from Scott Cunningham’s list of verification ingredients.
| Check | Catches |
|---|---|
| Unit tests | a function that does not do what you think |
| Data checks | rows lost or duplicated, values out of range |
| Continuous integration | code that only runs on your machine |
| Independent implementation | bugs specific to one language or package |
| A second agent as auditor | mistakes the first agent made and then believed |
A unit test
When a test fails, it tells you exactly which piece broke.
A unit test writes the check down so it runs every time, including after an agent edits your code.
testthatThe standard R package for tests.
Error:
! Expected 1 to be identical to 1L.
Differences:
`actual` is a double vector (1)
`expected` is an integer vector (1)
Prefer a specific expect_*() over expect_true(): its error message says what went wrong.
A function for the root mean squared error:
Vectors of different lengths should be an error. Are they?
── Warning: rmse works ─────────────────────────────────────────────────────────
longer object length is not a multiple of shorter object length
Backtrace:
▆
1. ├─testthat::expect_error(rmse(c(1, 2), c(1, 2, 3)))
2. │ └─testthat:::quasi_capture(...)
3. │ ├─testthat (local) .capture(...)
4. │ │ └─base::withCallingHandlers(...)
5. │ └─rlang::eval_bare(quo_get_expr(.quo), quo_get_env(.quo))
6. └─global rmse(c(1, 2), c(1, 2, 3))
7. └─base::mean((actual - predicted)^2)
── Failure: rmse works ─────────────────────────────────────────────────────────
Expected `rmse(c(1, 2), c(1, 2, 3))` to throw a error.
Error:
! Test failed with 1 failure and 1 success.
A number that means nothing, with no error. In a long agent run, that warning is one line among hundreds.
Test passed with 2 successes 😀.
test_that() groups expectations under a name, so a failure tells you which test broke.
✔ | F W S OK | Context
✔ | 2 | rmse
══ Results ═════════════════════════════════════════
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 2 ]
End main.R with this line, so every full run of the project also runs the tests.
Write the tests before you hand the step to an agent. Then the agent’s work has to pass your expectations, not its own.
An agent told “make the tests pass” has two ways to do it:
tests/.tests/ unless I ask.”A test is only a check if the agent being checked cannot rewrite it.
stopifnot()The simplest data check: stop the script if something is wrong.
Nothing printed: all three hold. If one failed, the script would stop at this line instead of producing a wrong table later.
These are the same things you look for when you read a diff. Here you write them down once.
before after
1704 2004
“Americas” appears twice in regions, so every American country-year is now in the data twice. Nothing stopped the script.1
Error:
! Expected `nrow(merged)` to equal `nrow(gapminder)`.
Differences:
`actual`: 2004
`expected`: 1704
validate PackageRules for a whole data set, checked at once:
name items passes fails nNA
1 V1 1704 1704 0 0
2 V2 1704 1704 0 0
3 V3 1704 1704 0 0
4 V4 1704 1704 0 0
5 V5 1704 1704 0 0
Test passed with 2 successes 🎉.
tests/.Tests only help if they run.
Continuous integration (CI): every time code is pushed, a server runs the project and its tests from scratch.
renv.lock is complete.GitHub’s CI service. It runs workflows on GitHub’s servers.
Workflows live in .github/workflows/ as YAML files.
Matthew DeHaven’s slides cover runners, actions, and multi-OS workflows in more detail.
Install R, restore the packages from renv.lock, run the tests. If any test fails, the run fails.
A small research project uses a few minutes per run. Long estimations belong on OSCAR, not on GitHub’s servers.
Source: GitHub Docs, “About billing for GitHub Actions.”
main.R from scratch: does the whole project still build?When an agent opens a pull request, CI is the first reviewer. You are the second.
One answer: compute the same thing a second, independent way, and compare.
/referee2A skill he uses to check code he did not write himself:
Scott Cunningham, Baylor talk (October 2026). His skills are in the MixtapeTools repository.
Agreement across languages is evidence; agreement within one language is not. — Scott Cunningham
Running the same R script twice and getting the same number tells you nothing about whether it is right.
\[\hat\beta = (X'X)^{-1}X'y\]
Life expectancy on GDP per capita (in $1,000s), with continent fixed effects:
Written from scratch with numpy, from a copy of the data saved in R with write.csv(gapminder, "gapminder.csv", row.names = FALSE):
import numpy as np, pandas as pd
df = pd.read_csv("gapminder.csv")
df["gdpPercap"] = df["gdpPercap"] / 1e3
X = pd.get_dummies(df["continent"], dtype=float) # continent fixed effects
X.insert(0, "gdpPercap", df["gdpPercap"])
X, y = X.to_numpy(), df["lifeExp"].to_numpy()
XtXi = np.linalg.inv(X.T @ X)
b = XtXi @ X.T @ y
e = y - X @ b
n, k = X.shape
se = np.sqrt(e @ e / (n - k) * XtXi[0, 0])
print(f"coef {b[0]:.6f} se {se:.6f} n {n}")coef 0.445270 se 0.023498 n 1704
R (fixest) |
Python (numpy) |
|
|---|---|---|
| Coefficient | 0.445270 | 0.445270 |
| Standard error (iid) | 0.023498 | 0.023498 |
| Observations | 1704 | 1704 |
In practice you would use statsmodels or pyfixest in Python. Writing it with numpy makes clear there is no shared code at all.
In R, clustering by country:
Estimate Std. Error
0.445270 0.158608
In Python, the textbook cluster-robust formula:
G = df["country"].nunique()
meat = sum(np.outer(s, s) for s in
(X[i].T @ e[i] for i in df.groupby("country").indices.values()))
V = XtXi @ meat @ XtXi
adj = G / (G - 1) * (n - 1) / (n - k) # small-sample adjustment
print(f"no adjustment: {np.sqrt(V[0, 0]):.6f}")
print(f"with adjustment: {np.sqrt(adj * V[0, 0]):.6f}")no adjustment: 0.157816
with adjustment: 0.158608
fixest applies by default, they agree exactly.This is what disagreement usually looks like:
Now you know it, and you can say which adjustment your paper uses.
Suppose the Python version forgot to divide GDP per capita by 1,000:
coef 0.000445
Disagreement does not tell you which one is wrong. It tells you where to look.
In a new folder, check/, reimplement code/03-regressions.R in Python
without reading the R code's output files. Use only data/clean/ and
the specification in AGENTS.md. Report the N, coefficients, and
standard errors for each model in a table, next to the R results,
to six decimals. Flag every difference larger than 1e-6 and explain it.The original agent can explain itself. A fresh verifier is more likely to catch what the first one normalized. — Scott Cunningham
The same idea as a referee: someone who did not write the paper reads it.
Give it:
Do not give it:
Independence is the point. An auditor that reads the first agent’s reasoning tends to inherit it.
You are auditing this project. Do not change any files outside audit/.
1. Run main.R from scratch. Does it finish? Record every warning.
2. For each number in paper/draft.qmd, find the code that produces it.
List any number that is typed in rather than computed.
3. Count observations at each step of code/02-clean.R. Explain every drop.
4. Write audit/report.md: each issue, the file and line, and how sure you are.Narrow steps, written output, and a rule against fixing things itself: you want a report, not a second producer.
Checking works when the errors are imperfectly correlated.
Stack checks whose mistakes are unlikely to line up.
The auditor’s report is a list of claims, not a verdict.
Every flag gets an answer in your log of checks: fixed, explained, or rejected, and why.
Scott Cunningham replicated a published paper with agents:
Six implementations of the same estimator. The same data, method, and controls. They should agree.
All six implement the Callaway and Sant’Anna difference-in-differences estimator, with the same options.
| Package | Language |
|---|---|
did |
R |
ddml |
R |
csdid |
Stata |
csdid2 |
Stata |
differences |
Python |
diff-diff |
Python |
You do not need to know this estimator. All that matters: the same method, called six ways.
With no covariates, all six packages give the same estimate:
\[\widehat{ATT} \approx 0.311\]
The estimator itself is implemented correctly in all six.
Add one covariate, municipal population × year:
| Package | Estimate |
|---|---|
ddml (R) |
0.45 |
csdid2 (Stata) |
0.45 |
did (R) |
0.53 |
differences (Python) |
0.67 |
csdid (Stata) |
1.15 |
diff-diff (Python) |
2.38 |
Same data, same estimator, same single covariate: a 5× spread.
Each line is one package across 16 covariate sets. Figure by Scott Cunningham, used with permission.
Drop that one variable and use any other covariate set:
All six packages agree to within 0.007.
One variable caused the whole spread. Why?
But then shouldn’t all six struggle the same way?
| Package | What it actually calls | Optimizer |
|---|---|---|
did |
glm() probit |
IRLS |
ddml |
glmnet lasso, then glm() |
coordinate descent + IRLS |
csdid |
probit, iterate(1000) difficult |
Newton–Raphson |
csdid2 |
probit with relaxed tolerance |
Newton–Raphson |
differences |
statsmodels Probit().fit() |
Newton |
diff-diff |
statsmodels Probit() plus its own code |
statsmodels + internal |
The documentation says “logistic regression.” Underneath, six different algorithms behave differently when the matrix is nearly singular. You do not see this.
Recovered from each package’s source code by Scott Cunningham’s agents.
None of these is an indefensible choice by a package author. Each is invisible to the user.
diff-diff has since been updated to address its issue.
The fix: rescale the covariate (divide by \(10^6\), or standardize). Most of the disagreement disappears.
The lesson: your choice of language, then package, then the algorithm inside it, are all researcher degrees of freedom. Only the first usually appears in a paper.
Hidden actions become detectable only when independent agents replicate one another.
No single agent did anything wrong here. The comparison found it.
Agents are useful because they make expensive verification routines cheap enough to run. — Scott Cunningham
Running six packages used to be a week of work. Now it is an afternoon.
With your neighbors, compare your logs (about 10 minutes):
Which of today’s checks would have caught each one?
Your final project is submitted with a log of checks. Today’s list is a starting point for it.
/referee2, and the six-packages experiment are adapted from these talks.r-lib/actions: GitHub Actions for R. https://github.com/r-lib/actions