Checking Results

Tests, independent implementations, and audits

Brendan Chapuis

April 19, 2027

Draws on talks by Scott Cunningham and slides by Matthew DeHaven
Course Home Page

Lecture Goals

  • Why checking is now a separate step
  • Unit tests with testthat, and checks on data
  • Running checks automatically with GitHub Actions
  • Independent implementations: the same estimate in R and in Python
  • A second agent as an auditor
  • Six packages, one estimator: what can go wrong out of sight
  • What your AI replications turned up

Checking Is a Separate Act

The Three Legs Again

Before AI

  • You produced the work.
  • Producing it checked it.
  • Producing it taught it to you.

With agents

  • An agent produces the work.
  • Nobody has checked it.
  • Nobody has learned it.

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.

Verification Is the New Bottleneck

G A You design the task B Agent produces A->B C Independent checks B->C D You decide C->D

  • Producing a first draft, a first regression, or a first table is now cheap.
  • Knowing whether it is right is not.

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).

Ingredients of a Good Check

Do not ask whether one output “looks right.” Ask how your workflow makes errors visible.

  • Expectations written down in advance: tests and data checks
  • Fresh starts: someone (or something) redoes the work without seeing the first attempt
  • Different tools: another language, another package, another model
  • Comparison to a source: the paper, the codebook, the published table

The unit of trust is the workflow, not the single answer.

Adapted from Scott Cunningham’s list of verification ingredients.

Today’s Checks

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

Unit Tests

What Is a Unit Test?

A unit test

  • takes a small piece of code (a “unit”),
  • runs it,
  • and checks whether the result is what you expected.

When a test fails, it tells you exactly which piece broke.

You Already Test Your Code

  • You merge two data frames, then print them to see if the merge worked.
  • You run a regression and check the coefficient has the right sign.
  • These are tests. You just run them by hand, once, and forget them.

A unit test writes the check down so it runs every time, including after an agent edits your code.

testthat

The standard R package for tests.

library(testthat)
local_edition(3)

The basic building block is an expectation. It is silent when it passes:

expect_equal(4, 4)

And throws an error when it fails:

expect_equal(4, 3)
Error:
! Expected 4 to equal 3.
Differences:
  `actual`: 4.0
`expected`: 3.0

More Expectations

expect_true(nrow(mtcars) == 32)
expect_equal(0.9999, 1, tolerance = 0.001)   # fuzzy equality
expect_identical(1, 1L)                       # exact: double vs integer
Error:
! Expected 1 to be identical to 1L.
Differences:
`actual` is a double vector (1)
`expected` is an integer vector (1)
expect_s3_class(lm(mpg ~ wt, data = mtcars), "lm")
expect_error(lm(mpg ~ wt, data = iris))

Prefer a specific expect_*() over expect_true(): its error message says what went wrong.

Testing a Function

A function for the root mean squared error:

rmse <- function(actual, predicted) {
  sqrt(mean((actual - predicted)^2))
}

What should it do?

expect_equal(rmse(c(1, 2, 3), c(2, 2, 2)), 0.816, tolerance = 0.01)
expect_equal(rmse(c(0, 0, 0), c(10, 10, 10)), 10)
expect_true(is.na(rmse(c(1, 2, NA), c(1, 2, 3))))

A Test That Fails

Vectors of different lengths should be an error. Are they?

test_that("rmse works", {
  expect_equal(rmse(c(0, 0, 0), c(10, 10, 10)), 10)
  expect_error(rmse(c(1, 2), c(1, 2, 3)))
})

A Test That Fails

── 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.

What Happened

  • The first expectation passed; the second failed.
  • R recycled the shorter vector, gave a warning, and returned a number.
rmse(c(1, 2), c(1, 2, 3))
[1] 1.154701

A number that means nothing, with no error. In a long agent run, that warning is one line among hundreds.

Fix the Function, Rerun the Test

rmse <- function(actual, predicted) {
  if (length(actual) != length(predicted)) stop("Lengths differ")
  sqrt(mean((actual - predicted)^2))
}

test_that("rmse works", {
  expect_equal(rmse(c(0, 0, 0), c(10, 10, 10)), 10)
  expect_error(rmse(c(1, 2), c(1, 2, 3)))
})
Test passed with 2 successes 😀.

test_that() groups expectations under a name, so a failure tells you which test broke.

Tests in a Project

