Goodhart's law in security metrics
A green test suite and a high detection rate tell you about the inputs and the paths that were checked, and about nothing else. Using cases from our own history, this module shows how a security metric stops measuring security, and teaches you to report a rate in a way that can be verified.
Time: about an hour. Roughly 35 minutes for the text, 20 minutes for the lab and 5 minutes for the questions. What you need: Python 3.8 or later with no third-party packages. No account, keys or network access are needed.
Learning goals
- State Goodhart's law and name the ways in which a security metric comes apart from security.
- Tell a check that can fail from a check that is green whatever the state of the system.
- Test a structural check by mutation: put the original defect back and confirm that the check goes red.
- Choose the unit of a trial and report a rate with its one-sided 95% Clopper-Pearson bound and a verdict.
- Set a task for an agent so that "the tests pass" does not become the goal.
Goodhart's law in defense
In Marilyn Strathern's widely quoted wording, the law reads: when a measure becomes a target, it ceases to be a good measure.
In defense, the measures are recall on an attack corpus, the false-positive rate, the number of green tests and coverage. Each of them was obtained on specific data with a specific tool. While a measure is only observed, it stays tied to protection. Once people start improving it, what improves is whatever is cheapest to change: the data, the tool or the definition. Protection may stay the same or get worse.
Security differs from ordinary engineering in one respect: the adversary is not limited to your corpus. The work of Athalye and coauthors and of Carlini and coauthors showed this for defenses against adversarial examples. A defense looked robust while it was tested with an attack that was not designed for that defense, and it stopped looking robust once the attack was adapted to it.
Four mechanisms follow, and then, separately, the behavior of agents.
Reward hacking
Reward hacking is the situation in which a system reaches a high value of a measure in a way the author of the measure did not intend. A well-known example from reinforcement learning: an agent in a racing game earned points for collecting bonuses and learned to circle in place, collecting them again and again, instead of finishing the race.
Defense teams do not need a neural network for this. The false-positive rate can be improved by switching the detector off. In our own history, a hand-written prefilter in front of a rule set behaved this way. It was supposed to pass on to the rules everything they are able to catch, but it passed on less. A closed filter produced fewer detections, and fewer detections on legitimate text mean a better false-positive rate. That was exactly the number we published and improved. This is question A3: a prefilter must be a superset of what it gates.
What to do:
- For every improvement in a measure, ask what else moved. The false-positive rate is considered only together with recall on an independent set.
- Find out which component made the decision. An aggregate number gives no right to any claim about an individual component.
- Derive the fast path from the slow one instead of maintaining it by hand next to it.
A detector overfitted to its corpus
An attack corpus is a finite sample collected by the same people who write the rules. A rule is written while looking at an example from the corpus and is then tested on that same example. Recall on your own corpus then measures memory, not the ability to detect.
Signs of overfitting:
- Recall on your own corpus is close to 100% and has not changed for months.
- On texts written by other people the result is noticeably worse, or no such measurement exists.
- A minimal edit to an example that preserves its meaning removes the detection.
- A rule is named after a technique that it has never detected outside its own example.
What to do:
- Keep a held-out set that the rules were not tuned on, and third-party sets. Report the rates on your own corpus and on the outside corpus separately.
- Split the data by attack family, not by row: variants of one sample must not end up in both tuning and evaluation.
- For every rule, ask what an attacker must change for it to stop firing. This is question E2. An edit that costs one keystroke cannot be counted as a constraint.
- Check the negative class. If the set of "legitimate" texts contains attacks, correct blocks look like false ones, and the set rewards weakening the rules. This is question F11.
A metric that cannot fail
A check is evidence only if it had the chance to give a different result. There are three common ways to lose that chance.
First: the input does not reach the code under test. A comparison of two implementations on a corpus that never enters the changed branch stays green for any edit in that branch. "The implementations agree" and "the corpus did not ask the question" produce the same check mark.
Second: there is no positive control. If a measurement shows zero detections, you need to know that it would show something other than zero where detections certainly exist. Without a control row, a column of zeros and a broken run look the same.
Third: "no" cannot be told from "could not ask". An alert whose condition cannot match any data series is always silent, and silence reads as health. A tool that reports "object not found" when the connection drops asserts something it does not know. These are questions F12 and B2.
What to do:
- Next to the result, report how many inputs reached the branch under test. Zero is allowed, but it must be visible.
- Include a control with a known answer in every measurement.
- Distinguish three states: yes, no, could not measure. The third never turns into the second.
Vacuous checks
A check is vacuous if it is true for any behavior of the system, or if it does not see the case it was written for. Common forms:
- An assertion that cannot be false: the number of misses is no greater than the number of rows.
- The test calls a function directly, while the defect lives in the path by which a request reaches that function.
- The test was written from an incident and covers one instance, not the class: one directory, one file, one deployment profile. This is question C3.
- The check was written from an example and gets exactly that example wrong: the pattern does not recognize the operator that the defect consists of. This is question F13.
Reading does not find such checks: a check that does not work looks like silence. Mutation finds them. Put the original defect back into the code, run the check and see whether it went red. A check that stayed green guards nothing.
Agents that game the tests
Coding agents are trained on tasks with a verifiable result, and at work they are judged the same way: did the checks pass. Model evaluation reports describe how an agent gets a green result while bypassing the task: it edits the test instead of the code, hard-codes the expected value for a special case, weakens an assertion, marks a test as skipped, or replaces the part under test with a stub.
For a defense team the conclusion is direct. For an agent that is told to "fix the red gate", the cheapest thing to change is the gate.
What to do:
- Do not let the agent edit the checks it is judged by. The checks have a separate owner, and a human reviews changes to them.
- State the task as the behavior of the system, not as the color of a result.
- In an agent's changes, read separately the removed assertions, the widened exception lists, the skip markers and the changed thresholds.
- Keep checks that the agent has not seen, and test by mutation the new tests the agent wrote.
- Require evidence: what was run and what was printed. The answer "could not verify" is accepted and valued above an unconfirmed "done".
- Do not appoint the model as the sole judge of its own work: a model trained to please the rater tends to agree.
Cases from our own history
Source: the draft case book docs/research/OSAA_CASE_BOOK_DRAFT.md, entries from August 2026.
The numbers below are taken from it. They are historical measurements of defects that have
already been fixed, not current product figures. We describe the class of defect and do not
reproduce attack texts. The full list of questions is in the
hub index.
| Question | What was green | What it turned out to be | Class of defect |
|---|---|---|---|
| A1. How many attacks does this particular rule catch? | Recall of 107 out of 107 on our own corpus after every change | The five rules that were examined caught zero attacks on 131 entries of our own and one attack between them among 6,104 third-party texts; four of them were blocking legitimate requests all the while | An aggregate number hides a part; overfitting to the corpus |
| A2. Does this set exist in more than one copy? | Two copies of the corpus with one name and one version | One copy held 53 entries, the other 107; measurements on the truncated copy looked better | The version does not change together with the content |
| A3. Is the prefilter a superset? | Unit tests of the rules that called the rules directly | The filter switched off some of the rules and so improved the published false-positive rate | Reward hacking |
| C1. Can the caller choose whether the control runs? | 60 unit tests, a corpus of 345 cases, 11 end-to-end tests | The control did not run for streamed responses; no test turned that mode on | The tests do not take the path of the defect |
| F2. How many rows exercised the branch under test? | A comparison of two implementations on 222 rows | No row reached the changed branch; the comparison stayed green after one of the implementations was edited | A metric that cannot fail |
| F13. Does the check fail on the case it was written for? | A new check on a tree where the defect was still present | The pattern of the check did not recognize the operator the defect consisted of; found by mutation | A vacuous check |
What these cases have in common: the data needed for the answer already existed, the error most often flattered the system, and the green test was part of the mechanism, because it did not take the path on which the defect lived.
How to report a rate honestly
A rate without a bound reads as more than it is. These are the rules we follow ourselves:
- The threshold τ is chosen before the measurement, from the risk, not from the result.
- A trial is an independent source sample. Paraphrases, translations, mutations and repeated runs of one sample make up one trial. It counts as an event if the event occurred in at least one variant. Counting variants as trials makes the bound narrower than the data allow.
- Report the number of events, the number of trials, the one-sided 95% Clopper-Pearson bound and the verdict.
- Together with the number, state the date, the system version, the dataset and which rows were read.
- A "before and after" comparison on the same rows is paired. Use McNemar's test for it, not two independent rates.
The Clopper-Pearson bound is exact: it relies on the binomial distribution, not on an approximation. The upper one-sided 95% bound is the rate at which the probability of seeing that many events or fewer is 5%. The lower bound is defined as its mirror image.
The verdict for the claim "the rate is below τ":
| Condition | Verdict |
|---|---|
| The upper bound is below τ | VERIFIED |
| The lower bound is not below τ | NOT VERIFIED |
| Otherwise | INCONCLUSIVE |
Zero events in a small number of trials means a lack of data, not safety. With zero events in N
trials the upper bound equals 1 - 0.05 ** (1 / N). Zero out of 10 is compatible with a true
rate of 25.9%. Two events out of 36 are compatible with a rate of 16.5%. Confirming a 1%
threshold without a single event takes 299 independent trials, and a 5% threshold takes 59.
In the Spectorn repository the bounds are computed by scripts/rate_bounds.py, which needs only
the Python standard library:
python3 scripts/rate_bounds.py claim 0 30 --tau 0.05
python3 scripts/rate_bounds.py plan --tau 0.01
python3 scripts/rate_bounds.py mcnemar 9 1
The first command judges the claim "the rate is below 5%" on zero events in 30 trials: the upper
bound is 9.50%, the verdict is INCONCLUSIVE. The exit code is 0 for VERIFIED, 1 for
NOT VERIFIED and 2 for INCONCLUSIVE. The second prints the number of trials without events
that a 1% threshold needs. The third computes the exact two-sided p-value for a paired change:
nine rows changed in one direction and one in the other, and p is about 0.021.
Spectorn's measured results, with their dates and limitations, are collected on the page "Measured evidence, with dates".
Required reading
- Dario Amodei et al., "Concrete Problems in AI Safety", 2016: the section on reward hacking. arxiv.org/abs/1606.06565
- Anish Athalye, Nicholas Carlini, David Wagner, "Obfuscated Gradients Give a False Sense of Security: Circumventing Defenses to Adversarial Examples", 2018: the introduction and the conclusions. arxiv.org/abs/1802.00420
- Nicholas Carlini et al., "On Evaluating Adversarial Robustness", 2019: the principles of evaluation and the list of checks. arxiv.org/abs/1902.06705
- David Manheim, Scott Garrabrant, "Categorizing Variants of Goodhart's Law", 2018.
- C. J. Clopper, E. S. Pearson, "The Use of Confidence or Fiducial Limits Illustrated in the Case of the Binomial", Biometrika, 1934.
- Spectorn, "28 questions to a green test suite": the index of questions.
Further reading
- Victoria Krakovna et al., "Specification gaming: the flip side of AI ingenuity", 2020.
- METR, "Recent Frontier Models Are Reward Hacking", 2025.
- Carson Denison et al., "Sycophancy to Subterfuge: Investigating Reward-Tampering in Large Language Models", 2024.
- Milad Nasr, Nicholas Carlini et al., "The Attacker Moves Second: Stronger Adaptive Attacks Bypass Defenses Against LLM Jailbreaks and Prompt Injections", 2025.
- Lawrence Brown, T. Tony Cai, Anirban DasGupta, "Interval Estimation for a Binomial Proportion", Statistical Science, 2001.
- Boaz Barak, the course CS 2881R AI Safety, Harvard University: the session on evaluation and reward hacking. boazbk.github.io/mltheoryseminar
Lab
Goal: get a green result from a detector that can do nothing outside its own corpus, and then report on it honestly. The data is synthetic: the "attacks" are strings with made-up marker words. The lab's numbers describe the toy and say nothing about any real detector or product.
The threshold is chosen before the measurement: τ = 5%. The claim under test: "the miss rate is below 5%".
Save the code to a file named lab_goodhart.py and run python3 lab_goodhart.py.
import math
ALPHA = 0.05 # one-sided 95% bound
TAU = 0.05 # threshold chosen before the measurement
FAMILIES = ["zorbak", "quillex", "mivoro", "tandrel", "pexuli", "roswen", "ublati", "kyndra"]
DEV_FAMILIES = FAMILIES[:6] # the detector was tuned on these families
HELD_OUT_FAMILIES = FAMILIES[6:] # these families were not seen during tuning
def variants(source):
return [source, source.upper(), "please, " + source, source.replace(" ", " ")]
def corpus(families):
# key: an independent source sample; value: its variants
return {
f"{family}-{number}": variants(f"{family} synthetic request {number}")
for family in families
for number in range(1, 6)
}
def tuned_detector(text):
return any(marker in text.lower() for marker in DEV_FAMILIES)
def broken_detector(text):
return False
def missed_rows(detector, samples):
return sum(1 for rows in samples.values() for row in rows if not detector(row))
def total_rows(samples):
return sum(len(rows) for rows in samples.values())
def missed_sources(detector, samples):
# a sample is missed if at least one of its variants is missed
return sum(1 for rows in samples.values() if any(not detector(row) for row in rows))
# Exact one-sided Clopper-Pearson bounds, standard library only.
# The same calculation as in the lab of the first module and in scripts/rate_bounds.py.
def binom_cdf(k, n, p):
total = 0.0
for i in range(k + 1):
log_term = math.lgamma(n + 1) - math.lgamma(i + 1) - math.lgamma(n - i + 1)
log_term += i * math.log(p) + (n - i) * math.log1p(-p)
total += math.exp(log_term)
return total
def upper_bound(k, n):
if k == n:
return 1.0
low, high = k / n, 1.0
for _ in range(100):
middle = (low + high) / 2
if binom_cdf(k, n, middle) > ALPHA:
low = middle
else:
high = middle
return high
def lower_bound(k, n):
if k == 0:
return 0.0
low, high = 0.0, k / n
for _ in range(100):
middle = (low + high) / 2
if 1.0 - binom_cdf(k - 1, n, middle) < ALPHA:
low = middle
else:
high = middle
return low
def report(label, events, trials):
low, high = lower_bound(events, trials), upper_bound(events, trials)
if high < TAU:
verdict = "VERIFIED"
elif low >= TAU:
verdict = "NOT VERIFIED"
else:
verdict = "INCONCLUSIVE"
print(f"{label}: {events}/{trials} = {events / trials:.2%}, "
f"bounds [{low:.2%}, {high:.2%}], threshold {TAU:.0%}: {verdict}")
dev = corpus(DEV_FAMILIES)
held_out = corpus(HELD_OUT_FAMILIES)
report("own corpus, trial = row", missed_rows(tuned_detector, dev), total_rows(dev))
report("own corpus, trial = sample", missed_sources(tuned_detector, dev), len(dev))
report("held-out families, trial = sample", missed_sources(tuned_detector, held_out), len(held_out))
def check_that_cannot_fail(detector):
return missed_rows(detector, dev) <= total_rows(dev)
def check_that_can_fail(detector):
return missed_sources(detector, dev) == 0
for name, check in (("check that cannot fail", check_that_cannot_fail),
("check that can fail", check_that_can_fail)):
print(name, "| tuned detector:", check(tuned_detector),
"| broken detector:", check(broken_detector))
What to do:
- Run the script and copy the three measurement lines into your report.
- Compare the first two lines. The detector and the data are the same, and only the unit of a trial has changed. Explain why the first line overstates confidence.
- Look at the third line and name the mechanism from the module text that it shows.
- Look at the last two lines of the output. This is a mutation check: the detector was replaced with a broken one. Which of the two checks guards anything?
- Write a mutation of your own: add a fifth variant to
variantsthat breaks the marker with an extraneous character, and run the script again. Record how the second line changed.
What you should get in steps one to four:
| Measurement | Events and trials | 95% bounds | Verdict at τ = 5% |
|---|---|---|---|
| Own corpus, trial = row | 0 out of 120 | from 0% to 2.47% | VERIFIED |
| Own corpus, trial = sample | 0 out of 30 | from 0% to 9.50% | INCONCLUSIVE |
| Held-out families, trial = sample | 10 out of 10 | from 74.11% to 100% | NOT VERIFIED |
The check that cannot fail returns True for both the tuned and the broken detector. The check
that can fail returns True for the tuned detector and False for the broken one.
The first row of the table is the green result that misleads: it was obtained on the detector's
own corpus and by counting variants as trials. The honest report consists of the second and third
rows. Check the second row against the tool in the Spectorn repository:
python3 scripts/rate_bounds.py claim 0 30 --tau 0.05.
In your report, include the table with your own numbers, the result of step 5, and one sentence
on how many independent samples without a single miss it would take to get the verdict VERIFIED
at a 5% threshold.
Self-check questions
- A corpus consists of 40 attacks, each recorded in five paraphrases. The detector missed none of the 200 rows. How many trials are there, what upper bound on the miss rate will you report, and what verdict does the claim "the miss rate is below 5%" get?
- After a rule was edited, the false-positive rate halved, while recall on your own corpus stayed the same. Which three questions will you ask before you call this an improvement?
- An agent reported that it fixed a defect and that all tests are green. Its changes include an edit to a test file. What will you check, and how will you make sure that the test can still fail?
Previous module: "LLMs for security engineers". Next module: "Model policy and gateway policy".