forked from ChelseaKR/fare-policy-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_sensitivity.py
More file actions
401 lines (335 loc) · 13.8 KB
/
Copy pathtest_sensitivity.py
File metadata and controls
401 lines (335 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"""Counterfactual sensitivity suite (EXP-02).
The sensitivity suite is written as `pairs:` of minimal-pair `variants:`; the
runner flattens each variant into an ordinary case carrying a `pair_id`, scores
every variant with the same deterministic checks, then re-groups the results
into a pair-level verdict. A pair is only "distinguished" if every variant
passed — that is what proves the answer changed (or held) across the boundary
rather than one boilerplate answer satisfying one side.
These tests exercise loading/flattening, the pair-verdict logic, the summary
plumbing, and the report line, all offline (no model calls, no cost).
"""
from __future__ import annotations
import json
import pytest
from assistant import config
from evals import report, runner
@pytest.fixture
def tmp_runs(tmp_path, monkeypatch):
runs = tmp_path / "runs"
monkeypatch.setattr(config, "EVAL_RUNS_DIR", runs)
return runs
# ── loading / flattening ─────────────────────────────────────────────────────
def test_sensitivity_suite_loads_and_flattens_variants_into_cases():
(suite,) = runner.load_suites(only="sensitivity")
assert suite["suite"] == "sensitivity"
assert suite["pairs"], "the suite is authored as pairs"
# Every pair contributes its variants to a flat `cases` list.
expected_cases = sum(len(p["variants"]) for p in suite["pairs"])
assert len(suite["cases"]) == expected_cases
for case in suite["cases"]:
assert case["suite"] == "sensitivity"
assert case["pair_id"], "each flattened variant carries its parent pair id"
assert case["boundary"], "each variant inherits the pair's boundary description"
assert "question" in case and "expected_behavior" in case
def test_sensitivity_suite_has_about_fifteen_pairs_with_unique_variant_ids():
(suite,) = runner.load_suites(only="sensitivity")
assert 13 <= len(suite["pairs"]) <= 18, "~15 boundary pairs"
ids = [c["id"] for c in suite["cases"]]
assert len(ids) == len(set(ids)), "variant ids are unique"
# Variant ids nest under their pair id (sens-001 → sens-001a / sens-001b).
for case in suite["cases"]:
assert case["id"].startswith(case["pair_id"])
def test_committed_sensitivity_suite_validates():
runner.validate_cases(runner.load_suites(only="sensitivity"))
# And it does not break whole-corpus validation either.
runner.validate_cases(runner.load_suites())
# ── pair-validation guards ───────────────────────────────────────────────────
def test_validate_rejects_pair_with_a_single_variant():
bad = [
{
"pairs": [
{
"id": "sens-x",
"boundary": "b",
"variants": [
{
"id": "sens-xa",
"question": "q?",
"expected_behavior": "answer",
"rationale": "r",
}
],
}
],
}
]
with pytest.raises(SystemExit, match="at least two variants"):
runner.validate_cases(bad)
def test_validate_rejects_pair_missing_boundary():
bad = [
{
"pairs": [
{
"id": "sens-y",
"variants": [
{
"id": "sens-ya",
"question": "q?",
"expected_behavior": "answer",
"rationale": "r",
},
{
"id": "sens-yb",
"question": "q?",
"expected_behavior": "answer",
"rationale": "r",
},
],
}
],
}
]
with pytest.raises(SystemExit, match="missing `boundary`"):
runner.validate_cases(bad)
# ── pair-verdict logic ───────────────────────────────────────────────────────
def test_pair_passes_only_when_every_variant_passes():
records = [
{"pair_id": "sens-001", "passed": True},
{"pair_id": "sens-001", "passed": True},
]
assert runner.pair_verdicts(records) == {"sens-001": True}
def test_mixed_pass_fail_pair_reports_failed():
records = [
{"pair_id": "sens-001", "passed": True},
{"pair_id": "sens-001", "passed": False}, # one side held, the other didn't
]
assert runner.pair_verdicts(records) == {"sens-001": False}
def test_pair_verdicts_groups_multiple_pairs_and_ignores_unpaired_records():
records = [
{"pair_id": "sens-001", "passed": True},
{"pair_id": "sens-001", "passed": True},
{"pair_id": "sens-002", "passed": True},
{"pair_id": "sens-002", "passed": False},
{"pair_id": None, "passed": False}, # ordinary (non-pair) case
{"suite": "refusal", "passed": True}, # no pair_id key at all
]
verdicts = runner.pair_verdicts(records)
assert verdicts == {"sens-001": True, "sens-002": False}
assert sum(verdicts.values()) == 1
# ── end-to-end offline run records pair stats ────────────────────────────────
def test_offline_sensitivity_run_writes_pairs_passed_and_total(tmp_runs):
run_dir = runner.run(offline=True, suite="sensitivity")
summary = json.loads((run_dir / "summary.json").read_text())
sens = summary["suites"]["sensitivity"]
assert "pairs_passed" in sens and "pairs_total" in sens
# One pair per authored boundary; total variants exceed the pair count.
(suite,) = runner.load_suites(only="sensitivity")
assert sens["pairs_total"] == len(suite["pairs"])
assert sens["total"] == sum(len(p["variants"]) for p in suite["pairs"])
assert 0 <= sens["pairs_passed"] <= sens["pairs_total"]
# Every trace in the run carries its pair id.
records = [json.loads(x) for x in (run_dir / "results.jsonl").read_text().splitlines()]
assert records and all(r["pair_id"] for r in records)
# ── report line ──────────────────────────────────────────────────────────────
def test_report_renders_boundary_pairs_line():
summary = {
"run_at": "2026-07-02T00:00:00+00:00",
"mode": "full",
"offline": True,
"judges_ran": False,
"answer_model": "mock",
"judge_model": "mock",
"prompt_versions": {"system": "v1"},
"duration_seconds": 1.0,
"suites": {
"sensitivity": {
"passed": 24,
"total": 30,
"pass_rate": 80.0,
"pairs_passed": 12,
"pairs_total": 15,
}
},
"total": {"passed": 24, "total": 30},
}
md = report.generate_markdown(summary, [])
assert "12/15 boundary pairs passed" in md
def test_report_omits_sensitivity_line_when_no_pair_stats():
summary = {
"run_at": "2026-07-02T00:00:00+00:00",
"mode": "full",
"offline": True,
"judges_ran": False,
"answer_model": "mock",
"judge_model": "mock",
"prompt_versions": {"system": "v1"},
"duration_seconds": 1.0,
"suites": {"refusal": {"passed": 1, "total": 1, "pass_rate": 100.0}},
"total": {"passed": 1, "total": 1},
}
md = report.generate_markdown(summary, [])
assert "boundary pairs passed" not in md
# ── the pair's own denominator ───────────────────────────────────────────────
#
# A pair verdict claims the assistant discriminated across a boundary. That
# claim rests on the two variants demanding different evidence, and on the two
# answers actually coming out different. Neither was checked until 2026-08-05,
# and the promoted report's "13/15 correctly distinguished" was published over
# two pairs whose variants asked for exactly the same thing.
def _variant(case_id, pair_id, **kw):
case = {
"id": case_id,
"pair_id": pair_id,
"expected_behavior": "answer",
"agency_scope": "MST",
"language": "en",
"required_facts": ["65"],
}
case.update(kw)
return case
def test_pair_gate_flags_variants_that_demand_identical_evidence():
cases = {c["id"]: c for c in [_variant("p-a", "p"), _variant("p-b", "p")]}
(problem,) = runner.pair_problems(cases)
assert "p-a, p-b" in problem
assert "one answer satisfies both sides" in problem
def test_pair_gate_accepts_variants_whose_demands_differ():
cases = {
c["id"]: c
for c in [
_variant("p-a", "p", required_facts=["65"]),
_variant("p-b", "p", required_facts=["62"]),
]
}
assert runner.pair_problems(cases) == []
def test_pair_gate_accepts_a_variant_that_only_adds_forbidden_content():
cases = {
c["id"]: c
for c in [
_variant("p-a", "p"),
_variant("p-b", "p", forbidden_content=["rides free"]),
]
}
assert runner.pair_problems(cases) == []
def test_pair_gate_flags_a_variant_that_demands_nothing():
cases = {
c["id"]: c
for c in [
_variant("p-a", "p", required_facts=[]),
_variant("p-b", "p", required_facts=["62"]),
]
}
(problem,) = runner.pair_problems(cases)
assert "declares neither required_facts nor forbidden_content" in problem
def test_pair_gate_ignores_ordinary_cases():
assert runner.pair_problems({"edge-001": {"id": "edge-001", "required_facts": ["65"]}}) == []
def test_check_pairs_passes_on_the_committed_suites():
runner.check_pairs() # no raise
def test_check_pairs_refuses_to_run_an_eval_over_undifferentiated_pairs(monkeypatch, capsys):
"""The gate runs before the first model call, like check_mirrors: a run that
cannot measure what it reports should not be paid for."""
monkeypatch.setattr(
runner,
"load_suites",
lambda: [{"cases": [_variant("p-a", "p"), _variant("p-b", "p")]}],
)
with pytest.raises(SystemExit) as exc:
runner.check_pairs()
assert exc.value.code == 1
assert "MINIMAL-PAIR GATE" in capsys.readouterr().err
def test_discrimination_marks_interchangeable_answers():
cases = {
c["id"]: c
for c in [
_variant("p-a", "p", required_facts=["65"]),
_variant("p-b", "p", required_facts=["62"]),
]
}
both = "Seniors are 65+ on MST and 62+ on Yolobus."
result = runner.pair_discrimination(
[{"case_id": "p-a", "answer": both}, {"case_id": "p-b", "answer": both}], cases
)
assert result["p"]["discriminating"] is False
assert len(result["p"]["interchangeable"]) == 2
def test_discrimination_marks_answers_the_checks_can_tell_apart():
cases = {
c["id"]: c
for c in [
_variant("p-a", "p", required_facts=["65"]),
_variant("p-b", "p", required_facts=["62"]),
]
}
result = runner.pair_discrimination(
[
{"case_id": "p-a", "answer": "Seniors are 65+ on MST."},
{"case_id": "p-b", "answer": "Seniors are 62+ on Yolobus."},
],
cases,
)
assert result["p"]["discriminating"] is True
assert result["p"]["interchangeable"] == []
def test_discrimination_skips_a_pair_whose_variants_are_not_all_in_the_run():
"""A smoke subset that kept one side of a pair is out of view, not evidence
that the pair fails to discriminate."""
cases = {
c["id"]: c for c in [_variant("p-a", "p"), _variant("p-b", "p", required_facts=["62"])]
}
assert runner.pair_discrimination([{"case_id": "p-a", "answer": "65"}], cases) == {}
def test_report_publishes_how_many_pairs_could_be_told_apart():
summary = {
"run_at": "2026-07-02T00:00:00+00:00",
"mode": "full",
"offline": True,
"judges_ran": False,
"answer_model": "mock",
"judge_model": "mock",
"prompt_versions": {"system": "v1"},
"duration_seconds": 1.0,
"suites": {
"sensitivity": {
"passed": 4,
"total": 4,
"pass_rate": 100.0,
"pairs_passed": 2,
"pairs_total": 2,
}
},
"total": {"passed": 4, "total": 4},
}
same = "Stored Value passes are eligible; no reduced fare on Day, Week, or Month passes."
records = [
{
"case_id": "sens-011a",
"suite": "sensitivity",
"passed": True,
"checks": [],
"judges": [],
"answer": same,
},
{
"case_id": "sens-011b",
"suite": "sensitivity",
"passed": True,
"checks": [],
"judges": [],
"answer": same,
},
{
"case_id": "sens-002a",
"suite": "sensitivity",
"passed": True,
"checks": [],
"judges": [],
"answer": "On MST a senior is 65+.",
},
{
"case_id": "sens-002b",
"suite": "sensitivity",
"passed": True,
"checks": [],
"judges": [],
"answer": "62+ on HTA.",
},
]
md = report.generate_markdown(summary, records)
assert "produced answers the per-variant checks can tell apart" in md
assert "Interchangeable pairs: sens-011." in md