project/
├── code/
│   └── rmse.R
├── tests/
│   └── test-rmse.R
└── main.R

Each test file loads what it tests:

tests/test-rmse.R
source("../code/rmse.R")   # tests run from inside tests/

test_that("rmse works", {
  expect_equal(rmse(c(0, 0, 0), c(10, 10, 10)), 10)
  expect_error(rmse(c(1, 2), c(1, 2, 3)))
})

Running All the Tests

testthat::test_dir("tests")
✔ | 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.

What to Test in a Research Project

  • The functions you wrote: a few cases where you know the answer
  • The data after each step: row counts, keys, ranges (next section)
  • The results: the main coefficient is finite, has the expected sign, and the N is right
  • The outputs: every figure and table file exists and is not empty

Write the tests before you hand the step to an agent. Then the agent’s work has to pass your expectations, not its own.

Watch the Tests Themselves

An agent told “make the tests pass” has two ways to do it:

  1. Fix the code.
  2. Change the test.
  • A test that was loosened, skipped, or deleted shows up in the diff of tests/.
  • Say in AGENTS.md: “Never edit files in tests/ unless I ask.”
  • A hook from 4/5 can enforce it.

A test is only a check if the agent being checked cannot rewrite it.

Checking Data

Assertions with stopifnot()

The simplest data check: stop the script if something is wrong.

library(gapminder)
stopifnot(
  nrow(gapminder) == 1704,
  !anyDuplicated(gapminder[, c("country", "year")]),
  all(gapminder$lifeExp > 0 & gapminder$lifeExp < 100)
)

Nothing printed: all three hold. If one failed, the script would stop at this line instead of producing a wrong table later.

The Checks That Matter Most

  • Row counts: how many rows should there be after this step?
  • Keys: is each country-year (or person-year) unique?
  • Ranges: ages from 0 to 120, shares from 0 to 1, no negative wages
  • Missing values: how many, and in which variables?
  • Units: dollars or thousands of dollars?

These are the same things you look for when you read a diff. Here you write them down once.

A Merge That Adds Rows

library(dplyr)
regions <- tibble(
  continent = c("Americas", "Americas"),
  region    = c("North America", "South America")
)
merged <- left_join(gapminder, regions, by = "continent")
c(before = nrow(gapminder), after = nrow(merged))
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

Catch It with a Test

expect_equal(nrow(merged), nrow(gapminder))
Error:
! Expected `nrow(merged)` to equal `nrow(gapminder)`.
Differences:
  `actual`: 2004
`expected`: 1704

Or tell the join what you expect, and it will refuse:

merged <- left_join(gapminder, regions, by = "continent",
                    relationship = "many-to-one")
Error in `left_join()`:
! Each row in `x` must match at most 1 row in `y`.
ℹ Row 49 of `x` matches multiple rows in `y`.

The validate Package

Rules for a whole data set, checked at once:

library(validate)
rules <- validator(
  lifeExp > 0, lifeExp < 100,
  pop > 0,
  year %in% seq(1952, 2007, by = 5),
  is_unique(country, year)
)
summary(confront(gapminder, rules))[, 1:5]
  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

Validation Inside a Test

test_that("gapminder passes the data rules", {
  out <- summary(confront(gapminder, rules))
  expect_equal(sum(out$fails), 0)
  expect_equal(sum(out$nNA), 0)
})
Test passed with 2 successes 🎉.
  • Put the rules next to the cleaning script, and the test in tests/.
  • When the raw data or the cleaning code changes, the rules are checked again.

Continuous Integration

Running Checks Automatically

Tests only help if they run.

Continuous integration (CI): every time code is pushed, a server runs the project and its tests from scratch.

  • It starts from a machine with nothing installed, so it also checks that your renv.lock is complete.
  • A pull request shows a green check or a red cross before you merge.
  • An agent’s PR has to pass the same tests as yours.

GitHub Actions

GitHub’s CI service. It runs workflows on GitHub’s servers.

  • Event: what starts it (a push, a pull request, a schedule, a button)
  • Job: a set of steps that runs on one fresh virtual machine
  • Step: a shell command, or a prebuilt action (like a function call)

Workflows live in .github/workflows/ as YAML files.

Matthew DeHaven’s slides cover runners, actions, and multi-OS workflows in more detail.

A Workflow for an R Project

# .github/workflows/tests.yml
on: [push, pull_request]
name: Run tests

