forked from ChelseaKR/fare-policy-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.py
More file actions
2934 lines (2701 loc) · 119 KB
/
Copy pathrunner.py
File metadata and controls
2934 lines (2701 loc) · 119 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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Eval runner.
python -m evals.runner --smoke # 26-case CI subset
The smoke subset's gated suites are small (4-6 cases each), so the below-macro
gate (`suites_below_macro`, ADR 0026) can only express a 2-case tolerance on
smoke, not a percentage one: a single failure in any gated suite is absorbed
as judge noise, and a second failure in the same suite is what actually fails
the build. This is coarser than the full suite's effective tolerance (every
full-run gated suite is large enough that a genuine breach already implies
several cases) and is a property of the sample size, not a relaxed gate.
python -m evals.runner --full # everything, then regenerate reports
python -m evals.runner --offline # mock model, deterministic checks only
python -m evals.runner --suite refusal # one suite
python -m evals.runner --jobs 8 # bounded-concurrency case execution
python -m evals.runner --no-cache # skip the answer/judge cache (FIX-04 runs)
python -m evals.runner --refresh-cache # re-call the provider, then restore the cache
python -m evals.runner --only-failed # rerun only cases that failed last time
python -m evals.runner --since 20260701T000000Z # reuse unchanged cases from that run
python -m evals.runner --replicates 3 # score every case 3x, Wilson intervals
Each run writes evals/runs/<timestamp>/ with results.jsonl (full traces) and
summary.json (scoreboard + versions). Judges run only when provider
credentials are available (AWS chain for bedrock, ANTHROPIC_API_KEY for
anthropic); otherwise judge verdicts are recorded as skipped, never as passes.
Cases execute under a bounded-concurrency ThreadPoolExecutor (`--jobs`,
default 4 — the pipeline is pure functions over an immutable retriever, and
4-8 workers fits Bedrock rate limits). Each case's multi-turn history replay
still runs sequentially within its own worker, so turns are never interleaved.
Answer and judge model calls are served from a content-keyed on-disk cache
(evals/cache.py) by default, so an incremental re-run after a one-prompt or
one-corpus change only pays for the cases that actually changed; `--no-cache`
disables this for runs that need to measure real model variance (FIX-04). CI
persists that cache across runs, so the cost of an unchanged suite is paid once
rather than once per pull request; `--refresh-cache` is the weekly cold run
that re-measures the provider and rewrites the stored answers (ADR 0022).
Variance runs (`--replicates N`, N > 1) score every case N times — a case's
replicate passes run sequentially inside its worker — and report a per-suite
mean pass rate with a Wilson 95% interval. A replicate run always bypasses the
cache (a cache-served replicate returns byte-identical answers and verdicts and
would measure zero variance) and cannot combine with `--since`/`--only-failed`
(reused cases contribute no fresh trials). A replicated multi-turn case replays
its history on every pass and pays for it every pass.
"""
from __future__ import annotations
import argparse
import collections
import csv
import hashlib
import io
import json
import math
import os
import stat
import sys
import tempfile
import time
from collections.abc import Iterator, Mapping, Sequence
from concurrent.futures import ThreadPoolExecutor, as_completed
from contextlib import contextmanager
from dataclasses import asdict, dataclass
from datetime import UTC, datetime
from decimal import Decimal, InvalidOperation
from pathlib import Path
import yaml
from assistant import config, corpus, fare_table
from assistant.answer import AnswerResult, answer_question
from assistant.facts import FareFact
from assistant.identity import SnapshotIdentity
from assistant.ingest import Chunk
from assistant.models import Model, get_model
from assistant.release_identity import (
PROMPT_NAMES,
ConfigIdentity,
ReleaseIdentityError,
build_config_identity,
build_release_identity,
load_release_descriptor,
resolve_current_snapshot,
verify_release_descriptor,
)
from assistant.retrieve import Retriever
from evals import attestation as eval_attestation
from evals import checks, judges
from evals.cache import CachingModel, EvalCache, case_content_key
from evals.checks import run_checks
from evals.stats import wilson_interval
_EFFECTIVE_ENVIRONMENT_JSON = "FPA_RELEASE_EFFECTIVE_ENVIRONMENT_JSON"
EVAL_RUN_BUNDLE_SCHEMA = "fare-assistant.eval-run-bundle.v1"
EVAL_RUN_BUNDLE_POINTER_SCHEMA = "fare-assistant.eval-run-bundle-pointer.v1"
# Environment-backed behavior that must not leak in from the shell when a
# deployment supplies an exact effective Lambda environment. Credentials are
# deliberately absent: model SDKs continue to use the caller's standard
# credential chain, while every answer-affecting setting is overlaid exactly.
_EVAL_BEHAVIOR_ENV = frozenset(
{
"AWS_REGION",
"ANTHROPIC_BASE_URL",
"ANTHROPIC_BEDROCK_BASE_URL",
"ANTHROPIC_CUSTOM_HEADERS",
"FPA_ANSWER_MODEL",
"FPA_DENSE",
"FPA_DISABLED_DOC_IDS",
"FPA_DOMAIN",
"FPA_EMBED_ANCESTORS",
"FPA_HISTORY_HMAC_KEY",
"FPA_HISTORY_HMAC_KEY_ID",
"FPA_JUDGE_MODEL",
"FPA_OLLAMA_HOST",
"FPA_PROVIDER",
"FPA_STALENESS_BUDGET_DAYS",
}
)
@dataclass(frozen=True)
class _CapturedFile:
"""One race-checked regular file read exactly once."""
path: Path
raw: bytes
sha256: str
@property
def receipt(self) -> dict[str, object]:
return {"sha256": self.sha256, "bytes": len(self.raw)}
@dataclass(frozen=True)
class _CapturedEvaluationInputs:
chunks: tuple[Chunk, ...]
facts: tuple[FareFact, ...]
manifest: Mapping[str, object]
prompts: Mapping[str, str]
config_identity: ConfigIdentity
snapshot_identity: SnapshotIdentity
facts_identity: Mapping[str, object]
gtfs_identity: Mapping[str, object]
structured_fares_by_agency: Mapping[
str,
tuple[fare_table.StructuredFare, ...],
]
@dataclass(frozen=True)
class _RunBundle:
run_dir: Path
bundle_path: Path
content_address: str
summary_sha256: str
results_sha256: str
def pointer(self) -> dict[str, str]:
return {
"schema": EVAL_RUN_BUNDLE_POINTER_SCHEMA,
"run_dir": str(self.run_dir),
"bundle_path": str(self.bundle_path),
"content_address": self.content_address,
"summary_sha256": self.summary_sha256,
"results_sha256": self.results_sha256,
}
def _canonical_json_bytes(value: object) -> bytes:
return (
json.dumps(
value,
allow_nan=False,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
)
+ "\n"
).encode("utf-8")
def _jsonl_lines(raw: bytes, context: str) -> list[str]:
"""Split canonical JSONL only on ASCII LF, preserving Unicode separators."""
try:
text = raw.decode("utf-8")
except UnicodeDecodeError as exc:
raise eval_attestation.EvalAttestationError(f"{context} must be valid UTF-8") from exc
if not text:
raise eval_attestation.EvalAttestationError(
f"{context} must contain at least one JSON record"
)
if "\r" in text:
raise eval_attestation.EvalAttestationError(f"{context} must use ASCII LF line endings")
if not text.endswith("\n"):
raise eval_attestation.EvalAttestationError(
f"{context} must end with one ASCII LF after the final JSON record"
)
lines = text[:-1].split("\n")
if any(not line for line in lines):
raise eval_attestation.EvalAttestationError(
f"{context} must contain exactly one JSON record per non-empty line"
)
return lines
def _stat_fingerprint(value: os.stat_result) -> tuple[int, ...]:
return (
value.st_dev,
value.st_ino,
value.st_mode,
value.st_size,
value.st_mtime_ns,
value.st_ctime_ns,
)
def _capture_regular_file(
path: Path,
context: str,
*,
optional: bool = False,
) -> _CapturedFile | None:
"""Read one regular file and reject replacement or mutation during read."""
try:
before = path.lstat()
except FileNotFoundError:
if optional:
try:
path.lstat()
except FileNotFoundError:
return None
raise eval_attestation.EvalAttestationError(f"{context} is missing: {path}") from None
except OSError as exc:
raise eval_attestation.EvalAttestationError(
f"{context} could not be inspected: {path}"
) from exc
if stat.S_ISLNK(before.st_mode) or not stat.S_ISREG(before.st_mode):
raise eval_attestation.EvalAttestationError(f"{context} is not a regular file: {path}")
flags = os.O_RDONLY | getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
try:
descriptor = os.open(path, flags)
except OSError as exc:
raise eval_attestation.EvalAttestationError(
f"{context} could not be opened safely: {path}"
) from exc
chunks: list[bytes] = []
try:
opened = os.fstat(descriptor)
if not stat.S_ISREG(opened.st_mode) or _stat_fingerprint(opened) != _stat_fingerprint(
before
):
raise eval_attestation.EvalAttestationError(
f"{context} changed while it was opened: {path}"
)
while block := os.read(descriptor, 1024 * 1024):
chunks.append(block)
after_read = os.fstat(descriptor)
except OSError as exc:
raise eval_attestation.EvalAttestationError(
f"{context} could not be read completely: {path}"
) from exc
finally:
os.close(descriptor)
try:
after_path = path.lstat()
except OSError as exc:
raise eval_attestation.EvalAttestationError(
f"{context} changed while it was read: {path}"
) from exc
fingerprint = _stat_fingerprint(before)
if _stat_fingerprint(after_read) != fingerprint or _stat_fingerprint(after_path) != fingerprint:
raise eval_attestation.EvalAttestationError(f"{context} changed while it was read: {path}")
raw = b"".join(chunks)
if len(raw) != before.st_size:
raise eval_attestation.EvalAttestationError(
f"{context} changed size while it was read: {path}"
)
return _CapturedFile(path, raw, hashlib.sha256(raw).hexdigest())
def _regular_directory(path: Path, context: str, *, optional: bool = False) -> bool:
try:
info = path.lstat()
except FileNotFoundError:
if optional:
return False
raise eval_attestation.EvalAttestationError(f"{context} is missing: {path}") from None
except OSError as exc:
raise eval_attestation.EvalAttestationError(
f"{context} could not be inspected: {path}"
) from exc
if stat.S_ISLNK(info.st_mode) or not stat.S_ISDIR(info.st_mode):
raise eval_attestation.EvalAttestationError(f"{context} is not a regular directory: {path}")
return True
def _decode_utf8(captured: _CapturedFile, context: str) -> str:
try:
return captured.raw.decode("utf-8")
except UnicodeDecodeError as exc:
raise eval_attestation.EvalAttestationError(
f"{context} must be valid UTF-8: {captured.path}"
) from exc
def _prompt_version_from_text(name: str, prompt: str) -> str:
lines = prompt.splitlines()
if not lines:
raise eval_attestation.EvalAttestationError(f"{name} prompt must contain a version header")
version = lines[0].lstrip("# ").strip()
if not version:
raise eval_attestation.EvalAttestationError(
f"{name} prompt version header must not be empty"
)
return version
def _parse_chunks(captured: _CapturedFile) -> tuple[Chunk, ...]:
rows: list[Chunk] = []
try:
for line in _jsonl_lines(captured.raw, "captured chunks"):
rows.append(Chunk(**json.loads(line)))
except (json.JSONDecodeError, TypeError, KeyError) as exc:
raise eval_attestation.EvalAttestationError("captured chunks are malformed") from exc
if not rows:
raise eval_attestation.EvalAttestationError("captured chunks must not be empty")
return tuple(rows)
def _parse_facts(captured: _CapturedFile) -> tuple[FareFact, ...]:
rows: list[FareFact] = []
try:
for line in _jsonl_lines(captured.raw, "captured facts"):
rows.append(FareFact(**json.loads(line)))
except (json.JSONDecodeError, TypeError, KeyError) as exc:
raise eval_attestation.EvalAttestationError("captured facts are malformed") from exc
return tuple(rows)
def _parse_manifest(captured: _CapturedFile) -> Mapping[str, object]:
try:
value = yaml.safe_load(captured.raw)
except yaml.YAMLError as exc:
raise eval_attestation.EvalAttestationError("captured manifest is malformed") from exc
if not isinstance(value, Mapping):
raise eval_attestation.EvalAttestationError("captured manifest must be an object")
return value
def _facts_identity(captured: _CapturedFile) -> dict[str, object]:
receipt = captured.receipt
return {
"schema": eval_attestation.FACTS_SCHEMA,
"facts_version": eval_attestation.canonical_digest(
eval_attestation.FACTS_SCHEMA,
{"receipt": receipt},
),
"receipt": receipt,
}
def _structured_fares_from_bytes(
agency: str,
*,
fare_attributes: bytes | None = None,
fare_products: bytes | None = None,
rider_categories: bytes | None = None,
) -> tuple[fare_table.StructuredFare, ...]:
"""Parse the exact captured fare bytes without reopening GTFS files."""
def rows(raw: bytes | None) -> list[dict[str, str]]:
if raw is None:
return []
return list(
csv.DictReader(
io.StringIO(raw.decode("utf-8-sig"), newline=""),
)
)
categories: dict[str, fare_table.RiderCategory] = {}
for row in rows(rider_categories):
category_id = row.get("rider_category_id")
if not category_id:
continue
categories[category_id] = fare_table.RiderCategory(
id=category_id,
name=(row.get("rider_category_name") or category_id).strip(),
eligibility_url=(row.get("eligibility_url") or "").strip() or None,
)
fares: list[fare_table.StructuredFare] = []
if fare_products is not None:
for row in rows(fare_products):
try:
amount = Decimal(row["amount"])
except (InvalidOperation, KeyError):
continue
try:
product_id = row["fare_product_id"]
except KeyError as exc:
raise eval_attestation.EvalAttestationError(
f"captured GTFS v2 fare row is missing fare_product_id for {agency}"
) from exc
fares.append(
fare_table.StructuredFare(
agency=agency,
product=row.get("fare_product_name") or product_id,
amount=amount,
rider_category=categories.get(row.get("rider_category_id") or ""),
)
)
return tuple(fares)
if fare_attributes is not None:
for row in rows(fare_attributes):
try:
amount = Decimal(row["price"])
except (InvalidOperation, KeyError):
continue
try:
fare_id = row["fare_id"]
except KeyError as exc:
raise eval_attestation.EvalAttestationError(
f"captured GTFS v1 fare row is missing fare_id for {agency}"
) from exc
fares.append(
fare_table.StructuredFare(
agency=agency,
product=fare_id,
amount=amount,
rider_category=None,
)
)
return tuple(fares)
def _capture_gtfs_inputs(
manifest: Mapping[str, object],
) -> tuple[
dict[str, object],
dict[str, tuple[fare_table.StructuredFare, ...]],
]:
"""Capture each GTFS byte used by deterministic fare checks exactly once."""
feeds = eval_attestation._configured_feeds(manifest)
root = config.RAW_DIR / "gtfs"
if root.exists() or root.is_symlink():
_regular_directory(root, "GTFS root")
fares_by_agency = {}
agencies = []
for feed in feeds:
agency = str(feed["agency"])
agency_dir = root / agency
files: list[dict[str, object]] = []
raw_files: dict[str, bytes] = {}
if _regular_directory(
agency_dir,
f"GTFS agency directory {agency}",
optional=True,
):
for member in eval_attestation.GTFS_LEGACY_CONSUMED_MEMBERS:
captured = _capture_regular_file(
agency_dir / member,
f"GTFS member {agency}/{member}",
optional=True,
)
if captured is None:
continue
raw_files[member] = captured.raw
files.append({"path": f"{agency}/{member}", **captured.receipt})
try:
fares_by_agency[agency] = _structured_fares_from_bytes(
agency,
fare_attributes=raw_files.get("fare_attributes.txt"),
fare_products=raw_files.get("fare_products.txt"),
rider_categories=raw_files.get("rider_categories.txt"),
)
except (UnicodeError, csv.Error) as exc:
raise eval_attestation.EvalAttestationError(
f"captured GTFS fare inputs are malformed for {agency}"
) from exc
agencies.append(
{
"agency": agency,
"state": "legacy_extracted_only" if files else "unavailable",
"files": files,
}
)
payload = {
"gtfs_feeds": feeds,
"consumed_members": list(eval_attestation.GTFS_LEGACY_CONSUMED_MEMBERS),
"agencies": agencies,
}
return (
{
"schema": eval_attestation.GTFS_LEGACY_INPUT_SCHEMA,
"gtfs_input_version": eval_attestation.canonical_digest(
eval_attestation.GTFS_LEGACY_INPUT_SCHEMA,
payload,
),
"consumed_members": list(eval_attestation.GTFS_LEGACY_CONSUMED_MEMBERS),
"agencies": agencies,
},
fares_by_agency,
)
def _capture_evaluation_inputs(
*,
cfg: config.Config,
environment: Mapping[str, str],
) -> _CapturedEvaluationInputs:
chunks_capture = _capture_regular_file(config.CHUNKS_PATH, "chunks")
facts_capture = _capture_regular_file(config.FACTS_PATH, "facts")
manifest_capture = _capture_regular_file(config.MANIFEST_PATH, "manifest")
answer_schema_capture = _capture_regular_file(
config.ANSWER_SCHEMA_PATH,
"answer contract",
)
assert (
chunks_capture is not None
and facts_capture is not None
and manifest_capture is not None
and answer_schema_capture is not None
)
prompt_captures: dict[str, _CapturedFile] = {}
for name in PROMPT_NAMES:
captured = _capture_regular_file(
config.PROMPTS_DIR / f"{name}.txt",
f"{name} prompt",
)
assert captured is not None
prompt_captures[name] = captured
prompts = {
name: _decode_utf8(captured, f"{name} prompt") for name, captured in prompt_captures.items()
}
chunks = _parse_chunks(chunks_capture)
facts = _parse_facts(facts_capture)
manifest = _parse_manifest(manifest_capture)
config_identity = build_config_identity(
environment,
resolved_config=cfg,
captured_prompt_bytes={name: captured.raw for name, captured in prompt_captures.items()},
captured_answer_schema_bytes=answer_schema_capture.raw,
)
snapshot_identity = resolve_current_snapshot(
chunks=chunks,
manifest=manifest,
)
gtfs_identity, structured_fares_by_agency = _capture_gtfs_inputs(manifest)
return _CapturedEvaluationInputs(
chunks=chunks,
facts=facts,
manifest=manifest,
prompts=prompts,
config_identity=config_identity,
snapshot_identity=snapshot_identity,
facts_identity=_facts_identity(facts_capture),
gtfs_identity=gtfs_identity,
structured_fares_by_agency=structured_fares_by_agency,
)
def _flatten_pairs(data: dict) -> list[dict]:
"""A sensitivity suite is written as `pairs:` of minimal-pair `variants:`.
Flatten each variant into an ordinary case dict carrying a `pair_id` (the
parent pair's id) and the pair's `boundary`, so every downstream consumer —
validation, checks.py grading, credential gating, scoring — treats it as a
normal case. The variants are re-grouped by `pair_id` only for the
pair-level verdict (`pair_verdicts`), never for scoring.
"""
cases = []
for pair in data["pairs"]:
for variant in pair["variants"]:
variant["pair_id"] = pair["id"]
variant.setdefault("boundary", pair.get("boundary"))
cases.append(variant)
return cases
def load_suites(only: str | None = None) -> list[dict]:
suites = []
for path in sorted(config.EVAL_SUITES_DIR.glob("*.yaml")):
if only and path.stem != only:
continue
data = yaml.safe_load(path.read_text(encoding="utf-8"))
if "pairs" in data and "cases" not in data:
data["cases"] = _flatten_pairs(data)
for case in data["cases"]:
case["suite"] = path.stem
suites.append(data)
return suites
def validate_cases(suites: list[dict]) -> None:
seen: set[str] = set()
required = {"id", "expected_behavior", "rationale"}
for suite in suites:
# Sensitivity suites carry minimal pairs that are flattened into cases.
for pair in suite.get("pairs", []):
if not pair.get("id"):
raise SystemExit("sensitivity pair missing `id`")
if not pair.get("boundary"):
raise SystemExit(f"pair {pair['id']}: missing `boundary`")
if len(pair.get("variants", [])) < 2:
raise SystemExit(f"pair {pair['id']}: needs at least two variants")
cases = suite.get("cases")
if cases is None and "pairs" in suite:
cases = _flatten_pairs(suite)
for case in cases or []:
# Auto-drafted skeletons (assistant.scaffold_agency) carry
# `draft: true`. They have TODO questions and empty required_facts,
# so they must never run or land in results: a human fills the facts
# and removes the flag first. Refuse the whole run if any survive.
if case.get("draft"):
raise SystemExit(
f"case {case.get('id', '?')}: `draft: true` — fill it in and "
"remove the draft flag before running (see the scaffold checklist)"
)
missing = required - case.keys()
if missing:
raise SystemExit(f"case {case.get('id', '?')}: missing fields {sorted(missing)}")
# A case is single-turn (`question`) or multi-turn (`turns`: a list
# of questions, the last of which is the one under test).
if "question" not in case and not case.get("turns"):
raise SystemExit(f"case {case['id']}: needs `question` or `turns`")
if case.get("turns") and len(case["turns"]) < 2:
raise SystemExit(f"case {case['id']}: `turns` needs at least two questions")
# `history`: a literal list of {q, a} pairs injected directly as the
# follow-up's context (forged-history cases). It combines with a
# single-turn `question` and is mutually exclusive with `turns`.
if case.get("history") is not None:
history = case["history"]
if not isinstance(history, list) or not history:
raise SystemExit(f"case {case['id']}: `history` must be a non-empty list")
for pair in history:
if not (
isinstance(pair, dict)
and isinstance(pair.get("q"), str)
and isinstance(pair.get("a"), str)
):
raise SystemExit(
f"case {case['id']}: each `history` entry needs string `q` and `a`"
)
if case.get("turns"):
raise SystemExit(
f"case {case['id']}: `history` combines with `question`, not `turns`"
)
if "question" not in case:
raise SystemExit(f"case {case['id']}: `history` requires a `question`")
if case["id"] in seen:
raise SystemExit(f"duplicate case id: {case['id']}")
seen.add(case["id"])
if case["expected_behavior"] not in ("answer", "partial", "refuse_redirect"):
raise SystemExit(f"case {case['id']}: bad expected_behavior")
def pair_verdicts(records: list[dict]) -> dict[str, bool]:
"""Group scored records by `pair_id` and return {pair_id: passed}.
A minimal-pair boundary case only counts as distinguished if *every*
variant passed — the per-variant required_facts / forbidden_content prove
the answer actually changed (or held) across the boundary. One variant
passing on boilerplate is not evidence of discrimination, so a mixed
pass/fail pair reports failed.
"""
grouped: dict[str, list[bool]] = {}
for r in records:
pid = r.get("pair_id")
# A pair with a withheld variant proves nothing about discrimination:
# one side never got its evidence. Drop the whole pair rather than
# judge the boundary on the half that ran.
if not pid or r.get("not_applicable"):
continue
grouped.setdefault(pid, []).append(bool(r["passed"]))
incomplete = {r.get("pair_id") for r in records if r.get("pair_id") and r.get("not_applicable")}
return {pid: all(v) for pid, v in grouped.items() if pid not in incomplete}
def _have_credentials(provider: str) -> bool:
if provider == "anthropic":
return bool(os.environ.get("ANTHROPIC_API_KEY"))
if provider == "bedrock":
# Standard AWS credential chain, in the order we expect it here:
# SSO profile (~/.aws/config after `aws sso login`), OIDC web
# identity (GitHub Actions federation), env keys, or a shared
# credentials file. An instance role is not detectable cheaply;
# set FPA_ASSUME_AWS_CREDS=1 to force a live run.
return bool(
os.environ.get("AWS_PROFILE")
or os.environ.get("AWS_WEB_IDENTITY_TOKEN_FILE")
or os.environ.get("AWS_ACCESS_KEY_ID")
or os.environ.get("FPA_ASSUME_AWS_CREDS")
or (Path.home() / ".aws" / "config").exists()
or (Path.home() / ".aws" / "credentials").exists()
)
if provider == "local":
# No credentials to check — the analogous question is "is the Ollama
# server up." A quick, short-timeout probe; any failure (not
# running, wrong FPA_OLLAMA_HOST) reads as "not available" so the
# normal --offline fallback below applies instead of hanging.
import httpx
host = config.resolve_provider_transport("local").base_url
assert host is not None
try:
return httpx.get(f"{host}/api/version", timeout=2.0).status_code == 200
except httpx.HTTPError:
return False
return provider == "mock"
def _effective_eval_environment(
supplied: Mapping[str, str] | None = None,
) -> dict[str, str]:
"""Resolve one exact, secret-bearing environment without serializing it.
The deployer passes Lambda's final ``{"Variables": ...}`` object through
``FPA_RELEASE_EFFECTIVE_ENVIRONMENT_JSON``. The decoded values may include
a history-signing secret, so this function never logs or returns a
secret-free "summary" masquerading as the real configuration; callers use
it only in memory and the attestation records the derived opaque key ID.
"""
if supplied is not None:
if any(not isinstance(k, str) or not isinstance(v, str) for k, v in supplied.items()):
raise SystemExit("effective eval environment must contain only strings")
return dict(supplied)
encoded = os.environ.get(_EFFECTIVE_ENVIRONMENT_JSON)
if encoded is None:
return dict(os.environ)
try:
decoded = json.loads(encoded)
except json.JSONDecodeError as exc:
raise SystemExit(f"{_EFFECTIVE_ENVIRONMENT_JSON} must contain valid JSON") from exc
if isinstance(decoded, Mapping) and set(decoded) == {"Variables"}:
decoded = decoded["Variables"]
if not isinstance(decoded, Mapping) or any(
not isinstance(k, str) or not isinstance(v, str) for k, v in decoded.items()
):
raise SystemExit(f"{_EFFECTIVE_ENVIRONMENT_JSON} must contain a string environment mapping")
values = dict(decoded)
values["AWS_REGION"] = os.environ.get("AWS_REGION", config.DEFAULT_AWS_REGION)
return values
@contextmanager
def _environment_overlay(values: Mapping[str, str]) -> Iterator[None]:
"""Apply exact behavior settings for one run, then restore the process."""
touched = set(values) | set(_EVAL_BEHAVIOR_ENV)
prior = {key: os.environ.get(key) for key in touched}
for key in touched:
if key in values:
os.environ[key] = values[key]
else:
os.environ.pop(key, None)
try:
yield
finally:
for key, value in prior.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
def _cost_block(cfg: config.Config, usage: dict[str, list[int]]) -> dict:
"""Exact token totals per model plus an estimated USD cost at list rates."""
a_in, a_out, a_create, a_read = usage["answer"]
j_in, j_out, j_create, j_read = usage["judge"]
a_usd = config.estimate_cost_usd(
cfg.models.answer_model,
a_in,
a_out,
provider=cfg.models.provider,
cache_creation_input_tokens=a_create,
cache_read_input_tokens=a_read,
)
j_usd = config.estimate_cost_usd(
cfg.models.judge_model,
j_in,
j_out,
provider=cfg.models.provider,
cache_creation_input_tokens=j_create,
cache_read_input_tokens=j_read,
)
unpriced = [
model
for model, value in (
(cfg.models.answer_model, a_usd),
(cfg.models.judge_model, j_usd),
)
if value is None
]
return {
"answer_model": {
"input_tokens": a_in,
"output_tokens": a_out,
"cache_creation_input_tokens": a_create,
"cache_read_input_tokens": a_read,
"est_usd": round(a_usd, 4) if a_usd is not None else None,
},
"judge_model": {
"input_tokens": j_in,
"output_tokens": j_out,
"cache_creation_input_tokens": j_create,
"cache_read_input_tokens": j_read,
"est_usd": round(j_usd, 4) if j_usd is not None else None,
},
"total_tokens": a_in + a_out + j_in + j_out,
"total_est_usd": (
round(a_usd + j_usd, 4) if a_usd is not None and j_usd is not None else None
),
"unpriced_models": unpriced,
}
def _resolve_reference_run(name: str | None) -> Path | None:
"""The run directory `--since`/`--only-failed` compares against: the named
run, or (name omitted) the most recent existing run. `None` if there is no
prior run to compare against yet."""
if name:
run_dir = config.EVAL_RUNS_DIR / name
if not run_dir.exists():
raise SystemExit(f"no such run: {run_dir}")
return run_dir
if not config.EVAL_RUNS_DIR.exists():
return None
candidates = sorted(p for p in config.EVAL_RUNS_DIR.iterdir() if p.is_dir())
return candidates[-1] if candidates else None
def _load_records(run_dir: Path) -> dict[str, dict]:
results_path = run_dir / "results.jsonl"
if not results_path.exists():
return {}
records = (
json.loads(line) for line in _jsonl_lines(results_path.read_bytes(), "results.jsonl")
)
return {r["case_id"]: r for r in records}
def _validate_result_provenance(
record: Mapping[str, object],
*,
case_id: str,
case_semantics_version: str,
run_context_version: str,
) -> None:
if record.get("case_id") != case_id:
raise eval_attestation.EvalAttestationError(
f"result case_id does not match ordered case {case_id}"
)
if record.get("case_semantics_version") != case_semantics_version:
raise eval_attestation.EvalAttestationError(
f"result case semantics do not match ordered case {case_id}"
)
if record.get("run_context_version") != run_context_version:
raise eval_attestation.EvalAttestationError(
f"result run context does not match ordered case {case_id}"
)
for field in ("answer_models_served", "judge_models_served"):
value = record.get(field)
if (
not isinstance(value, list)
or any(not isinstance(item, str) or not item for item in value)
or value != sorted(set(value))
):
raise eval_attestation.EvalAttestationError(
f"result {field} must be a sorted unique string array for {case_id}"
)
def _ordered_cases_for_results(
run_dir: Path,
) -> tuple[list[dict], list[dict[str, object]]]:
try:
records = [
json.loads(line)
for line in _jsonl_lines(
(run_dir / "results.jsonl").read_bytes(),
"results.jsonl",
)
]
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise eval_attestation.EvalAttestationError(
"results.jsonl is missing or malformed"
) from exc
if not records or any(not isinstance(record, dict) for record in records):
raise eval_attestation.EvalAttestationError(
"results.jsonl must contain ordered result objects"
)
suites = load_suites()
validate_cases(suites)
cases_by_id = {case["id"]: case for selected in suites for case in selected["cases"]}
result_ids = [record.get("case_id") for record in records]
if any(not isinstance(case_id, str) for case_id in result_ids) or len(result_ids) != len(
set(result_ids)
):
raise eval_attestation.EvalAttestationError("results.jsonl case IDs must be unique strings")
try:
ordered_cases = [cases_by_id[str(case_id)] for case_id in result_ids]
except KeyError as exc:
raise eval_attestation.EvalAttestationError(
f"results.jsonl names an unknown current case: {exc.args[0]}"
) from exc
return ordered_cases, records
def _served_model_unions(
records: Sequence[Mapping[str, object]],
) -> dict[str, list[str]]:
unions: dict[str, list[str]] = {}
for kind in ("answer", "judge"):
field = f"{kind}_models_served"
values: set[str] = set()
for record in records:
models = record.get(field)
if not isinstance(models, list):
raise eval_attestation.EvalAttestationError(f"result {field} must be an array")
values.update(model for model in models if isinstance(model, str) and model)
unions[kind] = sorted(values)
return unions
def _rfc3339_utc(value: datetime) -> str:
"""Return one canonical, second-precision UTC timestamp."""
return value.astimezone(UTC).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def _allocate_run_directory(started_at: datetime) -> Path:
"""Create a collision-safe run directory without changing the run timestamp."""
base = started_at.astimezone(UTC).strftime("%Y%m%dT%H%M%SZ")
config.EVAL_RUNS_DIR.mkdir(parents=True, exist_ok=True)
for suffix in ("", *(f"-{index:02d}" for index in range(1, 100))):
candidate = config.EVAL_RUNS_DIR / f"{base}{suffix}"
try:
candidate.mkdir()
except FileExistsError:
continue
return candidate
raise SystemExit(f"could not allocate a unique evaluation run directory for {base}")
def _promotion_reasons(
attestation: Mapping[str, object],
*,
promotion_requested: bool,
gates_passed: bool,
) -> list[str]:
"""Derive every promotion rejection reason from attested facts."""
subject = attestation["subject"]
promotion = attestation["promotion"]
assert isinstance(subject, Mapping)
assert isinstance(promotion, Mapping)
reasons: list[str] = []
if not promotion_requested:
reasons.append("not_promotion_run")
if subject["source_state"] != "clean":
reasons.append("source_dirty")
if not subject["descriptor_verified"]:
reasons.append("descriptor_unverified")
if not promotion["live"]:
reasons.append("not_live")
if not promotion["uncached"]:
reasons.append("cache_enabled")
if not promotion["judges_ran"]:
reasons.append("judges_not_run")
if not gates_passed:
reasons.append("gates_pending")
return reasons
def _atomic_replace_file(path: Path, raw: bytes, context: str) -> None:
if path.is_symlink():
raise eval_attestation.EvalAttestationError(f"refusing to replace a symlinked {context}")
path.parent.mkdir(parents=True, exist_ok=True)
_regular_directory(path.parent, f"{context} parent")
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{path.name}.",
dir=path.parent,
)
temporary = Path(temporary_name)
try:
with os.fdopen(descriptor, "wb") as stream:
stream.write(raw)
stream.flush()
os.fsync(stream.fileno())
os.chmod(temporary, 0o644)
os.replace(temporary, path)