Jainamshahhh commited on
Commit
ff1401a
·
verified ·
1 Parent(s): 0218bf9

Upload score_chrono.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. score_chrono.py +763 -0
score_chrono.py ADDED
@@ -0,0 +1,763 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ChronoCalc released scorer. Recomputes every gold answer, then exact-matches.
2
+
3
+ python score_chrono.py --selftest
4
+ python score_chrono.py ROWS.jsonl GENS.jsonl [--report R.json] [--verdicts V.jsonl]
5
+ python score_chrono.py --recompute ROWS.jsonl # gold integrity only, no model
6
+
7
+ WHAT MAKES THIS DIFFERENT FROM A KEY FILE. It does not trust the stored answers. For
8
+ every row it re-derives the gold answer from the scenario parameters in the row itself,
9
+ and if a stored answer and its recomputation disagree the run ABORTS rather than
10
+ scoring against either. A reviewer therefore does not have to take our labels on faith:
11
+ running this script is running the label generator.
12
+
13
+ DEPENDENCIES. Standard library plus `zoneinfo`, and two files that ship beside it:
14
+ solver_a.py and fedcal.py, which are also stdlib only. Reporting helpers come from
15
+ part2/scripts/common/scoring.py, shared with the other entries in this repo, also
16
+ stdlib only. Supported Python: 3.11 to 3.13. There is no pip install, and in
17
+ particular the `holidays` package is NOT used anywhere in this path; it appears only in
18
+ crosscheck_fedcal.py, a build-time tool.
19
+
20
+ TZDATA. Timezone answers depend on the IANA database, and IANA changes. Two guards,
21
+ because a silently different tzdata would silently change gold answers:
22
+ 1. Every F3 endpoint carries the UTC offset it was generated under. Before scoring,
23
+ the live zoneinfo is asked for the same offset, and a mismatch aborts the run
24
+ naming the endpoint. This is per-row and exact, not a sampled fingerprint.
25
+ 2. `--pin-tzdata` forces zoneinfo to read the pip `tzdata` package instead of the
26
+ system database, for reproducing a number byte for byte on a different machine.
27
+ It is optional; the guard above is what makes the run trustworthy either way.
28
+
29
+ =============================================================================
30
+ THE SCORING RULES, PRE-DECLARED. No tolerance, no partial credit, no judgment.
31
+ =============================================================================
32
+
33
+ ANSWER FORMATS. Exactly one form per family, and nothing else is accepted:
34
+ date <answer>YYYY-MM-DD</answer> F1, F2, F4
35
+ duration <answer>H:MM</answer> F3
36
+ isoweek <answer>YYYY-Www</answer> F5
37
+
38
+ H:MM semantics, pinned so there is nothing to argue about:
39
+ total hours, which MAY exceed 24 30:45 is valid
40
+ no days component "1 day 6:45" is not an answer
41
+ minutes always two digits 9:0 is malformed
42
+ hours never zero-padded 09:00 is malformed, 9:00 is right
43
+ zero hours are written as 0 0:45
44
+ Worked: 540 minutes is "9:00". 1845 minutes is "30:45". 45 minutes is "0:45".
45
+
46
+ ISO week semantics: YYYY is the ISO week-numbering year, which is not always the
47
+ calendar year of the date, and Www is zero-padded two digits, 01 to 53. 2022-01-01
48
+ falls in ISO week 2021-W52.
49
+
50
+ STRICT. The output must contain EXACTLY ONE <answer>...</answer> tag whose content
51
+ matches the required format for that row. Zero tags scores 0. Two or more tags scores
52
+ 0, even when they agree, because "the model emitted one answer" is part of what is
53
+ being measured. A well-formed single tag scores 1 only on an exact string match against
54
+ the recomputed gold.
55
+
56
+ LENIENT. Defined to favour the base model, so that no part of a reported lift rests on
57
+ format compliance. Scan the whole output for literals shaped like the row's answer
58
+ type, ignoring tags entirely, and compare the LAST one to the gold. The shapes:
59
+ date a YYYY-MM-DD literal not adjacent to another digit
60
+ isoweek a YYYY-Www literal
61
+ duration an H:MM literal with an unpadded hour, not adjacent to another digit or
62
+ colon, not immediately preceded by "T" or by "YYYY-MM-DD "
63
+ The two duration exclusions exist because prompts state instants as 2026-10-31T22:00,
64
+ and a scan that treated a quoted input timestamp as an answer would score the model on
65
+ its ability to copy the question.
66
+
67
+ LENIENT_ANY. A second, strictly more generous diagnostic: does the gold literal appear
68
+ ANYWHERE in the output as an answer-shaped literal. Published alongside, never gated
69
+ on. Its purpose is to bound how much the LAST-literal rule could be under-crediting a
70
+ model that computed correctly and then kept talking. If LENIENT and LENIENT_ANY are
71
+ far apart, the extraction rule is doing more work than it should, and that is a fact
72
+ about the harness that a reader is entitled to see rather than something to discover
73
+ after the fact.
74
+
75
+ CONFIDENT_WRONG. Among outputs with exactly one well-formed tag, the fraction whose
76
+ answer is wrong. Rows without a well-formed single tag are excluded from the
77
+ denominator, not counted as correct. Entirely mechanical: no hedge lexicon, no reading
78
+ of tone.
79
+
80
+ HAS_WORKING. Whether anything resembling a computation precedes the tag: at least two
81
+ non-empty lines and at least twenty characters before the first tag. A release gate,
82
+ not an accuracy metric. This project has twice shipped a tuned model that got terser
83
+ than its base and lost on tasks it had not been trained on, so a collapse to
84
+ bare answers has to be visible.
85
+
86
+ F1 SUBPOPULATION SPLIT, first-class since the pre-registered adjudication of
87
+ 2026-07-28 (part2/docs/eval/gcp/chrono_gate_adjudication.md). Every F1 row is
88
+ classified from its stored scenario parameters alone:
89
+
90
+ holiday-affected recomputing the gold and recomputing the SAME walk with
91
+ holidays ignored (weekends still skipped) give different
92
+ dates, i.e. at least one observed federal holiday changes
93
+ the answer
94
+ no-holiday the two walks agree, so the row is plain day-walking
95
+
96
+ Every metric above is then reported separately for each side, in the printed output
97
+ and in the report JSON under "f1_split", alongside the blended F1 numbers, which
98
+ continue to be published unchanged. The blend measures the pilot mix; the split
99
+ measures the capability, and the adjudication reads
100
+ f1_split -> holiday_affected -> <column> -> lenient_exact from the report file. The
101
+ classification is recomputed by this scorer at scoring time, never read from a stored
102
+ flag, for the same reason gold answers are recomputed: the released instrument, not a
103
+ notebook, is what produces every adjudicated number.
104
+ """
105
+ from __future__ import annotations
106
+
107
+ import argparse
108
+ import json
109
+ import re
110
+ import sys
111
+ from collections import Counter
112
+ from datetime import date, datetime, timedelta
113
+ from pathlib import Path
114
+ from zoneinfo import ZoneInfo
115
+
116
+ _HERE = Path(__file__).resolve().parent
117
+ sys.path.insert(0, str(_HERE))
118
+ sys.path.insert(0, str(_HERE.parent))
119
+
120
+ import solver_a # noqa: E402
121
+ from common import scoring # noqa: E402
122
+
123
+ SUPPORTED_PYTHON = (3, 11), (3, 13)
124
+
125
+ TAG_RE = re.compile(r"<answer>(.*?)</answer>", re.DOTALL | re.IGNORECASE)
126
+
127
+ STRICT_FORMS = {
128
+ "date": re.compile(r"^\d{4}-\d{2}-\d{2}$"),
129
+ "duration": re.compile(r"^(?:0|[1-9]\d*):[0-5]\d$"),
130
+ "isoweek": re.compile(r"^\d{4}-W\d{2}$"),
131
+ }
132
+
133
+ LITERAL_FORMS = {
134
+ "date": re.compile(r"(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)"),
135
+ "isoweek": re.compile(r"(?<![A-Za-z0-9])\d{4}-W\d{2}(?!\d)"),
136
+ "duration": re.compile(
137
+ r"(?<![\d:])(?<!T)(?<!\d{4}-\d{2}-\d{2} )(?:0|[1-9]\d{0,2}):[0-5]\d(?![\d:])"),
138
+ }
139
+
140
+ FAMILIES = ("F1", "F2", "F3", "F4", "F5")
141
+
142
+
143
+ class ScoringError(SystemExit):
144
+ pass
145
+
146
+
147
+ # ------------------------------------------------------------------ validation
148
+
149
+ def well_formed(answer_type: str, text: str) -> bool:
150
+ """Does `text` satisfy the declared answer format, including semantic validity."""
151
+ form = STRICT_FORMS.get(answer_type)
152
+ if form is None or not form.match(text):
153
+ return False
154
+ if answer_type == "date":
155
+ try:
156
+ date.fromisoformat(text)
157
+ except ValueError:
158
+ return False
159
+ elif answer_type == "isoweek":
160
+ week = int(text[6:])
161
+ if not 1 <= week <= 53:
162
+ return False
163
+ # Week 53 exists only in long ISO years; reject 53 where it does not.
164
+ if week == 53:
165
+ year = int(text[:4])
166
+ try:
167
+ date.fromisocalendar(year, 53, 1)
168
+ except ValueError:
169
+ return False
170
+ return True
171
+
172
+
173
+ def tags_in(output: str) -> list[str]:
174
+ return [m.group(1).strip() for m in TAG_RE.finditer(output or "")]
175
+
176
+
177
+ def single_well_formed_tag(answer_type: str, output: str) -> str | None:
178
+ """The one tag, or None when there are zero, several, or a malformed one."""
179
+ found = tags_in(output)
180
+ if len(found) != 1:
181
+ return None
182
+ return found[0] if well_formed(answer_type, found[0]) else None
183
+
184
+
185
+ def last_literal(answer_type: str, output: str) -> str | None:
186
+ hits = LITERAL_FORMS[answer_type].findall(output or "")
187
+ return hits[-1] if hits else None
188
+
189
+
190
+ def literals(answer_type: str, output: str) -> list[str]:
191
+ return LITERAL_FORMS[answer_type].findall(output or "")
192
+
193
+
194
+ def working_before_tag(output: str) -> bool:
195
+ m = TAG_RE.search(output or "")
196
+ head = (output or "")[: m.start()] if m else (output or "")
197
+ lines = [l for l in head.splitlines() if l.strip()]
198
+ return len(lines) >= 2 and len(head.strip()) >= 20
199
+
200
+
201
+ # ------------------------------------------------------------------ F1 split
202
+
203
+ def weekday_only_offset(anchor: date, n: int, forward: bool) -> date:
204
+ """The nth Mon-Fri day strictly after (or before) anchor, holidays IGNORED.
205
+
206
+ The counterfactual behind the F1 split. It deliberately lives here, in the
207
+ released scorer, rather than in the solvers: it computes a WRONG answer under the
208
+ task's rules (the answer a holiday-blind clerk would reach), and the solvers must
209
+ never contain a code path that produces wrong answers.
210
+ """
211
+ step = timedelta(days=1 if forward else -1)
212
+ cur, k = anchor, 0
213
+ while k < n:
214
+ cur += step
215
+ if cur.weekday() < 5:
216
+ k += 1
217
+ return cur
218
+
219
+
220
+ def holiday_affected(params: dict, gold: str) -> bool:
221
+ """Does an observed federal holiday change this F1 row's answer?
222
+
223
+ True exactly when the holiday-blind walk lands somewhere other than the recomputed
224
+ gold. Pure function of the scenario parameters, so the subpopulation a row belongs
225
+ to is decided by the released instrument at scoring time, not by a stored label.
226
+ """
227
+ if params.get("family") != "F1":
228
+ raise ScoringError(f"holiday_affected is defined for F1 only, got "
229
+ f"{params.get('family')!r}")
230
+ naive = weekday_only_offset(date.fromisoformat(params["anchor"]), params["n"],
231
+ params["direction"] == "after")
232
+ return naive.isoformat() != gold
233
+
234
+
235
+ def split_f1(gens: list[dict], by_id: dict[str, dict],
236
+ gold_by_id: dict[str, tuple[str, str]], metrics: dict) -> dict | None:
237
+ """Score the two F1 subpopulations separately. None when the file has no F1."""
238
+ hol: list[dict] = []
239
+ nohol: list[dict] = []
240
+ for g in gens:
241
+ params = (by_id[g["id"]].get("params") or {})
242
+ if params.get("family") != "F1":
243
+ continue
244
+ _, gold = gold_by_id[g["id"]]
245
+ (hol if holiday_affected(params, gold) else nohol).append(g)
246
+ if not hol and not nohol:
247
+ return None
248
+
249
+ out: dict = {
250
+ "definition": "holiday-affected means the recomputed gold differs from the "
251
+ "same walk with holidays ignored (weekends still skipped)",
252
+ "n_holiday_affected": len(hol),
253
+ "n_no_holiday": len(nohol),
254
+ }
255
+ for name, sub in (("holiday_affected", hol), ("no_holiday", nohol)):
256
+ if sub:
257
+ res = scoring.score_file(sub, metrics)
258
+ scoring.report(res, f"F1 {name.replace('_', ' ')} subpopulation "
259
+ f"({len(sub)} rows)", headline="strict_exact")
260
+ out[name] = res
261
+ else:
262
+ out[name] = None
263
+ print(f"\nF1 {name.replace('_', ' ')} subpopulation: 0 rows in this file, "
264
+ f"nothing to score on that side.")
265
+ return out
266
+
267
+
268
+ # ------------------------------------------------------------------ gold
269
+
270
+ def recompute(row: dict) -> tuple[str, str]:
271
+ """(answer_type, gold) recomputed from the row's scenario parameters."""
272
+ params = row.get("params")
273
+ if not isinstance(params, dict):
274
+ raise ScoringError(
275
+ f"row {row.get('id')!r} carries no `params` object, so its gold answer "
276
+ f"cannot be recomputed. This scorer refuses to grade against a stored key.")
277
+ out = solver_a.solve(params)
278
+ return out["answer_type"], out["answer"]
279
+
280
+
281
+ def check_tz_drift(rows: list[dict]) -> list[str]:
282
+ """Every recorded F3 UTC offset must still be what the live tzdata says."""
283
+ problems: list[str] = []
284
+ for r in rows:
285
+ p = r.get("params") or {}
286
+ if p.get("family") != "F3":
287
+ continue
288
+ for side in ("start", "end"):
289
+ spec = p.get(side) or {}
290
+ want = spec.get("utc_offset_min")
291
+ if want is None:
292
+ problems.append(f"{r.get('id')}: F3 {side} has no recorded utc_offset_min")
293
+ continue
294
+ naive = datetime.fromisoformat(spec["dt"])
295
+ got = ZoneInfo(spec["zone"]).utcoffset(naive)
296
+ got = int(got.total_seconds()) // 60
297
+ if got != want:
298
+ problems.append(
299
+ f"{r.get('id')}: {spec['zone']} {spec['dt']} was generated at "
300
+ f"{want} minutes from UTC, this machine says {got}. The IANA "
301
+ f"database has changed; re-run with --pin-tzdata or rebuild.")
302
+ return problems
303
+
304
+
305
+ def verify_golds(rows: list[dict]) -> list[str]:
306
+ """Stored answers must equal their recomputation, and be well formed."""
307
+ problems: list[str] = []
308
+ for r in rows:
309
+ try:
310
+ atype, gold = recompute(r)
311
+ except (solver_a.SolverError, ValueError) as exc:
312
+ problems.append(f"{r.get('id')}: {exc}")
313
+ continue
314
+ if not well_formed(atype, gold):
315
+ problems.append(f"{r.get('id')}: recomputed gold {gold!r} is not a "
316
+ f"well-formed {atype}")
317
+ stored = r.get("answer", r.get("reference"))
318
+ if stored is not None and str(stored).strip() != gold:
319
+ problems.append(f"{r.get('id')}: stored answer {stored!r} but recomputation "
320
+ f"says {gold!r}")
321
+ declared = r.get("answer_type")
322
+ if declared is not None and declared != atype:
323
+ problems.append(f"{r.get('id')}: declared answer_type {declared!r}, "
324
+ f"recomputation says {atype!r}")
325
+ return problems
326
+
327
+
328
+ # ------------------------------------------------------------------ metrics
329
+
330
+ def build_metrics(gold_by_id: dict[str, tuple[str, str]]):
331
+ def _g(row: dict) -> tuple[str, str]:
332
+ return gold_by_id[row["id"]]
333
+
334
+ def strict(pred: str, row: dict):
335
+ atype, gold = _g(row)
336
+ tag = single_well_formed_tag(atype, pred)
337
+ return tag == gold
338
+
339
+ def tag_compliance(pred: str, row: dict):
340
+ atype, _ = _g(row)
341
+ return single_well_formed_tag(atype, pred) is not None
342
+
343
+ def lenient(pred: str, row: dict):
344
+ atype, gold = _g(row)
345
+ return last_literal(atype, pred) == gold
346
+
347
+ def lenient_any(pred: str, row: dict):
348
+ atype, gold = _g(row)
349
+ return gold in literals(atype, pred)
350
+
351
+ def confident_wrong(pred: str, row: dict):
352
+ atype, gold = _g(row)
353
+ tag = single_well_formed_tag(atype, pred)
354
+ if tag is None:
355
+ return None # excluded from the denominator
356
+ return tag != gold
357
+
358
+ def has_working(pred: str, row: dict):
359
+ return working_before_tag(pred)
360
+
361
+ return {
362
+ "strict_exact": strict,
363
+ "lenient_exact": lenient,
364
+ "lenient_any": lenient_any,
365
+ "tag_compliance": tag_compliance,
366
+ "confident_wrong": confident_wrong,
367
+ "has_working": has_working,
368
+ }
369
+
370
+
371
+ def verdict_rows(gens: list[dict], gold_by_id: dict[str, tuple[str, str]]) -> list[dict]:
372
+ out = []
373
+ for r in gens:
374
+ atype, gold = gold_by_id[r["id"]]
375
+ rec = {"id": r["id"], "family": r.get("family", r.get("category", "")),
376
+ "answer_type": atype, "gold": gold}
377
+ for col in scoring.columns(gens):
378
+ pred = r.get(col) or ""
379
+ tag = single_well_formed_tag(atype, pred)
380
+ rec[col] = {
381
+ "tag": tag,
382
+ "n_tags": len(tags_in(pred)),
383
+ "strict": tag == gold,
384
+ "lenient": last_literal(atype, pred) == gold,
385
+ "lenient_any": gold in literals(atype, pred),
386
+ "has_working": working_before_tag(pred),
387
+ "chars": len(pred),
388
+ }
389
+ out.append(rec)
390
+ return out
391
+
392
+
393
+ # ------------------------------------------------------------------ driver
394
+
395
+ def load_rows(path: str | Path) -> list[dict]:
396
+ rows = scoring.load(path)
397
+ seen: set[str] = set()
398
+ for r in rows:
399
+ rid = r.get("id")
400
+ if not rid:
401
+ raise ScoringError(f"{path}: a row has no id")
402
+ if rid in seen:
403
+ raise ScoringError(f"{path}: duplicate id {rid!r}")
404
+ seen.add(rid)
405
+ return rows
406
+
407
+
408
+ def score(rows_path: str, gens_path: str, report_path: str = "",
409
+ verdicts_path: str = "") -> dict:
410
+ rows = load_rows(rows_path)
411
+ gens = scoring.load(gens_path)
412
+
413
+ by_id = {r["id"]: r for r in rows}
414
+ missing = [g.get("id") for g in gens if g.get("id") not in by_id]
415
+ if missing:
416
+ raise ScoringError(
417
+ f"{len(missing)} generation id(s) are absent from {rows_path}, first: "
418
+ f"{missing[:3]}. Scoring a generation file against the wrong slice is how "
419
+ f"a harness failure gets published as a model result.")
420
+
421
+ drift = check_tz_drift([by_id[g["id"]] for g in gens])
422
+ if drift:
423
+ raise ScoringError("timezone database drift:\n " + "\n ".join(drift[:10]))
424
+
425
+ problems = verify_golds([by_id[g["id"]] for g in gens])
426
+ if problems:
427
+ raise ScoringError(
428
+ f"{len(problems)} gold answer(s) failed recomputation; refusing to score.\n "
429
+ + "\n ".join(problems[:10]))
430
+
431
+ gold_by_id = {g["id"]: recompute(by_id[g["id"]]) for g in gens}
432
+ for g in gens:
433
+ g.setdefault("family", by_id[g["id"]].get("family", g.get("category", "")))
434
+
435
+ metrics = build_metrics(gold_by_id)
436
+ overall = scoring.score_file(gens, metrics)
437
+ scoring.report(overall, f"ChronoCalc: {Path(gens_path).name} ({len(gens)} rows)",
438
+ headline="strict_exact")
439
+
440
+ per_family: dict[str, dict] = {}
441
+ for fam in FAMILIES:
442
+ sub = [g for g in gens if g.get("family") == fam]
443
+ if not sub:
444
+ continue
445
+ per_family[fam] = scoring.score_file(sub, metrics)
446
+ scoring.report(per_family[fam], f"{fam} ({len(sub)} rows)",
447
+ headline="strict_exact")
448
+
449
+ f1_split = split_f1(gens, by_id, gold_by_id, metrics)
450
+
451
+ lengths = scoring.length_report(gens)
452
+ print("\nOutput length (characters):", json.dumps(lengths))
453
+ if lengths.get("terseness_flag"):
454
+ print("TERSENESS FLAG: the tuned median is under 0.6x the base median. This has "
455
+ "twice preceded a win-rate collapse in this project. Do not release on it.")
456
+
457
+ for col in scoring.columns(gens):
458
+ miss = sum(1 for g in gens if not working_before_tag(g.get(col) or ""))
459
+ pct = 100.0 * miss / len(gens)
460
+ note = " RELEASE BLOCKER" if (col == "tuned" and pct > 1.0) else ""
461
+ print(f"working section missing on column {col!r}: {miss}/{len(gens)} "
462
+ f"= {pct:.1f}%{note}")
463
+
464
+ result = {
465
+ "rows_file": str(rows_path),
466
+ "generations_file": str(gens_path),
467
+ "n_rows": len(gens),
468
+ "python": f"{sys.version_info.major}.{sys.version_info.minor}",
469
+ "overall": overall,
470
+ "per_family": per_family,
471
+ "f1_split": f1_split,
472
+ "lengths": lengths,
473
+ "family_mix": dict(Counter(g.get("family", "") for g in gens)),
474
+ }
475
+ if report_path:
476
+ Path(report_path).write_text(json.dumps(result, indent=2) + "\n")
477
+ print(f"wrote {report_path}")
478
+ if verdicts_path:
479
+ with Path(verdicts_path).open("w") as fh:
480
+ for v in verdict_rows(gens, gold_by_id):
481
+ fh.write(json.dumps(v, ensure_ascii=False) + "\n")
482
+ print(f"wrote {verdicts_path}")
483
+ return result
484
+
485
+
486
+ # ------------------------------------------------------------------ selftest
487
+
488
+ def _selftest() -> None:
489
+ """Every gate is fed something that must make it fail. See HANDOFF 5.13."""
490
+ ok = 0
491
+ lo, hi = SUPPORTED_PYTHON
492
+ assert lo <= sys.version_info[:2] <= hi, (
493
+ f"Python {sys.version_info[:2]} is outside the declared support range "
494
+ f"{lo} to {hi}")
495
+ ok += 1
496
+
497
+ # --- answer format validation, both directions -------------------------
498
+ good = {"date": ["2026-12-07", "2020-02-29"],
499
+ "duration": ["0:00", "0:45", "9:00", "30:45", "100:05"],
500
+ "isoweek": ["2026-W47", "2020-W53", "2021-W01"]}
501
+ bad = {"date": ["2026-12-7", "12/07/2026", "2026-13-01", "2026-02-30",
502
+ "December 7, 2026", "2026-12-07.", ""],
503
+ "duration": ["09:00", "9:0", "9:60", "1 day 6:45", "9h00", "9:00 hours",
504
+ "-1:00", ""],
505
+ "isoweek": ["2026-W5", "2026W47", "2026-w47", "2026-W54", "2025-W53", ""]}
506
+ for atype, xs in good.items():
507
+ for x in xs:
508
+ assert well_formed(atype, x), f"{atype} {x!r} should be well formed"
509
+ for atype, xs in bad.items():
510
+ for x in xs:
511
+ assert not well_formed(atype, x), f"{atype} {x!r} should be rejected"
512
+ # 2025 is a 52-week ISO year, so W53 must be rejected there. 2020 and 2026 are
513
+ # 53-week years (January 1 lands on a Thursday, or on a Wednesday in a leap year),
514
+ # so W53 is legitimate for those and must be accepted.
515
+ assert not well_formed("isoweek", "2025-W53")
516
+ assert well_formed("isoweek", "2020-W53") and well_formed("isoweek", "2026-W53")
517
+ ok += 1
518
+
519
+ # --- tag extraction -----------------------------------------------------
520
+ assert single_well_formed_tag("date", "x <answer>2026-12-07</answer>") == "2026-12-07"
521
+ assert single_well_formed_tag("date", "no tag here") is None
522
+ assert single_well_formed_tag(
523
+ "date", "<answer>2026-12-07</answer> and <answer>2026-12-07</answer>") is None, \
524
+ "two tags must score zero even when they agree"
525
+ assert single_well_formed_tag("date", "<answer>Dec 7 2026</answer>") is None
526
+ assert single_well_formed_tag("duration", "<answer>09:00</answer>") is None
527
+ assert single_well_formed_tag("duration", "<answer> 9:00 </answer>") == "9:00"
528
+ ok += 1
529
+
530
+ # --- lenient literal extraction ----------------------------------------
531
+ assert last_literal("date", "walk 2026-12-04 then 2026-12-07 done") == "2026-12-07"
532
+ assert last_literal("date", "nothing") is None
533
+ assert last_literal("isoweek", "week 2026-W47 it is") == "2026-W47"
534
+ # A quoted input timestamp must NOT be read as a duration answer.
535
+ txt = ("Start 2026-10-31T22:00 America/New_York, end 2026-11-01T06:00. "
536
+ "Elapsed is 9:00.")
537
+ assert last_literal("duration", txt) == "9:00", last_literal("duration", txt)
538
+ assert literals("duration", "at 2026-10-31 22:00 the clock") == [], \
539
+ "a date-space-time literal is not an answer shape"
540
+ assert literals("duration", "T06:00 alone") == []
541
+ assert last_literal("duration", "8:00 then 9:00") == "9:00"
542
+ assert last_literal("duration", "06:00 padded is ignored") is None
543
+ ok += 1
544
+
545
+ # --- working-section detection -----------------------------------------
546
+ assert working_before_tag("line one here\nline two here\n<answer>x</answer>")
547
+ assert not working_before_tag("<answer>2026-12-07</answer>")
548
+ assert not working_before_tag("short\n<answer>x</answer>")
549
+ ok += 1
550
+
551
+ # --- end to end, with a deliberately wrong row of every kind -----------
552
+ import tempfile
553
+
554
+ p_f1 = {"family": "F1", "anchor": "2026-11-20", "n": 10, "direction": "after"}
555
+ p_f3 = {"family": "F3",
556
+ "start": {"dt": "2026-10-31T22:00", "zone": "America/New_York",
557
+ "utc_offset_min": -240},
558
+ "end": {"dt": "2026-11-01T06:00", "zone": "America/New_York",
559
+ "utc_offset_min": -300}}
560
+ p_f5 = {"family": "F5", "kind": "of_date", "date": "2026-11-20"}
561
+ rows = [
562
+ {"id": "t-correct", "family": "F1", "params": p_f1, "answer": "2026-12-07"},
563
+ {"id": "t-wrong", "family": "F1", "params": p_f1, "answer": "2026-12-07"},
564
+ {"id": "t-notag", "family": "F1", "params": p_f1, "answer": "2026-12-07"},
565
+ {"id": "t-twotags", "family": "F1", "params": p_f1, "answer": "2026-12-07"},
566
+ {"id": "t-malformed", "family": "F1", "params": p_f1, "answer": "2026-12-07"},
567
+ {"id": "t-prose", "family": "F1", "params": p_f1, "answer": "2026-12-07"},
568
+ {"id": "t-terse", "family": "F1", "params": p_f1, "answer": "2026-12-07"},
569
+ {"id": "t-dst", "family": "F3", "params": p_f3, "answer": "9:00"},
570
+ {"id": "t-week", "family": "F5", "params": p_f5, "answer": "2026-W47"},
571
+ ]
572
+ body = "computing the walk\nskipping Thanksgiving 2026-11-26\n"
573
+ gens = [
574
+ {"id": "t-correct", "output": body + "<answer>2026-12-07</answer>"},
575
+ {"id": "t-wrong", "output": body + "<answer>2026-12-04</answer>"},
576
+ {"id": "t-notag", "output": body + "the answer is probably early December"},
577
+ {"id": "t-twotags",
578
+ "output": body + "<answer>2026-12-07</answer> or <answer>2026-12-07</answer>"},
579
+ {"id": "t-malformed", "output": body + "<answer>December 7 2026</answer>"},
580
+ {"id": "t-prose", "output": body + "so the due date is 2026-12-07 in the end"},
581
+ {"id": "t-terse", "output": "<answer>2026-12-07</answer>"},
582
+ {"id": "t-dst",
583
+ "output": "Start 2026-10-31T22:00, end 2026-11-01T06:00, so 8:00 elapsed.\n"
584
+ "Second thought, via UTC it is 9:00.\n<answer>9:00</answer>"},
585
+ {"id": "t-week", "output": body + "<answer>2026-W47</answer>"},
586
+ ]
587
+ with tempfile.TemporaryDirectory() as td:
588
+ rp, gp = Path(td) / "rows.jsonl", Path(td) / "gens.jsonl"
589
+ rp.write_text("".join(json.dumps(r) + "\n" for r in rows))
590
+ gp.write_text("".join(json.dumps(g) + "\n" for g in gens))
591
+ res = score(str(rp), str(gp))
592
+
593
+ m = res["overall"]["output"]
594
+ # All 7 F1 rows here share the Thanksgiving scenario, so the split must put
595
+ # 7 on the holiday-affected side, 0 on the other, and survive the empty side.
596
+ assert res["f1_split"]["n_holiday_affected"] == 7, res["f1_split"]
597
+ assert res["f1_split"]["n_no_holiday"] == 0
598
+ assert res["f1_split"]["no_holiday"] is None
599
+ assert res["f1_split"]["holiday_affected"]["output"]["strict_exact"]["n_scored"] == 7
600
+ # 4 of 9 strictly correct: correct, terse, dst, week.
601
+ assert m["strict_exact"]["n_true"] == 4, m["strict_exact"]
602
+ # tag compliance excludes notag, prose, twotags and malformed: 5 of 9.
603
+ assert m["tag_compliance"]["n_true"] == 5, m["tag_compliance"]
604
+ # lenient credits the prose row and the two-tag row on top of the 4 strict
605
+ # passes, which is exactly the point of it. It does NOT credit the malformed
606
+ # row, whose last date literal is the intermediate 2026-11-26.
607
+ assert m["lenient_exact"]["n_true"] == 6, m["lenient_exact"]
608
+ assert m["lenient_exact"]["n_true"] > m["strict_exact"]["n_true"], \
609
+ "lenient must be more generous than strict, or it is not doing its job"
610
+ # confident_wrong: 5 well-formed tags, 1 of them wrong.
611
+ assert m["confident_wrong"]["n_scored"] == 5, m["confident_wrong"]
612
+ assert m["confident_wrong"]["n_true"] == 1, m["confident_wrong"]
613
+ # the terse row is the only one with no working section.
614
+ assert m["has_working"]["n_true"] == 8, m["has_working"]
615
+ # F3's distractor: the last duration literal is the corrected 9:00.
616
+ assert res["per_family"]["F3"]["output"]["lenient_exact"]["n_true"] == 1
617
+ ok += 1
618
+
619
+ # --- the gold-integrity gate must fire ---------------------------
620
+ broken = [dict(r) for r in rows]
621
+ broken[0]["answer"] = "2026-12-04"
622
+ rp2 = Path(td) / "broken.jsonl"
623
+ rp2.write_text("".join(json.dumps(r) + "\n" for r in broken))
624
+ try:
625
+ score(str(rp2), str(gp))
626
+ raise AssertionError("a wrong stored answer was accepted")
627
+ except ScoringError as exc:
628
+ assert "recomputation" in str(exc)
629
+ ok += 1
630
+
631
+ # --- a row with no params must be refused, not guessed ------------
632
+ noparams = [dict(r) for r in rows]
633
+ noparams[0].pop("params")
634
+ rp3 = Path(td) / "noparams.jsonl"
635
+ rp3.write_text("".join(json.dumps(r) + "\n" for r in noparams))
636
+ try:
637
+ score(str(rp3), str(gp))
638
+ raise AssertionError("a row without params was scored")
639
+ except ScoringError as exc:
640
+ assert "params" in str(exc)
641
+ ok += 1
642
+
643
+ # --- tz drift gate ------------------------------------------------
644
+ drifted = [dict(r) for r in rows]
645
+ bad_p = json.loads(json.dumps(p_f3))
646
+ bad_p["start"]["utc_offset_min"] = -239
647
+ drifted[7] = dict(drifted[7], params=bad_p)
648
+ rp4 = Path(td) / "drift.jsonl"
649
+ rp4.write_text("".join(json.dumps(r) + "\n" for r in drifted))
650
+ try:
651
+ score(str(rp4), str(gp))
652
+ raise AssertionError("timezone drift was not detected")
653
+ except ScoringError as exc:
654
+ assert "IANA" in str(exc)
655
+ ok += 1
656
+
657
+ # --- a generation file from the wrong slice must be refused -------
658
+ gp2 = Path(td) / "wrong.jsonl"
659
+ gp2.write_text(json.dumps({"id": "not-a-chrono-id", "output": "x"}) + "\n")
660
+ try:
661
+ score(str(rp), str(gp2))
662
+ raise AssertionError("a mismatched generation file was scored")
663
+ except ScoringError as exc:
664
+ assert "absent" in str(exc)
665
+ ok += 1
666
+
667
+ # --- the F1 split: one synthetic case per side, and the sides move
668
+ # INDEPENDENTLY. The adjudication of 2026-07-28 reads the
669
+ # holiday-affected lenient number, so this proves that number can fail
670
+ # while the other side passes, and the reverse. All four answers below
671
+ # were verified against the solvers before being hardcoded.
672
+ p_hol = {"family": "F1", "anchor": "2026-11-20", "n": 10,
673
+ "direction": "after"} # gold 2026-12-07,
674
+ # weekend-only walk 2026-12-04 -> affected
675
+ p_clean = {"family": "F1", "anchor": "2026-08-03", "n": 4,
676
+ "direction": "after"} # gold 2026-08-07,
677
+ # weekend-only walk identical -> not affected
678
+ assert holiday_affected(p_hol, "2026-12-07") is True
679
+ assert holiday_affected(p_clean, "2026-08-07") is False
680
+ try:
681
+ holiday_affected({"family": "F3"}, "9:00")
682
+ raise AssertionError("non-F1 must be refused, not classified")
683
+ except ScoringError:
684
+ pass
685
+
686
+ split_rows = [
687
+ {"id": "s-hol", "family": "F1", "params": p_hol, "answer": "2026-12-07"},
688
+ {"id": "s-clean", "family": "F1", "params": p_clean,
689
+ "answer": "2026-08-07"},
690
+ ]
691
+ rp5 = Path(td) / "split_rows.jsonl"
692
+ rp5.write_text("".join(json.dumps(r) + "\n" for r in split_rows))
693
+
694
+ def split_of(hol_out: str, clean_out: str) -> dict:
695
+ gp5 = Path(td) / "split_gens.jsonl"
696
+ gp5.write_text(json.dumps({"id": "s-hol", "output": body + hol_out}) + "\n"
697
+ + json.dumps({"id": "s-clean",
698
+ "output": body + clean_out}) + "\n")
699
+ return score(str(rp5), str(gp5))["f1_split"]
700
+
701
+ # Holiday side passes while the no-holiday side fails...
702
+ s = split_of("<answer>2026-12-07</answer>", "<answer>2026-08-06</answer>")
703
+ assert s["n_holiday_affected"] == 1 and s["n_no_holiday"] == 1
704
+ assert s["holiday_affected"]["output"]["lenient_exact"]["pct"] == 100.0, s
705
+ assert s["no_holiday"]["output"]["lenient_exact"]["pct"] == 0.0, s
706
+ # ...and the reverse: the holiday side fails on the exact wrong answer the
707
+ # subpopulation exists to catch (the holiday-blind 2026-12-04) while the
708
+ # no-holiday side passes. The two sides are independent, so neither can mask
709
+ # the other in the adjudication.
710
+ s = split_of("<answer>2026-12-04</answer>", "<answer>2026-08-07</answer>")
711
+ assert s["holiday_affected"]["output"]["lenient_exact"]["pct"] == 0.0, s
712
+ assert s["holiday_affected"]["output"]["strict_exact"]["pct"] == 0.0, s
713
+ assert s["no_holiday"]["output"]["lenient_exact"]["pct"] == 100.0, s
714
+ ok += 1
715
+
716
+ print(f"\nscore_chrono selftest: {ok}/11 OK "
717
+ f"(every gate above was shown failing on purpose-built bad input, and the "
718
+ f"F1 split's two sides were shown moving independently)")
719
+
720
+
721
+ def main() -> None:
722
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
723
+ ap.add_argument("rows", nargs="?", help="row file carrying `params` per row")
724
+ ap.add_argument("gens", nargs="?", help="generation file from gcp_eval.py")
725
+ ap.add_argument("--report", default="")
726
+ ap.add_argument("--verdicts", default="")
727
+ ap.add_argument("--recompute", default="", help="verify a row file's golds and exit")
728
+ ap.add_argument("--selftest", action="store_true")
729
+ ap.add_argument("--pin-tzdata", action="store_true",
730
+ help="read timezone rules from the pip `tzdata` package only")
731
+ args = ap.parse_args()
732
+
733
+ if args.pin_tzdata:
734
+ import zoneinfo
735
+ zoneinfo.reset_tzpath([])
736
+ try:
737
+ import tzdata
738
+ print(f"tzdata pinned to the pip package, IANA {tzdata.IANA_VERSION}")
739
+ except ImportError:
740
+ raise SystemExit("--pin-tzdata needs `pip install tzdata`")
741
+
742
+ if args.selftest:
743
+ _selftest()
744
+ return
745
+ if args.recompute:
746
+ rows = load_rows(args.recompute)
747
+ drift = check_tz_drift(rows)
748
+ problems = verify_golds(rows) + drift
749
+ if problems:
750
+ print(f"FAIL: {len(problems)} problem(s)")
751
+ for p in problems[:40]:
752
+ print(f" {p}")
753
+ raise SystemExit(1)
754
+ mix = Counter(r.get("family", "") for r in rows)
755
+ print(f"recomputed {len(rows)} gold answers, all agree. mix={dict(mix)}")
756
+ return
757
+ if not (args.rows and args.gens):
758
+ ap.error("give ROWS.jsonl and GENS.jsonl, or --selftest, or --recompute FILE")
759
+ score(args.rows, args.gens, args.report, args.verdicts)
760
+
761
+
762
+ if __name__ == "__main__":
763
+ main()