jobs:
  tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: r-lib/actions/setup-r@v2
      - uses: r-lib/actions/setup-renv@v2
      - run: Rscript -e 'testthat::test_dir("tests")'

Install R, restore the packages from renv.lock, run the tests. If any test fails, the run fails.

What It Costs

  • Free on public repositories (standard runners).
  • On private repositories, the free plan includes 2,000 minutes a month, and more with GitHub Pro (free for students).

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.”

CI for a Research Project

  • Run the tests on every pull request
  • Run main.R from scratch: does the whole project still build?
  • Render the Quarto paper (4/14): does every number still come from code?

When an agent opens a pull request, CI is the first reviewer. You are the second.

Independent Implementations

Tests Check What You Thought Of

  • A test checks an expectation you wrote down.
  • It cannot check something you did not think to expect.
  • What if the estimate itself is wrong in a way no test anticipated?
  • A wrong merge, a dropped group, a package default you did not know about?

One answer: compute the same thing a second, independent way, and compare.

Scott Cunningham’s /referee2

A skill he uses to check code he did not write himself:

  • A fresh agent rebuilds each analysis in R, Stata, and Python.
  • At each step, it checks the three versions agree: the same sample, coefficients, standard errors, and F-statistics.
  • Any disagreement is a flag he has to resolve before he trusts the result.

Scott Cunningham, Baylor talk (October 2026). His skills are in the MixtapeTools repository.

Why Different Languages?

  • R, Stata, and Python have very different syntax and defaults.
  • So a coding error in one is unlikely to happen the same way in the others.
  • If all three agree, an error would have had to happen three times, in three different ways, with the same result.

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.

OLS Is Deterministic

