diff --git a/docs/wording_amendments.md b/docs/wording_amendments.md new file mode 100644 index 00000000..784b6ec9 --- /dev/null +++ b/docs/wording_amendments.md @@ -0,0 +1,172 @@ +# Committed wording amendments: the 14 release 20261014 dropped + +`annotations/us_full_run_20260612_policyengine_4_16_1_populace/us_wording-amendments.json` +lists the wording amendments board releases from dashboard-data-20260930 on +made to published audit text: the case, the field (a row annotation, a case +note, or a decision's reasoning in the adjudication record), the exact old +text and its replacement. Each release that made amendments appended them as +one block. Release dashboard-data-20261006's whole-field rewrites are in two +other records (`docs/release_20261006/annotation_rewrites.json` and +`reference_audit/2026-10-05-medicaid-031-annotations/rewrites.json`). Its 342 +on audit text are on cases release 20261010 re-judged. Its 9 on the +reference explanations show their new text at every board release since. +Three later releases, 20261010, 20261013 and 20261027, changed that file, but +only in 23, 9 and 4 other rows. Nothing in this module checks those 9. +`policybench/wording_amendments.py` says which of +the record's entries are in force and whether the committed files publish +them, and gives the next board release the restoration of the 14 that no +release since dashboard-data-20261014 has published. + +## What happened + +Release dashboard-data-20261013b re-judged five cases and amended 14 passages +of their text: six on `scenario_015` `head_medicaid_eligible`, three on +`scenario_015` `federal_refundable_credits`, two each on `scenario_014` and +`scenario_086` `federal_refundable_credits`, and one on `scenario_045` `snap` +(record entries 856 to 869, ten targets: four case notes and six row +annotations). Its committed files and snapshot publish them. + +Release dashboard-data-20261014 (#221) kept those five cases. Its driver, +`scripts/finish_argon.py`, rebuilt every case's text from the seed's +verdicts, which hold the judge's wording from before the amendments, and +replayed only its own stage's amendments, which `load_amendments` limits to +cases it re-judged. None of its gates compared a kept case's text with the +base release's committed files: export's scope check holds the incumbents' +`modelStats`, and the freeze rebuilds the annotation files by triage's own +rule (it held the reference explanations and the adjudication record to the +base, but not the two text files). So it published the 14 passages' old +text, and the freeze copied the record forward unchanged. Release 20261013b's +own tests of its committed text stop running once the pointer names a later +release. + +Release dashboard-data-20261027 rebuilt the same text from the same verdicts. +Release dashboard-data-20261111's carry (`carry_kept_wording`, +`docs/fable52/design.md`) carries each kept case's text from release +20261027's committed files, so it carried the old text too, as +`committed_amendments` in `scripts/freeze_fable52.py` notes. No other entry +of the record, and none of release 20261006's 351 rewrites, was dropped on a +case a later release kept: each is published at its own release, and while +its case is kept. Compared release to release, the text +of a case the later release kept changed only through release 20261006's +rewrites, the 14, and the adjudication sentences new decisions appended. + +## The invariant + +A row annotation or case note amendment is in force from its release until a +later release re-judges its case; the new verdict then replaces the text it +corrected. A reasoning amendment stays in force while the adjudication record +holds the decision: a re-judge changes a decision's reasoning only through +listed amendments (`verify_adjudication_record` in the freezes), and the case +note's adjudication sentence restates the reasoning. While an amendment is in +force, the committed files must publish its new text and not its old: a row +annotation in its row; a case note amendment in the note's body, the text +before any adjudication sentence; a reasoning amendment in the adjudication +record and in the sentence. The payload's cells carry the same texts. + +`superseding_releases` reads each release's re-judged cases from its +`judge_provenance.json`, registered and pinned by sha256 in `RELEASES`. +Later entries of the same target can rewrite part of an entry's new text, so +`entry_state` undoes them, last first, before testing it. An amendment that +cuts words has its new text inside its old; `holds` counts each outside the +other. The test is presence in the target's text, not position: a target +whose row, note or decision is gone reads MISSING, and an old text that an +unrelated later edit puts back in the same field reads BOTH. Both fail safe. +So does a decision that a later release replaces outright or removes: its +reasoning amendments read NEITHER or MISSING, and that release fails the +tests until it lists amendments for the new reasoning or this module gains a +rule that retires the old ones. + +The rule cannot see a re-judge whose new text says again what a retired +amendment corrected. At release 20261111, 11 retired row amendments read +that way: their old text is published and their new text is not. They are +entry 323 (retired by release 20261010), entries 688 and 792 (20261014), and +entries 1355, 1560, 1709, 1818, 1943, 2023, 2133 and 2377 (20261111). A +re-judge can change the reference or the verdict, so whether each row is +still wrong takes a case-by-case reading. That reading is outside this +restoration. + +`tests/test_wording_amendments.py` holds the working tree's committed row +annotations, case notes, adjudication record and snapshot to every amendment +in force, except the entries `known_dropped` names for the release the app's +pointer names: the 14 for releases 20261014, 20261027 and 20261111, a closed +list the tests pin, and none for any later release. The registry test +requires every release that moves the pointer, appends amendments or commits +a `judge_provenance.json` to be listed in `RELEASES`, and every listed +provenance file to match its pin, so the next board release fails the tests +if it leaves the 14 dropped or drops any other amendment in force. + +The tests check that with release 20261111's data from git: a Hypothesis +property puts back the old text of any of the 414 row and note amendments in +force that no later entry rewrites and requires `dropped_amendments` to name +it and `restore_frames` to give the files back; undoing the whole chain of +each of the 414 targets in force flags it; and reverting the reasoning of +each of the 10 decisions the 17 reasoning amendments correct, in the record +or only in the sentence, flags every one of the 17. + +## The restoration, for the next board release + +The 14 are pinned by content (`DROPPED_BY_20261014_SHA256`), so an edit to +the record cannot change what is restored. Restoring them on release +20261111's committed files gives each of the ten targets the text release +20261013b committed, byte for byte, and changes nothing else; in the payload +it rewrites `annotation` or the body of `caseAnnotation` in 18 cells and no +other field. No score, statistic or rank moves: nothing that computes one +reads annotation text, and the reverse change, release 20261014's, moved no +incumbent's `modelStats` or heatmap row. + +The next release's driver, forked from `scripts/finish_fable52.py` with +release 20261111 as its base, takes the restoration through the carry: + +1. `base_annotation_frames` restores the 14 on the base's committed files: + `restore_frames(rows, notes, dropped_by_20261014(record))`, all 14 + restored, with the record read at `BASE_COMMIT` as the driver reads its + other base files. The carry then gives every kept case the restored text, + and `kept_annotation_problems` holds triage, export and the freeze to it. +2. `prepare_inputs` writes the restored text when it copies the two + annotation files into the bundle (`restore_csv_texts`, which writes them as + triage does), so a full `--early` rehearsal, which runs check (a) on the + copied files, carries the restoration too. Read the two files from + `BASE_COMMIT` there too, as step 1 does, rather than from the working tree; + otherwise a direct fix to the committed files that lands first makes + `restore_text` refuse (it fails closed). +3. Check (a), `base_restoration_problems`, compares the scope export's cells + with `restore_payload(live, entries, reopened=reopened)` instead of + `live`, in `_build_payload_in_scratch`, which export and the freeze's + rebuild both call. A case the release re-opens keeps its new verdict's + text; `restore_payload` skips it, and check (a) exempts its text fields + anyway. +4. The record is not changed: the 14 entries are already in it. The freeze's + `committed_amendments` note about them is dropped, and the forked + docstrings that say the carry reproduces the base's committed wording say + instead that it carries the restored base. +5. The release adds itself to `RELEASES`, with its block size and its pinned + judge provenance. `known_dropped` gives it none, so the tests hold its + committed files and snapshot to all 14. The restoration tests read + release 20261111's files from git and need no change. +6. The driver's inherited MOCK boards (the freeze tests' `_h_build_template` + and the finish tests' `_serve_mock_base`) run triage and export on MOCK + files and a MOCK record, where the restoration raises. Give steps 1 and 3 + one shared, explicit seam: for example, a module-level function or + constant that names the entries to restore, which the MOCK fixtures patch + to none, as they already patch `SEED_DIGEST_SHA256`. Add one test that the + unpatched driver restores all 14 on the real base. Do not use a try/except + or a condition on the record's shape: a seam that can turn both steps off + in production passes check (a) and the kept gate, because both sides are + then unrestored. Only step 5's tests would catch it, after the freeze. + +`tests/test_wording_amendments.py` runs steps 1 and 3 through the Fable 5.2 +driver's functions: with the restored base, triage's frames are the restored +files and the kept-case gate passes them; a release that carries the base +without the restoration fails that gate on each of the ten targets. Against +the restored base payload, check (a) flags the one cell of an export +missing one restored row and all 18 cells of an export missing all of it. +Its passing case builds the export with `restore_payload` itself, so it +shows only that check (a) accepts the restored payload. It does not run +export from the restored files, or the next driver, which does not exist +yet. + +Publishing the restoration changes published text on kept cells, so it ships +only on the maintainer's go. The release note would say: "Restores the +corrected wording of 14 annotation passages on five cases, which release +dashboard-data-20261014 had reverted to their earlier text. No score or rank +changes." diff --git a/policybench/wording_amendments.py b/policybench/wording_amendments.py new file mode 100644 index 00000000..936eb455 --- /dev/null +++ b/policybench/wording_amendments.py @@ -0,0 +1,632 @@ +"""Which committed wording amendments are in force, and whether the committed +annotation files publish them. + +``annotations//us_wording-amendments.json`` lists the wording amendments +board releases from dashboard-data-20260930 on made to published audit text: +the case, the field (one model's row annotation, a case note, or a decision's +reasoning in the adjudication record), the exact old text and its +replacement. Each release that made amendments appended them as one block. +(Release dashboard-data-20261006's whole-field rewrites are in two other +records, docs/release_20261006/annotation_rewrites.json and +reference_audit/2026-10-05-medicaid-031-annotations/rewrites.json. Its 342 on +audit text are on cases release 20261010 re-judged; its 9 on the reference +explanations are published at every board release since. The three releases +that changed that file since, 20261010, 20261013 and 20261027, changed other +rows. Nothing here checks those 9.) + +A row annotation or case note amendment stays in force until a later release +re-judges its case: the new verdict then replaces the text it corrected, and +that release's own amendments, if any, speak for the new text. A reasoning +amendment stays in force while the adjudication record holds the decision: a +re-judge changes a decision's reasoning only through listed amendments, and +the case note's adjudication sentence restates it. While an amendment is in +force, the committed files must publish its new text and not its old. + +Release dashboard-data-20261014 broke that for the 14 amendments release +dashboard-data-20261013b made (entries 856 to 869). Its driver rebuilt the text +of every case it kept from the case's verdict and replayed only its own stage's +amendments, and no gate compared a kept case's text with the record, so it and +every release since published the five cases' text without them. +``dropped_amendments`` finds the amendments in force that a set of committed +texts does not publish. ``restore_frames``, ``restore_csv_texts`` and +``restore_payload`` give the next board release the restoration of the 14. +docs/wording_amendments.md has the trace and the steps for that release's +driver. +""" + +from __future__ import annotations + +import copy +import csv +import hashlib +import io +import json +from collections.abc import Callable, Iterable, Sequence +from dataclasses import dataclass +from pathlib import Path + +from policybench.adjudications import _ADJUDICATION_MARKER + +ROOT = Path(__file__).resolve().parents[1] +RUN_LABEL = "us_full_run_20260612_policyengine_4_16_1_populace" +ANNOTATIONS = Path("annotations") / RUN_LABEL +RECORD_PATH = ANNOTATIONS / "us_wording-amendments.json" +ROW_ANNOTATIONS_PATH = ANNOTATIONS / "us_audit_row_annotations.csv" +CASE_NOTES_PATH = ANNOTATIONS / "us_case_notes.csv" +ADJUDICATIONS_PATH = ANNOTATIONS / "us_adjudications.json" +POINTER_PATH = Path("app/src/data.artifact.json") + +# The fields an amendment may name, and where each one's text is published: +# the row annotations file (one model's row), the body of the case note (its +# text before any adjudication sentence), and the adjudication record (a +# decision's reasoning, which the case note's adjudication sentence restates). +TEXT_FIELDS = ("annotation", "case_annotation", "reasoning") + + +@dataclass(frozen=True) +class Release: + """One board release from the record's first on, oldest first. + + ``amendments`` is how many entries it appended to the record. + ``judge_provenance`` is the committed record of the verdicts it judged + again (each names its ``case_id``), or None when it re-judged no case, + and ``judge_provenance_sha256`` pins that file's bytes, so an edit to it + cannot retire an amendment unseen. + """ + + tag: str + amendments: int + judge_provenance: str | None + judge_provenance_sha256: str | None = None + + +# Every board release since the record began, in publication order. A release +# that appends amendments or re-judges cases must be listed here, and the last +# entry must be the release app/src/data.artifact.json names: the tests hold +# the blocks to the record's length, the last tag to the pointer and the +# listed provenance files to every one committed, so an unlisted release fails +# them rather than hiding a dropped amendment. +RELEASES: tuple[Release, ...] = ( + Release( + "dashboard-data-20260930", + 394, + "docs/gpt61sol/judge_provenance.json", + "6f7ec329b93a39a8f6fd556c3a3c2f0dbba5d2be6dd31d14ea92a64e3acbb77b", + ), + Release("dashboard-data-20261006", 0, None), + Release( + "dashboard-data-20261010", + 0, + "docs/haiku55/judge_provenance.json", + "f0d0b32ffb0b045a5516fcdaa6c7536a0476023f270e57d7daad4c5355315715", + ), + Release( + "dashboard-data-20261013", + 462, + "docs/musewonder/judge_provenance.json", + "8734eadc9fe2afb17ec09408b832be35c635d362d6249a3b20765c9446a61edc", + ), + Release( + "dashboard-data-20261013b", + 14, + "docs/release_20261013b/judge_provenance.json", + "b07a270d9b0d081deec519805324f6326d3f9e69de4caaa3860a1409aff587e8", + ), + Release( + "dashboard-data-20261014", + 0, + "docs/argon/judge_provenance.json", + "d03ad43ca15f5982293d34dfdc298960852aeab1ff1f8abb3b3e936a68998698", + ), + Release( + "dashboard-data-20261027", + 1578, + "docs/terra/judge_provenance.json", + "e86bdc31f8f1c692c49e4166df2019f6ee96edad2c5032e8a7cfe80c0da3aa80", + ), + Release( + "dashboard-data-20261111", + 0, + "docs/fable52/judge_provenance.json", + "16eef650f1873511b3e50436fc44880cdc22b54906b905403c8b7c0e8f3c2dd6", + ), +) + +# The 14 amendments release dashboard-data-20261013b made (record entries 856 +# to 869, its whole block), which release dashboard-data-20261014 dropped and +# no release since has published. The sha256 is of the 14 entries as +# json.dumps(entries, sort_keys=True, ensure_ascii=False) spells them, so an +# edit to the record cannot change what the restoration applies. +DROPPED_BY_20261014 = tuple(range(856, 870)) +DROPPED_BY_20261014_SHA256 = ( + "035b7e85e5592afae161de3fc3ee23c6e2af75bea6922fc1c766a76af45a134a" +) +# The releases whose committed files and payload publish the 14's old text. +# Closed: the tests pin it to these three, so no later release can join it. +PUBLISHED_WITHOUT_THE_14 = ( + "dashboard-data-20261014", + "dashboard-data-20261027", + "dashboard-data-20261111", +) + +APPLIED = "APPLIED" +REVERTED = "REVERTED" +BOTH = "BOTH" +NEITHER = "NEITHER" +MISSING = "MISSING" + + +class WordingAmendmentError(ValueError): + """A record, a text or a restoration that does not hold.""" + + +def _require(condition: bool, message: str) -> None: + if not condition: + raise WordingAmendmentError(message) + + +def parse_record(record: dict, label: object = RECORD_PATH) -> list[dict]: + """A wording amendments record's entries, in order, each checked to name + a text field and, for a row annotation alone, a model.""" + entries = record.get("amendments") if isinstance(record, dict) else None + _require(isinstance(entries, list), f"{label}: no amendments list") + for index, entry in enumerate(entries): + _require( + isinstance(entry, dict) and entry.get("field") in TEXT_FIELDS, + f"{label} entry {index}: not an amendment of {TEXT_FIELDS}", + ) + _require( + ("model" in entry) == (entry["field"] == "annotation"), + f"{label} entry {index}: a row annotation names its model, " + "and nothing else does", + ) + return entries + + +def load_record(root: Path = ROOT) -> list[dict]: + """The record's entries under ``root``, in order.""" + return parse_record(json.loads((root / RECORD_PATH).read_text(encoding="utf-8"))) + + +def entry_releases( + record: Sequence[dict], releases: Sequence[Release] = RELEASES +) -> list[str]: + """Each entry's release tag, from the releases' block sizes in order.""" + tags = [r.tag for r in releases for _ in range(r.amendments)] + _require( + len(tags) == len(record), + f"the releases' blocks cover {len(tags)} entries; the record holds " + f"{len(record)}: list the release that appended the rest", + ) + return tags + + +def rejudged_cases( + root: Path = ROOT, releases: Sequence[Release] = RELEASES +) -> dict[str, frozenset[str]]: + """Each release's re-judged cases, as case ids, from its judge provenance, + each file checked against its pin.""" + out: dict[str, frozenset[str]] = {} + for release in releases: + if release.judge_provenance is None: + out[release.tag] = frozenset() + continue + raw = (root / release.judge_provenance).read_bytes() + digest = hashlib.sha256(raw).hexdigest() + _require( + digest == release.judge_provenance_sha256, + f"{release.judge_provenance} hashes to {digest}, not the " + f"{release.judge_provenance_sha256} {release.tag} pins", + ) + data = json.loads(raw) + out[release.tag] = frozenset(v["case_id"] for v in data["verdicts"]) + return out + + +def superseding_releases( + record: Sequence[dict], + root: Path = ROOT, + releases: Sequence[Release] = RELEASES, +) -> list[str | None]: + """For each entry, the first release after its own that re-judged its + case, or None while the entry is in force. A reasoning entry is never + superseded by a re-judge (the module docstring says why): it stays in + force, and a decision that leaves the record leaves it MISSING.""" + tags = [r.tag for r in releases] + rejudged = rejudged_cases(root, releases) + out: list[str | None] = [] + for entry, tag in zip(record, entry_releases(record, releases), strict=True): + if entry["field"] == "reasoning": + out.append(None) + continue + later = tags[tags.index(tag) + 1 :] + out.append(next((t for t in later if entry["case_id"] in rejudged[t]), None)) + return out + + +def target(entry: dict) -> tuple[str, str, str | None]: + """Where an entry's text lives: its case, its field and, for a row + annotation, its model.""" + return entry["case_id"], entry["field"], entry.get("model") + + +def split_note(note: str) -> tuple[str, str]: + """A case note's body (the text collect_audit writes) and its + adjudication sentence (apply_adjudications' text, or "" when the case has + no decision). Case note amendments name the body; a decision's reasoning + is restated in the sentence.""" + index = note.find(_ADJUDICATION_MARKER) + return (note, "") if index < 0 else (note[:index], note[index:]) + + +def holds(text: str, entry: dict) -> tuple[bool, bool]: + """Whether ``text`` holds ``entry``'s old text and its new text, each + counted outside the other where one contains the other: an amendment + that cuts words ("exactly 12% × $9,629 = $1,155.43" to "$1,155.43") has + its new text inside its old, and one that adds words has its old inside + its new.""" + old, new = entry["old"], entry["new"] + if new in old: + return old in text, new in text.replace(old, "\x00") + return old in text.replace(new, "\x00"), new in text + + +def entry_state(text: str | None, entry: dict, later: Iterable[dict] = ()) -> str: + """Whether ``text`` publishes ``entry``. + + ``later`` are the record's later entries of the same target, in record + order. Each may rewrite part of this entry's new text with its context, + so they are undone first, last first, each new text back to its old once + where it occurs. Then (holds) APPLIED: the new text is there and the old + is not; REVERTED: the old text is there and the new is not; BOTH, + NEITHER, or MISSING when there is no text (the target's row, note or + decision is gone). + + The test is presence in the target's text, not position: it cannot tell + a dropped amendment whose new text the same field also holds elsewhere, + and an old text that a later, unrelated edit puts back elsewhere in the + field reads BOTH. + """ + if text is None: + return MISSING + for item in reversed(list(later)): + if item["new"] in text: + text = text.replace(item["new"], item["old"], 1) + has_old, has_new = holds(text, entry) + if has_new and not has_old: + return APPLIED + if has_old and not has_new: + return REVERTED + return BOTH if has_old else NEITHER + + +# A source of published text: for an entry, every text that publishes its +# target (one row, one case note's body, a decision's reasoning and the +# sentence restating it, or every payload cell carrying one of those). +TextSource = Callable[[dict], list[str | None]] + + +def _case_key(case_id: str) -> tuple[str, str, str]: + country, scenario, variable = case_id.split("__", 2) + return country, scenario, variable + + +def frame_source(rows, notes, adjudications: Sequence[dict] = ()) -> TextSource: + """Texts from the row annotations and case notes (frames or the parsed + CSVs, with country, scenario_id, variable, model and annotation, and + case_annotation) and the adjudication record's entries. + + A row annotation entry reads its row; a case note entry, the note's body; + a reasoning entry, the record's reasoning for the case and the note's + adjudication sentence (None when the note has none).""" + published_rows: dict[tuple, list[str]] = {} + for r in _records(rows): + key = (str(r["country"]), str(r["scenario_id"]), str(r["variable"])) + published_rows.setdefault((*key, str(r["model"])), []).append( + str(r["annotation"]) + ) + published_notes: dict[tuple, list[tuple[str, str]]] = {} + for r in _records(notes): + key = (str(r["country"]), str(r["scenario_id"]), str(r["variable"])) + published_notes.setdefault(key, []).append( + split_note(str(r["case_annotation"])) + ) + reasoning: dict[tuple, list[str]] = {} + for e in adjudications: + key = (e.get("country", "us"), e["scenario_id"], e["variable"]) + reasoning.setdefault(key, []).append(str(e.get("reasoning", ""))) + + def texts(entry: dict) -> list[str | None]: + key = _case_key(entry["case_id"]) + if entry["field"] == "annotation": + found = published_rows.get((*key, entry["model"]), []) + _require(len(found) <= 1, f"{entry['case_id']}: more than one row") + return list(found) or [None] + note = published_notes.get(key, []) + _require(len(note) <= 1, f"{entry['case_id']}: more than one case note") + if entry["field"] == "case_annotation": + return [note[0][0] if note else None] + decided = reasoning.get(key) + return [ + "\n".join(decided) if decided else None, + (note[0][1] or None) if note else None, + ] + + return texts + + +def payload_source(payload: dict) -> TextSource: + """Texts from a dashboard payload's cells: a row annotation is its + model's cell's ``annotation``; a case note is the body of the + ``caseAnnotation`` of every cell that carries one, and a decision's + reasoning its adjudication sentence. The payload is the published wrapper + (with ``countries``) or the country payload the snapshot stores.""" + country = payload["countries"]["us"] if "countries" in payload else payload + predictions = country["scenarioPredictions"] + + def texts(entry: dict) -> list[str | None]: + _, scenario, variable = _case_key(entry["case_id"]) + cells = predictions.get(scenario, {}).get(variable, {}) + if entry["field"] == "annotation": + cell = cells.get(entry["model"]) + return [None if cell is None else cell.get("annotation")] + notes = [ + split_note(c["caseAnnotation"]) + for c in cells.values() + if "caseAnnotation" in c + ] + if entry["field"] == "case_annotation": + return [body for body, _ in notes] or [None] + return [sentence or None for _, sentence in notes] or [None] + + return texts + + +def committed_source(root: Path = ROOT) -> TextSource: + """Texts from the committed row annotations, case notes and adjudication + record under ``root``.""" + rows, notes = ( + list(csv.DictReader(io.StringIO((root / p).read_text(encoding="utf-8")))) + for p in (ROW_ANNOTATIONS_PATH, CASE_NOTES_PATH) + ) + record = json.loads((root / ADJUDICATIONS_PATH).read_text(encoding="utf-8")) + return frame_source(rows, notes, record["adjudications"]) + + +def later_same_target(record: Sequence[dict]) -> list[list[dict]]: + """For each entry, the record's later entries of its target, in record + order.""" + out: list[list[dict]] = [[] for _ in record] + seen: dict[tuple, list[dict]] = {} + for index in range(len(record) - 1, -1, -1): + found = seen.setdefault(target(record[index]), []) + out[index] = found[::-1] + found.append(record[index]) + return out + + +def dropped_amendments( + record: Sequence[dict], + source: TextSource, + root: Path = ROOT, + releases: Sequence[Release] = RELEASES, + *, + superseded: Sequence[str | None] | None = None, +) -> list[tuple[int, str]]: + """Each amendment in force that ``source`` does not publish, with its + state (REVERTED, BOTH, NEITHER or MISSING), in record order. + + In force is superseding_releases' (or ``superseded``, when the caller + computed it). An entry's later entries of the same target, in force + whenever it is, are undone first (entry_state). Every text the source + gives for the target must publish it. + """ + if superseded is None: + superseded = superseding_releases(record, root, releases) + _require(len(superseded) == len(record), "one superseding release per entry") + chains = later_same_target(record) + out: list[tuple[int, str]] = [] + for index, entry in enumerate(record): + if superseded[index] is not None: + continue + states = [entry_state(t, entry, chains[index]) for t in source(entry)] + bad = next((s for s in states if s != APPLIED), None) + if bad is not None: + out.append((index, bad)) + return out + + +def known_dropped(tag: str) -> tuple[int, ...]: + """The record entries release ``tag``'s committed files are known not to + publish: the 14 for the three releases that published without them, and + none for any other. A release after dashboard-data-20261111 must publish + every amendment in force.""" + return DROPPED_BY_20261014 if tag in PUBLISHED_WITHOUT_THE_14 else () + + +def dropped_by_20261014(record: Sequence[dict]) -> list[dict]: + """The 14 entries to restore, checked against their pin.""" + _require( + len(record) > DROPPED_BY_20261014[-1], + f"the record has {len(record)} entries; the 14 are entries " + f"{DROPPED_BY_20261014[0]} to {DROPPED_BY_20261014[-1]}", + ) + entries = [record[i] for i in DROPPED_BY_20261014] + digest = hashlib.sha256( + json.dumps(entries, sort_keys=True, ensure_ascii=False).encode() + ).hexdigest() + _require( + digest == DROPPED_BY_20261014_SHA256, + f"record entries {DROPPED_BY_20261014[0]} to {DROPPED_BY_20261014[-1]} " + f"hash to {digest}, not the pinned {DROPPED_BY_20261014_SHA256}", + ) + _require( + all(e["field"] in ("annotation", "case_annotation") for e in entries), + "a restoration names a row annotation or a case note only", + ) + return entries + + +def restore_text(text: str, entries: Iterable[dict], label: str) -> str: + """``text`` with each entry's old text, found exactly once and with its + new text absent, replaced by the new text.""" + for entry in entries: + _require( + not holds(text, entry)[1], + f"{label}: already holds the new text of {entry['case_id']} " + f"{entry['field']}: {entry['new'][:80]!r}", + ) + count = text.count(entry["old"]) + _require( + count == 1, + f"{label}: the old text occurs {count} times, not once: " + f"{entry['old'][:80]!r}", + ) + text = text.replace(entry["old"], entry["new"]) + return text + + +def _restore_field(text: str, entry: dict, label: str) -> str: + """A row annotation, or a case note with the entry restored in its body + and its adjudication sentence kept as it is.""" + if entry["field"] == "annotation": + return restore_text(text, [entry], label) + body, sentence = split_note(text) + return restore_text(body, [entry], label) + sentence + + +def _records(frame) -> list[dict]: + return frame.to_dict("records") if hasattr(frame, "to_dict") else list(frame) + + +def _restorable(entry: dict) -> None: + _require( + entry["field"] in ("annotation", "case_annotation"), + f"{entry['case_id']}: only a row annotation or a case note is restored", + ) + + +def restore_frames(rows, notes, entries: Sequence[dict], *, reopened=frozenset()): + """Copies of ``rows`` and ``notes`` with ``entries`` restored, and the + entries restored and skipped. + + ``rows`` and ``notes`` are pandas frames shaped as the committed files + are (or as a release driver's triage builds them): country, scenario_id, + variable and model with annotation, and country, scenario_id and variable + with case_annotation. Each entry must find exactly one row or note, and + its old text exactly once in that row or in that note's body. An entry on + a case in ``reopened`` is skipped and its text left as it is: the release + judged that case again, so the new verdict's text replaces the text the + entry corrected. Entries are applied in the order given. + """ + rows, notes = rows.copy(), notes.copy() + _require( + rows.index.is_unique and notes.index.is_unique, + "restore_frames needs frames with a unique index", + ) + restored: list[dict] = [] + skipped: list[dict] = [] + for entry in entries: + _restorable(entry) + if entry["case_id"] in reopened: + skipped.append(entry) + continue + country, scenario, variable = _case_key(entry["case_id"]) + frame = rows if entry["field"] == "annotation" else notes + mask = ( + (frame["country"].astype(str) == country) + & (frame["scenario_id"].astype(str) == scenario) + & (frame["variable"].astype(str) == variable) + ) + if entry["field"] == "annotation": + mask &= frame["model"].astype(str) == entry["model"] + _require( + int(mask.sum()) == 1, + f"{entry['case_id']} {entry['field']} " + f"{entry.get('model') or ''}: {int(mask.sum())} rows, not one", + ) + index = frame.index[mask][0] + frame.loc[index, entry["field"]] = _restore_field( + str(frame.loc[index, entry["field"]]), + entry, + f"{entry['case_id']} {entry['field']} {entry.get('model') or ''}", + ) + restored.append(entry) + return rows, notes, restored, skipped + + +def restore_csv_texts( + rows_text: str, notes_text: str, entries: Sequence[dict], *, reopened=frozenset() +): + """The row annotations and case notes files' text with ``entries`` + restored (restore_frames), each read with ``keep_default_na=False`` (so + empty cells stay empty; pandas still infers numeric and boolean columns) + and written as triage writes it (``to_csv(index=False)``), and the + entries restored and skipped. With no entries this gives each board + release's committed files back byte for byte, from dashboard-data-20260930 + to dashboard-data-20261111.""" + import pandas as pd + + rows, notes = ( + pd.read_csv(io.StringIO(text), keep_default_na=False) + for text in (rows_text, notes_text) + ) + rows, notes, restored, skipped = restore_frames( + rows, notes, entries, reopened=reopened + ) + return rows.to_csv(index=False), notes.to_csv(index=False), restored, skipped + + +def restore_payload(payload: dict, entries: Sequence[dict], *, reopened=frozenset()): + """``payload`` with ``entries`` restored in its cells, and the entries + restored and skipped. + + A row annotation entry rewrites its model's cell's ``annotation``; a case + note entry rewrites the body of the ``caseAnnotation`` of every cell that + carries one, and at least one must. The payload is the published wrapper + (with ``countries``) or a country payload, and the result has the same + shape and key order. Only the dicts on the path to a changed cell are + copied; the rest is shared with ``payload``. A case in ``reopened`` is + skipped, as in restore_frames. + """ + wrapped = "countries" in payload + out = dict(payload) + if wrapped: + out["countries"] = dict(payload["countries"]) + country = out["countries"]["us"] = dict(payload["countries"]["us"]) + else: + country = out + country["scenarioPredictions"] = dict(country["scenarioPredictions"]) + predictions = country["scenarioPredictions"] + restored: list[dict] = [] + skipped: list[dict] = [] + for entry in entries: + _restorable(entry) + if entry["case_id"] in reopened: + skipped.append(entry) + continue + _, scenario, variable = _case_key(entry["case_id"]) + _require( + variable in predictions.get(scenario, {}), + f"{entry['case_id']}: no cells in the payload", + ) + predictions[scenario] = dict(predictions[scenario]) + cells = predictions[scenario][variable] = dict(predictions[scenario][variable]) + if entry["field"] == "annotation": + names = [entry["model"]] if entry["model"] in cells else [] + field = "annotation" + else: + names = [m for m, c in cells.items() if "caseAnnotation" in c] + field = "caseAnnotation" + _require( + bool(names) and all(field in cells[m] for m in names), + f"{entry['case_id']} {entry['field']} {entry.get('model') or ''}: " + f"no cell carries {field}", + ) + for model in names: + cells[model] = copy.copy(cells[model]) + cells[model][field] = _restore_field( + cells[model][field], entry, f"{entry['case_id']} {model} {field}" + ) + restored.append(entry) + return out, restored, skipped diff --git a/tests/test_wording_amendments.py b/tests/test_wording_amendments.py new file mode 100644 index 00000000..19c4748f --- /dev/null +++ b/tests/test_wording_amendments.py @@ -0,0 +1,872 @@ +"""Tests for policybench.wording_amendments: every committed wording +amendment in force is published, and the restoration of the 14 that release +dashboard-data-20261014 dropped. + +Two kinds of data test. The invariant and registry tests read the working +tree, so they hold every later release's committed files. The restoration +tests read release dashboard-data-20261111's files from git at its board +commit, the base the next release restores the 14 on, so they still hold +once that release commits the restored text. Unit tests whose text is +invented say MOCK. +""" + +from __future__ import annotations + +import functools +import gzip +import io +import json +import subprocess +import sys +from collections import Counter +from pathlib import Path + +import pandas as pd +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +from policybench import wording_amendments as wa +from policybench.adjudications import parse_adjudications + +ROOT = Path(__file__).resolve().parents[1] +SNAPSHOT_PATH = Path("paper/snapshot/20260501/runs") / wa.RUN_LABEL / "data.json.gz" +# Board commits (docs/runbook.md, "Releases cut before sealing", and #260): +# release dashboard-data-20261013b, which last published the 14, and release +# dashboard-data-20261111, the base the next release restores them on. +COMMIT_20261013B = "2cb77a17" +COMMIT_20261111 = "e61eea4c" +TAG_20261111 = "dashboard-data-20261111" +# The payload cells the restoration rewrites: the 17 that carry one of the +# four restored case notes (11 on scenario_086, 2 on each other case) and +# the six restored rows' cells, five of them among the 17. +RESTORED_CELLS = 18 +RESTORED_CELL_FIELDS = 23 +# Of the 32 in-force amendments that later entries of their target rewrite +# (18 case notes, 7 rows, 7 reasoning) at release 20261111, 20 can be dropped +# alone with the later entries kept; in the other 12 a later entry rewrites +# words inside the dropped entry's new text. +BUILT_INSIDE = 20 +UNBUILDABLE_INSIDE = 12 + +FIVE_CASES = Counter( + { + "us__scenario_015__head_medicaid_eligible": 6, + "us__scenario_015__federal_refundable_credits": 3, + "us__scenario_014__federal_refundable_credits": 2, + "us__scenario_086__federal_refundable_credits": 2, + "us__scenario_045__snap": 1, + } +) + + +def git_bytes(commit: str, path: Path) -> bytes: + return subprocess.run( + ["git", "-C", str(ROOT), "show", f"{commit}:{path.as_posix()}"], + capture_output=True, + check=True, + ).stdout + + +def read_frames(rows_text: str, notes_text: str) -> tuple[pd.DataFrame, ...]: + return tuple( + pd.read_csv(io.StringIO(text), keep_default_na=False) + for text in (rows_text, notes_text) + ) + + +def targets(entries) -> set[tuple]: + return {wa.target(e) for e in entries} + + +# --- The working tree: what the pointer's release committed ---------------------- + + +@functools.cache +def record() -> tuple[dict, ...]: + return tuple(wa.load_record()) + + +@functools.cache +def superseded() -> tuple[str | None, ...]: + return tuple(wa.superseding_releases(record())) + + +@functools.cache +def snapshot_text() -> str: + return gzip.decompress((ROOT / SNAPSHOT_PATH).read_bytes()).decode("utf-8") + + +# --- Release 20261111 at its board commit: the base of the restoration ------------ + +RELEASES_TO_20261111 = wa.RELEASES[ + : [r.tag for r in wa.RELEASES].index(TAG_20261111) + 1 +] + + +@functools.cache +def base_record() -> tuple[dict, ...]: + return tuple( + wa.parse_record(json.loads(git_bytes(COMMIT_20261111, wa.RECORD_PATH))) + ) + + +@functools.cache +def base_superseded() -> tuple[str | None, ...]: + return tuple(wa.superseding_releases(base_record(), ROOT, RELEASES_TO_20261111)) + + +@functools.cache +def base_text() -> tuple[str, str]: + return tuple( + git_bytes(COMMIT_20261111, path).decode("utf-8") + for path in (wa.ROW_ANNOTATIONS_PATH, wa.CASE_NOTES_PATH) + ) + + +def base_frames() -> tuple[pd.DataFrame, pd.DataFrame]: + return read_frames(*base_text()) + + +@functools.cache +def base_adjudications() -> tuple[dict, ...]: + data = json.loads(git_bytes(COMMIT_20261111, wa.ADJUDICATIONS_PATH)) + return tuple(data["adjudications"]) + + +@functools.cache +def base_snapshot_text() -> str: + return gzip.decompress(git_bytes(COMMIT_20261111, SNAPSHOT_PATH)).decode("utf-8") + + +def base_snapshot() -> dict: + return json.loads(base_snapshot_text()) + + +@functools.cache +def the_14() -> tuple[dict, ...]: + return tuple(wa.dropped_by_20261014(base_record())) + + +@functools.cache +def restored_text() -> tuple[str, str]: + rows, notes, restored, skipped = wa.restore_csv_texts(*base_text(), the_14()) + assert len(restored) == 14 and skipped == [] + return rows, notes + + +def restored_frames() -> tuple[pd.DataFrame, pd.DataFrame]: + return read_frames(*restored_text()) + + +def base_dropped(source) -> list[tuple[int, str]]: + return wa.dropped_amendments(base_record(), source, superseded=base_superseded()) + + +# --- The registry ------------------------------------------------------------------ + + +def test_the_registry_lists_every_release_since_the_record_began(): + """The releases' blocks cover the record, the last release is the one + the app's pointer names, every committed judge provenance file is a + listed release's and matches its pin, and the record begins with release + 20261111's record unchanged. A release that appends amendments, commits a + judge_provenance.json under docs/, moves the pointer or edits a + provenance file without a RELEASES entry fails here. (Entries appended + after release 20261111 are held only by the count here and by the + invariant below. A freeze forked from scripts/freeze_fable52.py commits + the base's record with only its own block appended: committed_amendments.)""" + assert len(wa.entry_releases(record())) == len(record()) + pointer = json.loads((ROOT / wa.POINTER_PATH).read_text()) + assert wa.RELEASES[-1].tag == pointer["tag"] + tags = [r.tag for r in wa.RELEASES] + assert len(set(tags)) == len(tags) and tags == sorted(tags) + named = {r.judge_provenance for r in wa.RELEASES if r.judge_provenance} + found = { + p.relative_to(ROOT).as_posix() + for p in (ROOT / "docs").rglob("judge_provenance.json") + } + assert named == found + assert set(wa.rejudged_cases()) == set(tags) + assert record()[: len(base_record())] == base_record() + + +def test_the_registry_matches_the_record_at_release_20261111(): + """Release 20261111's record: 2448 entries, its note naming the last + block's 1578, and the blocks the registry gives.""" + assert len(base_record()) == 2448 + note = json.loads(git_bytes(COMMIT_20261111, wa.RECORD_PATH))["note"] + assert "The last 1578 (after the first 870)" in note + assert [r.amendments for r in RELEASES_TO_20261111] == [ + 394, 0, 0, 462, 14, 0, 1578, 0, + ] # fmt: skip + + +def test_a_provenance_file_that_moved_is_refused(tmp_path): + """MOCK edit: one changed byte in a listed provenance file fails its pin, + so editing a release's re-judged cases cannot retire an amendment.""" + release = wa.RELEASES[4] + path = tmp_path / release.judge_provenance + path.parent.mkdir(parents=True) + path.write_bytes((ROOT / release.judge_provenance).read_bytes() + b"\n") + with pytest.raises(wa.WordingAmendmentError, match="pins"): + wa.rejudged_cases(tmp_path, [release]) + + +def test_only_the_three_releases_publish_without_the_14(): + """Closed list: a later release cannot join it to pass the invariant + with the 14 still dropped.""" + assert wa.PUBLISHED_WITHOUT_THE_14 == ( + "dashboard-data-20261014", + "dashboard-data-20261027", + TAG_20261111, + ) + assert wa.known_dropped("dashboard-data-20261209") == () + assert wa.known_dropped(TAG_20261111) == wa.DROPPED_BY_20261014 + + +# --- The invariant --------------------------------------------------------------- + + +def test_the_committed_files_publish_every_amendment_in_force(): + """Every amendment in force is published by the committed row + annotations, case note bodies, adjudication record and adjudication + sentences, but for the entries known_dropped names for the release the + pointer names: the 14 while that is dashboard-data-20261111, none after + it. A release that drops a committed amendment on a kept case or a + decision's reasoning, or does not restore the 14, fails here.""" + found = wa.dropped_amendments( + record(), wa.committed_source(), superseded=superseded() + ) + assert [index for index, _ in found] == list(wa.known_dropped(wa.RELEASES[-1].tag)) + assert {state for _, state in found} <= {wa.REVERTED} + + +def test_the_committed_snapshot_publishes_every_amendment_in_force(): + """The same for the committed snapshot's cells, which the dashboard + payload publishes: a row annotation is its model's cell's annotation, a + case note every cell's caseAnnotation body, a decision's reasoning every + cell's adjudication sentence.""" + found = wa.dropped_amendments( + record(), + wa.payload_source(json.loads(snapshot_text())), + superseded=superseded(), + ) + assert [index for index, _ in found] == list(wa.known_dropped(wa.RELEASES[-1].tag)) + + +def test_release_20261111_published_everything_in_force_but_the_14(): + """At its board commit: 456 amendments in force (439 row and note, all + 17 reasoning), every one published but the 14, in the files and in the + snapshot.""" + in_force = [i for i, s in enumerate(base_superseded()) if s is None] + assert len(in_force) == 456 + reasoning = [i for i, e in enumerate(base_record()) if e["field"] == "reasoning"] + assert len(reasoning) == 17 and set(reasoning) <= set(in_force) + files = wa.frame_source(*base_frames(), base_adjudications()) + cells = wa.payload_source(base_snapshot()) + for source in (files, cells): + assert base_dropped(source) == [ + (i, wa.REVERTED) for i in wa.DROPPED_BY_20261014 + ] + + +def test_the_14_are_release_20261013bs_block_on_five_cases(): + """The pinned 14 are the whole block release 20261013b appended, on the + five cases, four case notes and six rows, none of them re-judged by + release 20261111.""" + tags = wa.entry_releases(base_record(), RELEASES_TO_20261111) + block = [i for i, tag in enumerate(tags) if tag == "dashboard-data-20261013b"] + assert tuple(block) == wa.DROPPED_BY_20261014 + assert Counter(e["case_id"] for e in the_14()) == FIVE_CASES + assert Counter(t[1] for t in targets(the_14())) == { + "case_annotation": 4, + "annotation": 6, + } + assert all(base_superseded()[i] is None for i in block) + + +def test_the_pin_refuses_an_edited_record(): + """MOCK edit: one changed character in one of the 14 entries fails the + pin, so an edit to the record cannot change what the restoration + applies.""" + edited = [dict(e) for e in base_record()] + edited[860]["new"] = edited[860]["new"] + " MOCK" + with pytest.raises(wa.WordingAmendmentError, match="pinned"): + wa.dropped_by_20261014(edited) + + +# --- The restoration, on release 20261111's committed data --------------------------- + + +def test_the_restoration_gives_back_release_20261013bs_text(): + """Restoring the 14 on release 20261111's files gives each of the 10 + targets the text release 20261013b committed, byte for byte, and changes + no other row, note or column.""" + before = base_frames() + after = restored_frames() + published = read_frames( + *( + git_bytes(COMMIT_20261013B, path).decode("utf-8") + for path in (wa.ROW_ANNOTATIONS_PATH, wa.CASE_NOTES_PATH) + ) + ) + want = targets(the_14()) + for frame_before, frame_after, frame_then, column, with_model in zip( + before, + after, + published, + ("annotation", "case_annotation"), + (True, False), + strict=True, + ): + assert list(frame_after.columns) == list(frame_before.columns) + changed = frame_after[column] != frame_before[column] + assert frame_after.drop(columns=column).equals( + frame_before.drop(columns=column) + ) + keys = ["country", "scenario_id", "variable"] + ( + ["model"] if with_model else [] + ) + moved = { + ("__".join(k[:3]), column, k[3] if with_model else None) + for k in frame_after.loc[changed, keys].itertuples(index=False) + } + assert moved == {t for t in want if t[1] == column} + then = { + tuple(k): text + for *k, text in frame_then[[*keys, column]].itertuples(index=False) + } + for *k, text in frame_after.loc[changed, [*keys, column]].itertuples( + index=False + ): + assert text == then[tuple(k)], k + + +def test_restore_csv_texts_writes_the_files_as_committed(): + """Read and written back with nothing restored, both files are their + committed bytes, so the restored text differs from them only where the + 14 restore.""" + rows, notes, restored, _ = wa.restore_csv_texts(*base_text(), []) + assert (rows, notes) == base_text() and restored == [] + + +def test_the_restored_files_publish_every_amendment_in_force(): + files = wa.frame_source(*restored_frames(), base_adjudications()) + assert base_dropped(files) == [] + + +def test_the_restored_payload_publishes_every_amendment_in_force(): + """restore_payload rewrites the 10 targets' cells and nothing else: the + changed cells are the row targets' models and every cell carrying a + restored case note, each with only its annotation field changed and its + keys in order, every other cell serialized as before, the input payload + unchanged, and each restored field release 20261013b's.""" + payload = {"countries": {"us": base_snapshot()}} + out, restored, skipped = wa.restore_payload(payload, the_14()) + assert len(restored) == 14 and skipped == [] + assert json.dumps(payload["countries"]["us"]) == json.dumps( + json.loads(base_snapshot_text()) + ) + assert base_dropped(wa.payload_source(out)) == [] + before = payload["countries"]["us"]["scenarioPredictions"] + after = out["countries"]["us"]["scenarioPredictions"] + then = json.loads(gzip.decompress(git_bytes(COMMIT_20261013B, SNAPSHOT_PATH)))[ + "scenarioPredictions" + ] + want: set[tuple] = set() + for case, field, model in targets(the_14()): + _, scenario, variable = case.split("__") + cells = before[scenario][variable] + if field == "annotation": + want.add((scenario, variable, model, "annotation")) + else: + want |= { + (scenario, variable, m, "caseAnnotation") + for m, c in cells.items() + if "caseAnnotation" in c + } + moved = set() + for scenario, variables in after.items(): + for variable, cells in variables.items(): + for model, cell in cells.items(): + old = before[scenario][variable][model] + if json.dumps(cell) == json.dumps(old): + continue + assert list(cell) == list(old) + moved |= { + (scenario, variable, model, k) for k in cell if cell[k] != old[k] + } + assert moved == want and len(moved) == RESTORED_CELL_FIELDS + assert len({m[:3] for m in moved}) == RESTORED_CELLS + for scenario, variable, model, field in moved: + assert ( + after[scenario][variable][model][field] + == (then[scenario][variable][model][field]) + ) + + +def test_a_reopened_case_is_skipped(): + """A case the release judged again keeps its text: the new verdict's + text replaces what the entry corrected.""" + snap = "us__scenario_045__snap" + rows, notes, restored, skipped = wa.restore_frames( + *base_frames(), the_14(), reopened=frozenset({snap}) + ) + assert [e["case_id"] for e in skipped] == [snap] and len(restored) == 13 + assert (rows.annotation != base_frames()[0].annotation).sum() == 5 + out, restored, skipped = wa.restore_payload( + {"countries": {"us": base_snapshot()}}, the_14(), reopened=frozenset({snap}) + ) + assert [e["case_id"] for e in skipped] == [snap] and len(restored) == 13 + + +# --- A dropped amendment is caught, whichever it is ---------------------------------- + + +def undo(text: str, entries) -> str: + """``text`` with ``entries`` undone, last first, each new text back to + its old once: the text a rebuild from before them would publish.""" + for entry in reversed(list(entries)): + assert entry["new"] in text, entry + text = text.replace(entry["new"], entry["old"], 1) + return text + + +@functools.cache +def droppable() -> tuple[int, ...]: + """In-force row and note amendments no later entry rewrites, whose new + text the restored files hold once and whose old text they do not, so + putting the old text back gives it exactly once.""" + source = wa.frame_source(*restored_frames()) + later = wa.later_same_target(base_record()) + out = [] + for index, entry in enumerate(base_record()): + if ( + base_superseded()[index] is not None + or later[index] + or entry["field"] == "reasoning" + ): + continue + (text,) = source(entry) + if text.count(entry["new"]) == 1 and entry["old"] not in text: + if text.replace(entry["new"], entry["old"]).count(entry["old"]) == 1: + out.append(index) + return tuple(out) + + +def test_most_amendments_in_force_are_droppable(): + """The property below draws from most of the 439 row and note + amendments in force, ten of the 14 among them.""" + assert len(droppable()) >= 400 + assert len(set(droppable()) & set(wa.DROPPED_BY_20261014)) == 10 + + +@settings( + max_examples=60, + deadline=None, + suppress_health_check=[HealthCheck.too_slow], +) +@given(st.data()) +def test_dropping_any_amendment_in_force_is_caught_and_restorable(data): + """Put back one in-force amendment's old text in the restored files, as + release 20261014 did to the 14 (in a case note, in its body: the + adjudication sentence is the decision's text, which may also hold the new + wording, as entry 2398's case's does): dropped_amendments names it, and + restore_frames with that entry gives back the restored files exactly.""" + index = data.draw(st.sampled_from(droppable()), label="entry") + entry = base_record()[index] + rows, notes = restored_frames() + frame = rows if entry["field"] == "annotation" else notes + case = entry["case_id"].split("__") + mask = ( + (frame.country == case[0]) + & (frame.scenario_id == case[1]) + & (frame.variable == case[2]) + ) + if entry["field"] == "annotation": + mask &= frame.model == entry["model"] + (at,) = frame.index[mask] + body, sentence = wa.split_note(frame.loc[at, entry["field"]]) + if entry["field"] == "annotation": + body, sentence = frame.loc[at, entry["field"]], "" + frame.loc[at, entry["field"]] = body.replace(entry["new"], entry["old"]) + sentence + found = dict(base_dropped(wa.frame_source(rows, notes, base_adjudications()))) + assert found.get(index) == wa.REVERTED + back_rows, back_notes, restored, _ = wa.restore_frames(rows, notes, [entry]) + assert restored == [entry] + assert (back_rows.to_csv(index=False), back_notes.to_csv(index=False)) == ( + restored_text() + ) + + +def test_rebuilding_any_target_from_before_its_amendments_is_caught(): + """Every in-force row and note target, its whole chain of amendments + undone (what a rebuild from the pre-amendment verdict publishes), flags + at least one of its entries, chained targets and entry 2398 (whose new + text the case's adjudication sentence also holds) included.""" + rows, notes = restored_frames() + source = wa.frame_source(rows, notes, base_adjudications()) + record = base_record() + later = wa.later_same_target(record) + chains: dict[tuple, list[int]] = {} + for index, entry in enumerate(record): + if base_superseded()[index] is None and entry["field"] != "reasoning": + chains.setdefault(wa.target(entry), []).append(index) + assert len(chains) == 414 + for key, chain in chains.items(): + (text,) = source(record[chain[0]]) + reverted = undo(text, [record[i] for i in chain]) + states = [wa.entry_state(reverted, record[i], later[i]) for i in chain] + assert any(s != wa.APPLIED for s in states), (key, states) + assert 2398 in chains[wa.target(record[2398])] + + +def test_dropping_one_amendment_inside_a_chain_is_caught(): + """An in-force amendment that later entries of its target rewrite, + dropped alone (its new text back to its old, the later entries kept), is + flagged. That is the path where entry_state undoes the later entries + first. Some such drops cannot be built, because a later entry rewrites + words inside this entry's new text; the rest are all caught.""" + record = base_record() + later = wa.later_same_target(record) + source = wa.frame_source(*restored_frames(), base_adjudications()) + built: list[int] = [] + unbuildable: list[int] = [] + for index, entry in enumerate(record): + if base_superseded()[index] is not None or not later[index]: + continue + text = source(entry)[0] + dropped = undo(text, later[index]).replace(entry["new"], entry["old"], 1) + for after in later[index]: + if after["old"] not in dropped: + unbuildable.append(index) + break + dropped = dropped.replace(after["old"], after["new"], 1) + else: + built.append(index) + state = wa.entry_state(dropped, entry, later[index]) + assert state != wa.APPLIED, (index, state) + assert (len(built), len(unbuildable)) == (BUILT_INSIDE, UNBUILDABLE_INSIDE) + + +@pytest.mark.parametrize("where", ["record", "sentence"]) +def test_reverting_any_decisions_reasoning_is_caught(where): + """The 17 reasoning amendments correct 10 decisions. Undoing each + decision's chain in the adjudication record (or only in the case note's + adjudication sentence that restates it) flags every amendment in the + chain: a re-judge does not retire a decision's reasoning.""" + rows, notes = base_frames() + record = base_record() + later = wa.later_same_target(record) + chains: dict[tuple, list[int]] = {} + for index, entry in enumerate(record): + if entry["field"] == "reasoning": + chains.setdefault(wa.target(entry), []).append(index) + assert sum(map(len, chains.values())) == 17 and len(chains) == 10 + for (case, _, _), chain in chains.items(): + _, scenario, variable = case.split("__") + decisions = [dict(e) for e in base_adjudications()] + edited = notes.copy() + if where == "record": + (decision,) = [ + d + for d in decisions + if (d["scenario_id"], d["variable"]) == (scenario, variable) + ] + decision["reasoning"] = undo( + decision["reasoning"], [record[i] for i in chain] + ) + else: + mask = (edited.scenario_id == scenario) & (edited.variable == variable) + (at,) = edited.index[mask] + body, sentence = wa.split_note(edited.loc[at, "case_annotation"]) + edited.loc[at, "case_annotation"] = body + undo( + sentence, [record[i] for i in chain] + ) + found = dict(base_dropped(wa.frame_source(rows, edited, decisions))) + assert all(i in found for i in chain), (case, where, chain, found) + assert later[chain[0]] == [record[i] for i in chain[1:]] + + +# --- Refusals and states, on MOCK text ------------------------------------------------ + +MOCK_ENTRY = { + "case_id": "us__scenario_mock__mock_output", + "field": "annotation", + "model": "mock-model", + "old": "MOCK old wording", + "new": "MOCK new wording", + "reason": "MOCK", +} +MOCK_SENTENCE = ( + " Developer adjudication (2026-01-01): the judge (mock-judge) returned " + "llm_error; adjudicated reference_engine_defect (mock). MOCK old wording." +) + + +def mock_frames(row_text: str, note_text: str = "MOCK note"): + rows = pd.DataFrame( + { + "country": ["us", "us"], + "scenario_id": ["scenario_mock", "scenario_mock"], + "variable": ["mock_output", "mock_output"], + "model": ["mock-model", "other-model"], + "annotation": [row_text, "MOCK old wording elsewhere"], + } + ) + notes = pd.DataFrame( + { + "country": ["us"], + "scenario_id": ["scenario_mock"], + "variable": ["mock_output"], + "case_annotation": [note_text], + } + ) + return rows, notes + + +def test_restore_frames_changes_only_its_row(): + rows, notes = mock_frames("A MOCK old wording here.") + out_rows, out_notes, restored, _ = wa.restore_frames(rows, notes, [MOCK_ENTRY]) + assert out_rows.annotation.tolist() == [ + "A MOCK new wording here.", + "MOCK old wording elsewhere", + ] + assert rows.annotation[0] == "A MOCK old wording here." + assert out_notes.equals(notes) and restored == [MOCK_ENTRY] + + +def test_a_case_note_is_restored_in_its_body_and_keeps_its_sentence(): + """MOCK note whose adjudication sentence also holds the old text: the + body is restored, the sentence (the decision's text) is not touched.""" + note = {k: v for k, v in MOCK_ENTRY.items() if k != "model"} + note["field"] = "case_annotation" + rows, notes = mock_frames("x", "Body: MOCK old wording." + MOCK_SENTENCE) + _, out_notes, _, _ = wa.restore_frames(rows, notes, [note]) + assert out_notes.case_annotation[0] == "Body: MOCK new wording." + MOCK_SENTENCE + source = wa.frame_source(*mock_frames("x", out_notes.case_annotation[0])) + assert wa.entry_state(source(note)[0], note) == wa.APPLIED + + +@pytest.mark.parametrize( + "text, message", + [ + ("No such wording.", "occurs 0 times"), + ("MOCK old wording, MOCK old wording.", "occurs 2 times"), + ("MOCK old wording, then MOCK new wording.", "already holds"), + ], +) +def test_restore_frames_refuses_text_it_cannot_amend_exactly_once(text, message): + rows, notes = mock_frames(text) + with pytest.raises(wa.WordingAmendmentError, match=message): + wa.restore_frames(rows, notes, [MOCK_ENTRY]) + + +def test_restore_frames_refuses_a_missing_or_doubled_row_and_a_reasoning_entry(): + rows, notes = mock_frames("MOCK old wording") + with pytest.raises(wa.WordingAmendmentError, match="0 rows"): + wa.restore_frames(rows, notes, [{**MOCK_ENTRY, "model": "absent-model"}]) + doubled = pd.concat([rows.iloc[[0]], rows], ignore_index=True) + with pytest.raises(wa.WordingAmendmentError, match="2 rows"): + wa.restore_frames(doubled, notes, [MOCK_ENTRY]) + reasoning = {k: v for k, v in MOCK_ENTRY.items() if k != "model"} + with pytest.raises(wa.WordingAmendmentError, match="only a row annotation"): + wa.restore_frames(rows, notes, [{**reasoning, "field": "reasoning"}]) + + +def test_restore_payload_refuses_a_case_without_cells(): + payload = {"scenarioPredictions": {"scenario_mock": {}}} + with pytest.raises(wa.WordingAmendmentError, match="no cells"): + wa.restore_payload(payload, [MOCK_ENTRY]) + payload = { + "scenarioPredictions": { + "scenario_mock": {"mock_output": {"mock-model": {"score": 0}}} + } + } + with pytest.raises(wa.WordingAmendmentError, match="no cell carries"): + wa.restore_payload(payload, [MOCK_ENTRY]) + + +@pytest.mark.parametrize( + "text, state", + [ + ("MOCK new wording.", wa.APPLIED), + ("MOCK old wording.", wa.REVERTED), + ("MOCK old wording; MOCK new wording.", wa.BOTH), + ("Something else.", wa.NEITHER), + (None, wa.MISSING), + ], +) +def test_entry_state(text, state): + assert wa.entry_state(text, MOCK_ENTRY) == state + + +def test_entry_state_and_restore_text_when_the_new_text_cuts_words(): + """MOCK cut, as entry 1275 cuts "exactly 12% × $9,629 = " from its old + text: the old text holds the new, so a reverted text holds the new text + only inside the old, and is REVERTED, not APPLIED; restore_text amends + it, and refuses a text holding the new text outside the old.""" + cut = {**MOCK_ENTRY, "old": "exactly MOCK $1.00", "new": "MOCK $1.00"} + assert wa.entry_state("Paid MOCK $1.00.", cut) == wa.APPLIED + assert wa.entry_state("Paid exactly MOCK $1.00.", cut) == wa.REVERTED + assert wa.entry_state("Paid exactly MOCK $1.00, MOCK $1.00.", cut) == wa.BOTH + assert wa.restore_text("Paid exactly MOCK $1.00.", [cut], "MOCK") == ( + "Paid MOCK $1.00." + ) + with pytest.raises(wa.WordingAmendmentError, match="already holds"): + wa.restore_text("Paid exactly MOCK $1.00, MOCK $1.00.", [cut], "MOCK") + + +def test_entry_state_undoes_later_rewrites_of_the_new_text_first(): + """MOCK chain: a later entry rewrote part of this entry's new text, so + the published text holds neither entry's new text whole; undoing the + later one shows this one applied.""" + later = {**MOCK_ENTRY, "old": "new wording", "new": "newer wording"} + assert wa.entry_state("MOCK newer wording.", MOCK_ENTRY) == wa.NEITHER + assert wa.entry_state("MOCK newer wording.", MOCK_ENTRY, [later]) == wa.APPLIED + assert wa.entry_state("MOCK old wording.", MOCK_ENTRY, [later]) == wa.REVERTED + + +def test_a_reasoning_entry_reads_the_record_and_the_sentence(): + """MOCK decision: a reasoning entry is published only when both the + adjudication record and the case note's sentence hold its new text; a + note without a sentence leaves it MISSING.""" + entry = {k: v for k, v in MOCK_ENTRY.items() if k != "model"} + entry["field"] = "reasoning" + decision = [{"scenario_id": "scenario_mock", "variable": "mock_output"}] + new_sentence = MOCK_SENTENCE.replace("old", "new") + for reasoning, note, states in [ + ("MOCK new wording.", "Body." + new_sentence, [wa.APPLIED, wa.APPLIED]), + ("MOCK new wording.", "Body." + MOCK_SENTENCE, [wa.APPLIED, wa.REVERTED]), + ("MOCK old wording.", "Body." + new_sentence, [wa.REVERTED, wa.APPLIED]), + ("MOCK new wording.", "Body.", [wa.APPLIED, wa.MISSING]), + ]: + source = wa.frame_source( + *mock_frames("x", note), [{**decision[0], "reasoning": reasoning}] + ) + assert [wa.entry_state(t, entry) for t in source(entry)] == states + + +def test_entry_releases_refuses_an_unlisted_block(): + with pytest.raises(wa.WordingAmendmentError, match="list the release"): + wa.entry_releases([*base_record(), MOCK_ENTRY], RELEASES_TO_20261111) + + +# --- The Fable 5.2 driver's carry and gates, with the restoration -------------------- + + +@pytest.fixture(scope="module") +def driver(): + """The Fable 5.2 driver, imported as its own tests import it (it imports + release_20261006 from scripts/ when a gate runs).""" + if str(ROOT / "scripts") not in sys.path: + sys.path.insert(0, str(ROOT / "scripts")) + import finish_fable52 + + return finish_fable52 + + +@pytest.fixture +def decisions(): + data = json.loads(git_bytes(COMMIT_20261111, wa.ADJUDICATIONS_PATH)) + return parse_adjudications(data, wa.ADJUDICATIONS_PATH) + + +def serve_base(monkeypatch, driver, frames): + """The driver's base_annotation_frames, serving ``frames``: the next + release's base, release 20261111's committed files, with or without the + restoration.""" + monkeypatch.setattr( + driver, "base_annotation_frames", lambda: tuple(f.copy() for f in frames) + ) + + +def build(driver, decisions): + """The frames triage builds when every case is kept: collect_audit's + output stands in as release 20261111's files themselves, since the carry + replaces each kept row's and note's text with the base's.""" + rows, notes = base_frames() + collected = { + "row": rows, + "case": notes.rename( + columns={ + "case_failure_sources": "case_failure_source", + "case_failure_subtypes": "case_failure_subtype", + } + ), + } + return driver.annotation_frames(collected, frozenset(), decisions, []) + + +def test_the_carry_publishes_the_restoration_and_the_kept_gate_holds_it( + monkeypatch, driver, decisions +): + """With the restoration in the base the next release's driver carries + (base_annotation_frames), triage's frames are the restored files, and + the kept-case gate passes them. A release that carries the base without + the restoration publishes the old text, and the gate, holding the + restored base, names each of the 10 targets.""" + serve_base(monkeypatch, driver, restored_frames()) + built = build(driver, decisions) + assert driver.kept_annotation_problems(*built, frozenset(), decisions) == [] + assert tuple(driver.annotation_csv_text(f) for f in built) == restored_text() + + serve_base(monkeypatch, driver, base_frames()) + unrestored = build(driver, decisions) + assert tuple(driver.annotation_csv_text(f) for f in unrestored) == base_text() + serve_base(monkeypatch, driver, restored_frames()) + problems = driver.kept_annotation_problems( + *unrestored, frozenset(), decisions, limit=100 + ) + want = { + f"{case} {model} annotation" + if field == "annotation" + else f"{case} case note case_annotation" + for case, field, model in targets(the_14()) + } + assert sorted(problems) == sorted(want) + + +def test_check_a_holds_the_export_to_the_restored_base_payload(driver): + """The driver's check (a) compares the scope export's cells with the + base payload's. Against restore_payload's base, an export built apart + that carries the restoration passes, one missing a single restored row + fails on that row's cell only, and one carrying none of it fails on all + 18 cells; so the next release passes restore_payload(live) as the base + it compares.""" + us = base_snapshot() + incumbents = {row["model"] for row in us["modelStats"]} + five = {(c.split("__")[1], c.split("__")[2]) for c in FIVE_CASES} + + def trimmed() -> dict: + predictions = json.loads(base_snapshot_text())["scenarioPredictions"] + return { + "countries": { + "us": { + "scenarioPredictions": { + scenario: { + variable: cells + for variable, cells in variables.items() + if (scenario, variable) in five + } + for scenario, variables in predictions.items() + if any(s == scenario for s, _ in five) + } + } + } + } + + base, _, _ = wa.restore_payload(trimmed(), the_14()) + export, _, _ = wa.restore_payload(trimmed(), the_14()) + assert driver.base_restoration_problems(export, base, incumbents) == [] + snap_row = next(e for e in the_14() if e["case_id"] == "us__scenario_045__snap") + short, _, _ = wa.restore_payload( + trimmed(), [e for e in the_14() if e is not snap_row] + ) + assert driver.base_restoration_problems(short, base, incumbents, limit=100) == [ + f"scenarioPredictions scenario_045 snap {snap_row['model']} changed" + ] + problems = driver.base_restoration_problems(trimmed(), base, incumbents, limit=100) + assert len(problems) == RESTORED_CELLS + assert all(p.startswith("scenarioPredictions ") for p in problems)