\[\hat\beta = (X'X)^{-1}X'y\]

  • OLS is a fixed function of the data. There is no randomness in it.
  • So the coefficients and standard errors are the same real numbers in any language.
  • If two implementations agree to six decimals, a wide class of bugs is ruled out.
  • If they disagree, it is a bug, or a named default (degrees of freedom, the type of robust SE, missing values), and you can find out which.

The Estimate in R

Life expectancy on GDP per capita (in $1,000s), with continent fixed effects:

library(fixest)
g <- gapminder |> mutate(gdpPercap = gdpPercap / 1e3)
m <- feols(lifeExp ~ gdpPercap | continent, data = g)
round(coeftable(m)[, 1:2], 6)
  Estimate Std. Error 
  0.445270   0.023498 
nobs(m)
[1] 1704

The Same Estimate in Python

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

They Agree

R (fixest) Python (numpy)
Coefficient 0.445270 0.445270
Standard error (iid) 0.023498 0.023498
Observations 1704 1704
  • Different language, different code, no shared package.
  • Same sample, same coefficient, same standard error.

In practice you would use statsmodels or pyfixest in Python. Writing it with numpy makes clear there is no shared code at all.

Clustered Standard Errors

In R, clustering by country:

m_cl <- feols(lifeExp ~ gdpPercap | continent, cluster = ~country, data = g)
round(coeftable(m_cl)[, 1:2], 6)
  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

A Disagreement With a Name

  • Without a small-sample adjustment, the two standard errors differ in the third decimal.
  • With the adjustment fixest applies by default, they agree exactly.

This is what disagreement usually looks like:

  • not noise,
  • but a named default you did not know you were choosing.

Now you know it, and you can say which adjustment your paper uses.

A Disagreement That Is a Bug

Suppose the Python version forgot to divide GDP per capita by 1,000:

coef 0.000445
  • R says 0.445; Python says 0.000445.
  • The gap is exactly a factor of 1,000, which points straight at units.

Disagreement does not tell you which one is wrong. It tells you where to look.

Asking an Agent for an Independent Implementation

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.
  • Start a fresh session, so it does not reuse the first agent’s reasoning.
  • Do not show it the R numbers until it has its own.

A Second Agent as Auditor

Why a Second Agent?

  • The agent that produced the work can explain it. It has also already convinced itself it is right.
  • A fresh agent, starting cold, has not.

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.

What to Give the Auditor

Give it:

  • the repository
  • the claims to check: the paper’s tables, or your draft
  • a narrow job: “check the sample in Table 2,” not “check everything”

Do not give it:

  • the first agent’s transcript or reasoning
  • your hopes for the result

Independence is the point. An auditor that reads the first agent’s reasoning tends to inherit it.

An Audit Prompt

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.

Correlated Errors

Checking works when the errors are imperfectly correlated.

  • Two sessions of the same model share training, habits, and blind spots.
  • A different model or tool is more independent.
  • A different language is more independent still.
  • You, reading the diff, are the most independent of all.

Stack checks whose mistakes are unlikely to line up.

You Adjudicate

The auditor’s report is a list of claims, not a verdict.

  • Some flags will be real bugs.
  • Some will be fine, and you should be able to say why.
  • Some will be wrong.

Every flag gets an answer in your log of checks: fixed, explained, or rejected, and why.

Six Packages, One Estimator

The Experiment

Scott Cunningham replicated a published paper with agents:

  • Dias and Fontes (2024), AEJ: Economic Policy, on Brazil’s mental health reform
  • 96 agents with zero discretion: every decision fixed in advance
  • Varied only the package and the covariates

Six implementations of the same estimator. The same data, method, and controls. They should agree.

Six Packages

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.

No Covariates: They Agree

With no covariates, all six packages give the same estimate:

\[\widehat{ATT} \approx 0.311\]

The estimator itself is implemented correctly in all six.

One Covariate: They Do Not

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.

Across 16 Specifications

Each line is one package across 16 covariate sets. Figure by Scott Cunningham, used with permission.

The Smoking Gun

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?

A Badly Scaled Column

  • Population × year: for a town of 50,000 in 2010, that is 100,500,000.
  • The other covariates range from about 0.01 to 16,000.
  • Put them in one design matrix and \(X'X\) is very badly conditioned: close to singular as far as the computer is concerned.
  • Every one of these estimators fits a logit or probit for the propensity score, which needs that matrix.

But then shouldn’t all six struggle the same way?

Same Name, Different Optimizer

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.

What Went Wrong, Silently

  • One package silently returned estimates of exactly zero, with no error.
  • One needed special options to converge at all.
  • One ran with a relaxed tolerance: stable, but not formally converged.
  • Some propensity-score routines silently drop covariates they cannot estimate and regress on a constant instead.

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, and the Lesson

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.

What This Means for You

  • Rescale variables so they are on similar scales. Check for warnings about convergence.
  • When an estimate matters, compute it a second way: another package, another language.
  • Agreement is evidence. Disagreement tells you where to look.

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.

Your AI Replications

What Did You Find?

With your neighbors, compare your logs (about 10 minutes):

  • Did your table or figure match? How closely: exactly, to rounding, or not at all?
  • What did you check, and how? Which check found something?
  • What did the agent get wrong, or do without telling you?
  • Did it ever claim to have run or checked something it had not?

Patterns to Listen For

  • The sample: a different N, from a filter, a merge, or missing values
  • Defaults: standard errors, weights, or reference categories that differed from the paper’s
  • Versions: a package that changed since the paper was published
  • “Fixing” to match: the agent adjusted things until the number matched, without a reason
  • Confidence: a summary that said “replicated successfully” when it was not

Which of today’s checks would have caught each one?

Back to the Whole Class

  • One example of a check that found a real problem
  • One example of something the agent did that you only saw in the transcript
  • One thing you will do differently on the final project

Your final project is submitted with a log of checks. Today’s list is a starting point for it.

Summary

Summary

  • Agents make production cheap. Checking is now a separate step you do on purpose.
  • Unit tests and data checks write your expectations down so they run every time.
  • CI runs them on every pull request, on a clean machine.
  • Independent implementations: agreement across languages is evidence; agreement within one is not.
  • A second agent audits cold, with a narrow job; you adjudicate.
  • Same estimator, same data, six packages: a 5× spread. Compare, and look where they disagree.

References

  • Cunningham, Scott (2026). Talks at Texas A&M (October 2) and Baylor (October 14). The verification framing, /referee2, and the six-packages experiment are adapted from these talks.
  • DeHaven, Matthew (2026). “Unit Tests & GitHub Actions,” ECON 2020 lecture slides, Brown University. The testthat and GitHub Actions material is condensed from these slides.
  • Dias, Mateus and Luiz Felipe Fontes (2024). American Economic Journal: Economic Policy.
  • GitHub Docs. “Understanding GitHub Actions” and “About billing for GitHub Actions.” https://docs.github.com/en/actions
  • Wickham, Hadley. “Testing basics,” in R Packages (2e). https://r-pkgs.org/testing-basics.html
  • r-lib/actions: GitHub Actions for R. https://github.com/r-lib/actions