diff --git a/AGENTS.md b/AGENTS.md index f43d8b86c..6951f6c53 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -328,7 +328,7 @@ The 2.0 rewrite landed as underscore-private modules beside the v1 code, which 2 **Measuring a change to the group suggester: use `tools/differential/suggest_measure.py`.** Run it after any change to `nameparser/_suggest.py`, to `nameparser/config/_order_names.py` (or `tools/vocab/order_names.py`, which writes it) or to a predicate a signal reads (the capitals, particle and patronymic tests, and the title, suffix and numeral tests a name is read past), or to rules/O9, whose reading the `capitals_as_family` vote asks of the parse itself: `suggest` moves no parse, so the snapshot and every corpus check report nothing. It draws groups of known order, 2, 3, 4, 5, 10, 20, 50 and 200 names by default (a change to a threshold adds `--sizes 2,3,4,5,10,20,50,100,200,500,1000,2000`: a share counted among the names that vote holds at 200 names and fails past it, which no default size shows, and #1442's two stray votes decided lists of 500 and more for that reason), from the local corpora and reports the share of groups read right by size, the same-order rows being the anti-goal (at least 95% at every size, save `orcid-givcaps`' two same-order rows, a list writing its given names in capitals (`ANNA Smith`), which the capitals signal reads the wrong way round by design (decisions/group-suggestion, 2026-11-12 CAPITALS), and `orcid-byline-joined`'s given-first row at 50 and 100 names, and at 200 until #1357, a list of nothing but `AM Hoy` bylines that the few names the name tables vote on decide (decisions/group-suggestion, 2026-11-14 #1355, which took `orcid-byline`'s own row off this list, as #1397 took `orcid-famcaps-short`'s); groups of 2 to 4 are where #1308's final review found a patronymic rule forcing given-first on a family-first base); `--set NAME=VALUE` overrides a threshold, and `--set _MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000 --set _MIN_RUN_NAMES=1000000` decides nothing and is the harness proof (the order count alone leaves the patronymic rule free to decide its own given-first order, and the two vote counts leave the letters setting free to decide; `_MIN_VOTES` also holds `capitals_as_family`, whose table `--set _MIN_CAPITALS_LETTERS=1000000` empties alone). A table change also moves the `print(suggestion)` evidence docs/getting-started.rst and docs/suggest.rst show as doctests, which `uv run pytest` does not run: run `uv run sphinx-build -b doctest docs ` too (#1374's ORCID table made `Wang Xiaoming` a given-name vote and failed every build job). Its figures are quoted in `Parser.suggest`'s docstring, docs/suggest.rst and docs/design/decisions/group-suggestion.md; re-take all three when they move (decisions/group-suggestion's THRESHOLDS entry names the command, and its latest dated entry carrying a re-taken table, 2026-11-15 #1357's, holds the table the other two round; the 2026-11-12 CAPITALS entry holds the `capitals_as_family` table, which the docstring's and docs/suggest.rst's capitals sentences round). A signal that reads one of the pipeline's predicates must read it exactly where the pipeline's rule does, no wider and no narrower, and its tests need a row at each edge: #1310's patronymic signal first voted an `-ovich` ending on any word (wider: two-word `Abramovich Roman` decided East Slavic and forced given-first), then its fix refused one on the first word, which rules/O1 never asks about (narrower: `Abramovich Roman Arkadyevich`, which the rule reads right, cast nothing). Only the second review caught the narrowing. A signal that votes where exactly ONE end of a name is listed votes by the other end alone once one end is no longer read: #1355's first sketch stopped looking up a short capitals word opening a name, and `WU Zhi` then cast a given-first surname vote by `Zhi`, so the shipped rule silences the signal on the whole name; when a rule stops reading a word, put a name whose other word is listed too in its grid. And a rule keyed to a word's shape needs a population of nothing but that shape: the default populations mix short capitals surnames with long ones, so the ending word's twin of that defect (`Zhi LI`) went unseen from #1308 until #1355 cut `orcid-famcaps-short`, and #1397 fixed it (decisions/group-suggestion, 2026-11-14 #1355 and #1397). A setting has more than one effect, and a suggestion that leaves something out leaves it out on every base: #1356 was first decided on "the East Slavic rule stands down under a family-first order", true of its reordering and false of its `patronymic` view, and PR #1399 as first pushed then kept every family-first base's order. Five names written `Zzyvan Petrovich Qqsidorov` under `FAMILY_FIRST` were read family `Zzyvan` where master moved the base and read them right; and `SIDOROV Ivan Petrovich` five times under `FAMILY_FIRST_GIVEN_LAST` lost the rule, though `capitals_as_family`, suggested in the same patch, makes the rule name the patronymic there. Review found both; the tool's table was identical with and without them, its populations then holding neither shape and no `FAMILY_FIRST_GIVEN_LAST` base anywhere in it (it has read the parliament lists under one since, which catches the second kind on a real list; its draws still run under two bases). Before deciding what a suggestion leaves out, sweep every base order × every switch the same patch can turn on × both written positions of the word the rule reads, and compare whole names read right (given and family), not the family alone: `FAMILY_FIRST_GIVEN_LAST` reads the family of `Sidorov Ivan Petrovich` right and its given name wrong, which a family count scored as nothing to fix. One signal is wider on purpose, and says so where it is decided: the letters signal (#1254) counts a run joined with full stops (`B.K.`), which rules/O8 never moves, beside the spaced runs it does, since three quarters of Nepal's runs are written joined (decisions/group-suggestion, 2026-11-11 LETTER RUNS); a test holds every other run to the rule exactly. -**Validating a new parsing rule** — before implementing, simulate it in a throwaway script against `TEST_NAMES` (plus a few target-language examples) to catch regressions/false-positives early. E.g. this surfaced the `last_base` `do`/`st`/`mc` empties and the patronymic `"David Michael Abramovich"` false-reorder. After the change, `tests/v2/test_snapshot.py` lists every corpus name it moved, grouped by changed field -- read them, and re-record with `uv run python tools/differential/snapshot.py --record` once every move is intended, so the PR diff of `snapshot.jsonl` shows the reviewer the same list. `uv run python tools/differential/cldr_agreement.py` reports how the tree's agreement with CLDR's stated name fields moved; `tests/v2/test_cldr_agreement.py` fails on any move, and `tools/differential/cldr_agreement.json` doubles as a measured list of names the parser and CLDR read differently. The same command and test score the GND corpus's real names (`gnd_fields.jsonl`, record `gnd_agreement.json`) by the same rules, and `--record` rewrites every record, printing per source what it accepts. A locale-pack change reads the second view the same command prints, per pack (`cldr_agreement_locales.json`, #672, and `wikidata_native_agreement_locales.json` for real Han and kana names); its `JA` rows run only with the `ja` extra installed. A change to Han, Hangul or kana order or to Korean segmentation reads `wikidata_native_agreement.json` too: the only real names in those scripts the corpora hold. It holds no honorific, so a change to the honorific peel moves nothing there. A change to comma or credential handling also reads the local corpus of hand-typed names (`snapshot.py --local ctgov-officials --base `, which reads the base from a baseline kept for its package's files and never the shared snapshot beside the corpus (a base read once from the same fetch is copied rather than parsed again; `--sample N` reads a fixed sample while iterating; the shared snapshot beside the corpus is one file per source for every worktree, and #752's phase 2f found ctgov reporting a sibling branch's 1,334 joined-credential readings as its own moves against it); tools/differential/README.md's "Local corpora"): the one population of names nobody chose for a test or a catalog, so it shows how often each shape is typed, and the one no CI run sees. A change to title handling reads `ukec-individuals` the same way: UK donors' names in spoken order and mixed case, in 8,219 of whose 15,214 `parse()` read a title on 2026-10-22. A change to English titles, honorifics or post-nominals also reads `snapshot.py --local govuk-people` the same way: GOV.UK's display names of ministers, officials and officers, the title run and the post-nominals as an office writes them (`The Rt Hon`, `Sir`, `Baroness`, ranks; `KC`, `CBE`, `KCB`), in 2,093 of whose 6,021 `parse()` read one or both on 2026-10-30. A change to Spanish titles, to the `es` pack, or to how a title marks where a name starts after an office reads `snapshot.py --local dof-signatures` the same way: the names in the signature blocks of Mexico's Diario Oficial for 2025, cut from the clause that names the signatory's office, 65.4% of its 33,565 signatures opening with a title (`Lic.`, `Dr.`, `Mtro.`, `C.`, `Licenciada`, `C.P.`), whose first word `parse()` read as a title in 82.1% and `parser_for(locales.ES)` in 86.8% on 2026-10-31. A change to particles or generational words reads `snapshot.py --local tse-donors` the same way, Brazilian names in spoken order dense with both. A change to initials, to a title word outside English, or to how a script's combining marks are read reads `snapshot.py --local nepal-candidates` the same way: Nepal's local election candidates, each a romanized name (surnames written as initials, `B.K.`, `K.C.`; honorific titles such as `Guru` in front, `Shekh`, a title there until #752's phase 2j made it one only inside a title phrase, and `Md.`, a title by its period's shape until #1383 made it Muhammad written short, the given name) beside the same name in Devanagari, written with vowel signs and the virama, combining marks the letter-shape tests do not count as letters (decisions/nfd-shapes), and with the joiners ZWJ and ZWNJ. It is the only large population of South Asian names the corpora hold, and its corpus reads both scripts. A change to non-Latin scripts or to Arabic-script names reads `snapshot.py --local jrc-names` the same way, and `local_corpora.py groups jrc-names`: the spellings of one person across scripts and transliterations, harvested from news text, with 17,074 Arabic-script spellings where the committed corpora hold 315 distinct names with an Arabic letter, 96 of them CLDR's fictional renderings (2026-10-24), and under a licence that keeps even a reading of one of its names in the cache. A change to patronymics, to Turkic or East Slavic names, to Indic titles and initials, or to Slavic or Portuguese double surnames reads `snapshot.py --local opensanctions-parliaments --base ` the same way, and `local_corpora.py groups opensanctions-parliaments`: the members of twenty-three national chambers as each parliament writes them (Azerbaijan, the Central Asian chambers, Turkey, Croatia, Slovenia, Slovakia, Portugal, India, Ukraine, Belarus, Russia, Indonesia, Ethiopia, South Korea, Israel, Mongolia) and Indonesia's 2018 regional heads, read through OpenSanctions, 24,302 spellings of 19,283 members on 2026-11-12 (24,084 of 19,216 on 2026-11-08, before the Khural and other lists' newer exports), some members' aliases in another script (Kazakh beside Russian Cyrillic, Uzbek Cyrillic beside Latin, Devanagari beside Latin, Hangul and Hanja or Hebrew beside Latin) or with a title (`Shri`, `Smt.`), the population issues #1186 to #1192 were read from, and the one that measures Indonesia's `H.` and `Imam` (#1205, #1206) Ethiopia's father's name (#1203), Korea's Hangul and Hanja (#1213, #1215, #1216) Israel's Hebrew (#1209 to #1211) and Mongolia's Cyrillic, the father's name first (#1237, `mn_parliament`, 126 members, added 2026-11-12); `config_diff.py --group ` keeps one parliament. A change to which field a word lands in also reads `local_agreement.py psc-individuals --base ` the same way: real names with the four boxes their filers typed them into (UK companies' people with significant control), scored field by field and by nationality; and `local_agreement.py orcid-researchers --base `, ORCID holders' own two boxes (given names, family name) from every country, scored by the country they work or live in -- a population each person split for themselves, academic but worldwide, the one to read for a change a language pack makes. Its `name` is COMPOSED from those boxes, given first, so it cannot show which word a writer put first: a count of where a word falls in it is fixed by construction, and #1163's 538 records with the trailing letters in the family box against 0 with the word before them (`Lakshmi R S`, never `R S Lakshmi`) reproduced from that field. Order is measured on the free-text `credit` name (125,960 of the 2026-10-27 fetch's 1,831,533 records, which lean towards bibliographic bylines), against the boxes (decisions/O8); and `local_agreement.py patentsview-inventors --base `, US patents' inventors in the two boxes their filings give, split by a professional filer, with how many people filed under each name in each country, the one to read for how common a name's word is among a country's US-patent inventors. A change to titles or post-nominals, or to the `cs` pack, reads `local_agreement.py cz-candidates --base `, and with `--locale cs` too: Czech election candidates' four boxes (the title before the name, given names, surname, the title after it), scored by election, the only population whose titles are stated apart from the name, 36% of its 170,181 records titled (2026-10-30), nearly all academic degrees; its names are composed from the boxes (`Ing. Jan Novák, Ph.D.`), so it says nothing about how a writer spaces or punctuates them. A change to family-first order, to Vietnamese names or to their titles reads `local_agreement.py uit-vinames --base ` and `local_agreement.py vn-assembly --base `, and with `--locale vi`, `locales.VI` being that pack (#1108): 21,090 distinct names and 499 National Assembly deputies written family name first with their diacritics, whose parts no one filed but the convention derives (first word the family, last the given, the words between the middle name), so they score middle names, which ORCID's two boxes cannot, and `vn-assembly` the `GS.`/`PGS.`/`TS.`/`ThS.` titles composed from the education each deputy states. These are the only real fielded populations outside the committed fields files, and no CI run sees them either. +**Validating a new parsing rule** — before implementing, simulate it in a throwaway script against `TEST_NAMES` (plus a few target-language examples) to catch regressions/false-positives early. E.g. this surfaced the `last_base` `do`/`st`/`mc` empties and the patronymic `"David Michael Abramovich"` false-reorder. After the change, `tests/v2/test_snapshot.py` lists every corpus name it moved, grouped by changed field -- read them, and re-record with `uv run python tools/differential/snapshot.py --record` once every move is intended, so the PR diff of `snapshot.jsonl` shows the reviewer the same list. `uv run python tools/differential/cldr_agreement.py` reports how the tree's agreement with CLDR's stated name fields moved; `tests/v2/test_cldr_agreement.py` fails on any move, and `tools/differential/cldr_agreement.json` doubles as a measured list of names the parser and CLDR read differently. The same command and test score the GND corpus's real names (`gnd_fields.jsonl`, record `gnd_agreement.json`) by the same rules, and `--record` rewrites every record, printing per source what it accepts. A locale-pack change reads the second view the same command prints, per pack (`cldr_agreement_locales.json`, #672, and `wikidata_native_agreement_locales.json` for real Han and kana names); its `JA` rows run only with the `ja` extra installed. A change to Han, Hangul or kana order or to Korean segmentation reads `wikidata_native_agreement.json` too: the only real names in those scripts the corpora hold. It holds no honorific, so a change to the honorific peel moves nothing there. A change to comma or credential handling also reads the local corpus of hand-typed names (`snapshot.py --local ctgov-officials --base `, which reads the base from a baseline kept for its package's files and never the shared snapshot beside the corpus (a base read once from the same fetch is copied rather than parsed again; `--sample N` reads a fixed sample while iterating; the shared snapshot beside the corpus is one file per source for every worktree, and #752's phase 2f found ctgov reporting a sibling branch's 1,334 joined-credential readings as its own moves against it); tools/differential/README.md's "Local corpora"): the one population of names nobody chose for a test or a catalog, so it shows how often each shape is typed, and the one no CI run sees. A change to title handling reads `ukec-individuals` the same way: UK donors' names in spoken order and mixed case, in 8,219 of whose 15,214 `parse()` read a title on 2026-10-22. A change to English titles, honorifics or post-nominals also reads `snapshot.py --local govuk-people` the same way: GOV.UK's display names of ministers, officials and officers, the title run and the post-nominals as an office writes them (`The Rt Hon`, `Sir`, `Baroness`, ranks; `KC`, `CBE`, `KCB`), in 2,093 of whose 6,021 `parse()` read one or both on 2026-10-30. A change to Spanish titles, to the `es` pack, or to how a title marks where a name starts after an office reads `snapshot.py --local dof-signatures` the same way: the names in the signature blocks of Mexico's Diario Oficial for 2025, cut from the clause that names the signatory's office, 65.4% of its 33,565 signatures opening with a title (`Lic.`, `Dr.`, `Mtro.`, `C.`, `Licenciada`, `C.P.`), whose first word `parse()` read as a title in 82.1% and `parser_for(locales.ES)` in 86.8% on 2026-10-31. A change to particles or generational words reads `snapshot.py --local tse-donors` the same way, Brazilian names in spoken order dense with both. A change to initials, to a title word outside English, or to how a script's combining marks are read reads `snapshot.py --local nepal-candidates` the same way: Nepal's local election candidates, each a romanized name (surnames written as initials, `B.K.`, `K.C.`; honorific titles such as `Guru` in front, `Shekh`, a title there until #752's phase 2j made it one only inside a title phrase, and `Md.`, a title by its period's shape until #1383 made it Muhammad written short, the given name) beside the same name in Devanagari, written with vowel signs and the virama, combining marks the letter-shape tests do not count as letters (decisions/nfd-shapes), and with the joiners ZWJ and ZWNJ. It is the only large population of South Asian names the corpora hold, and its corpus reads both scripts. A change to non-Latin scripts or to Arabic-script names reads `snapshot.py --local jrc-names` the same way, and `local_corpora.py groups jrc-names`: the spellings of one person across scripts and transliterations, harvested from news text, with 17,074 Arabic-script spellings where the committed corpora hold 315 distinct names with an Arabic letter, 96 of them CLDR's fictional renderings (2026-10-24), and under a licence that keeps even a reading of one of its names in the cache. A change to patronymics, to Turkic or East Slavic names, to Indic titles and initials, or to Slavic or Portuguese double surnames reads `snapshot.py --local opensanctions-parliaments --base ` the same way, and `local_corpora.py groups opensanctions-parliaments`: the members of twenty-eight national chambers as each parliament writes them (Azerbaijan, the Central Asian chambers, Turkey, Croatia, Slovenia, Slovakia, Portugal, India, Ukraine, Belarus, Russia, Indonesia, Ethiopia, South Korea, Israel, Mongolia, and since 2026-11-19 Malaysia, Pakistan's two chambers, Egypt and Somalia, #1465) and Indonesia's 2018 regional heads, read through OpenSanctions, 26,515 spellings of 20,856 members on 2026-11-19 (24,302 of 19,283 on 2026-11-12, before the five chambers and some other lists' newer exports; 24,084 of 19,216 on 2026-11-08, before the Khural and other lists' newer exports), some members' aliases in another script (Kazakh beside Russian Cyrillic, Uzbek Cyrillic beside Latin, Devanagari beside Latin, Hangul and Hanja or Hebrew beside Latin) or with a title (`Shri`, `Smt.`), the population issues #1186 to #1192 were read from, and the one that measures Indonesia's `H.` and `Imam` (#1205, #1206) Ethiopia's father's name (#1203), Korea's Hangul and Hanja (#1213, #1215, #1216) Israel's Hebrew (#1209 to #1211) and Mongolia's Cyrillic, the father's name first (#1237, `mn_parliament`, 126 members, added 2026-11-12), and Egypt's Arabic-script names, each written short and with the full chain of names (#1072, #1464); `config_diff.py --group ` keeps one parliament. A change to Malay, Indian-Malaysian or Chinese-Malaysian names (`bin`, `binti`, `B.`, `bt`, `a/l`, `a/p`, `anak`, the `@` alias, `MD`, honorifics such as `Ustaz` and `Cikgu` opening a name, a Chinese name written family first) or to names written wholly in capitals reads `snapshot.py --local my-candidates --base ` the same way: Malaysia's election candidates of 2008 to 2023 as their ballots name them, in capitals, 3,077 distinct names on 2026-11-19, grouped by the ethnicity each file states (`config_diff.py --group chinese`), the population issues #1467, #1468, #1164, #1183 and #1179 were read from. A change to which field a word lands in also reads `local_agreement.py psc-individuals --base ` the same way: real names with the four boxes their filers typed them into (UK companies' people with significant control), scored field by field and by nationality; and `local_agreement.py orcid-researchers --base `, ORCID holders' own two boxes (given names, family name) from every country, scored by the country they work or live in -- a population each person split for themselves, academic but worldwide, the one to read for a change a language pack makes. Its `name` is COMPOSED from those boxes, given first, so it cannot show which word a writer put first: a count of where a word falls in it is fixed by construction, and #1163's 538 records with the trailing letters in the family box against 0 with the word before them (`Lakshmi R S`, never `R S Lakshmi`) reproduced from that field. Order is measured on the free-text `credit` name (125,960 of the 2026-10-27 fetch's 1,831,533 records, which lean towards bibliographic bylines), against the boxes (decisions/O8); and `local_agreement.py patentsview-inventors --base `, US patents' inventors in the two boxes their filings give, split by a professional filer, with how many people filed under each name in each country, the one to read for how common a name's word is among a country's US-patent inventors. A change to titles or post-nominals, or to the `cs` pack, reads `local_agreement.py cz-candidates --base `, and with `--locale cs` too: Czech election candidates' four boxes (the title before the name, given names, surname, the title after it), scored by election, the only population whose titles are stated apart from the name, 36% of its 170,181 records titled (2026-10-30), nearly all academic degrees; its names are composed from the boxes (`Ing. Jan Novák, Ph.D.`), so it says nothing about how a writer spaces or punctuates them. A change to family-first order, to Vietnamese names or to their titles reads `local_agreement.py uit-vinames --base ` and `local_agreement.py vn-assembly --base `, and with `--locale vi`, `locales.VI` being that pack (#1108): 21,090 distinct names and 499 National Assembly deputies written family name first with their diacritics, whose parts no one filed but the convention derives (first word the family, last the given, the words between the middle name), so they score middle names, which ORCID's two boxes cannot, and `vn-assembly` the `GS.`/`PGS.`/`TS.`/`ThS.` titles composed from the education each deputy states. These are the only real fielded populations outside the committed fields files, and no CI run sees them either. ## Gotchas diff --git a/tests/v2/test_local_corpora.py b/tests/v2/test_local_corpora.py index 4005eb71d..a156a086f 100644 --- a/tests/v2/test_local_corpora.py +++ b/tests/v2/test_local_corpora.py @@ -54,10 +54,11 @@ # the module holding the name (local_core.RETRIES, local_fec.FEC_MAX_BAD). # A second load by path (load_tool) would be a copy nothing reads. (core, ctgov, fec, tse, tw, ukec, psc, jrc, nepal, orcid, patentsview, volby, dof, uit, - vnassembly, parliaments) = ( + vnassembly, parliaments, mycandidates) = ( importlib.import_module(f"local_{key}") for key in ("core", "ctgov", "fec", "tse", "tw", "ukec", "psc", "jrc", "nepal", "orcid", - "patentsview", "volby", "dof", "uit", "vnassembly", "parliaments")) + "patentsview", "volby", "dof", "uit", "vnassembly", "parliaments", + "mycandidates")) _SOURCE = "ctgov-officials" _DATE = "2026-10-21T09:00:05" @@ -3594,14 +3595,14 @@ def test_no_module_imports_a_sibling_constant() -> None: # module. A `from local_x import CONSTANT` would bind a second name a # patch on local_x cannot reach, and a test could pass with its guard # off. The modules are SOURCES' own, so a new source is covered. PSC, - # JRC, ORCID, PV, VOLBY, DOF, UIT, VN, PARLIAMENTS, CTGOV_OFFICIALS and + # JRC, ORCID, PV, VOLBY, DOF, UIT, VN, PARLIAMENTS, MY, CTGOV_OFFICIALS and # CTGOV_CONTACTS are sources' names, keys of # SOURCES, and no fetch's setting; split is a function, not a setting. import ast sources = {source.fetch.__module__ for source in local.SOURCES.values()} assert sources == {m.__name__ for m in (ctgov, fec, tse, tw, ukec, psc, jrc, nepal, orcid, patentsview, volby, dof, uit, vnassembly, - parliaments) + parliaments, mycandidates) } | {"local_govuk"} siblings = {"local_corpora", "local_core", *sources} imported = {(path.stem, alias.name) @@ -3614,7 +3615,7 @@ def test_no_module_imports_a_sibling_constant() -> None: ("local_corpora", "ORCID"), ("local_corpora", "PV"), ("local_corpora", "VOLBY"), ("local_corpora", "DOF"), ("local_corpora", "UIT"), ("local_corpora", "VN"), - ("local_corpora", "PARLIAMENTS"), + ("local_corpora", "PARLIAMENTS"), ("local_corpora", "MY"), ("local_corpora", "CTGOV_OFFICIALS"), ("local_corpora", "CTGOV_CONTACTS")} diff --git a/tests/v2/test_local_mycandidates.py b/tests/v2/test_local_mycandidates.py new file mode 100644 index 000000000..461bf04ab --- /dev/null +++ b/tests/v2/test_local_mycandidates.py @@ -0,0 +1,205 @@ +"""Offline checks on tools/differential/local_mycandidates.py, the +my-candidates local corpus of Malaysia's election candidates. + +Every name here is invented: the candidates are real people, so their +records stay in the cache. What these pin is what a fetch keeps (one +record per distinct spelling within an election and ethnicity, its +election, form and ethnicity, the ethnicity as its group), which column +each pinned file is read by, and the fetch's refusals: a file other than +the pinned one, another header or row count, a file ending inside a row +(each arm), rows of another width or with an empty name past their +shares, and a corpus read at another commit or by another version. The +network is a stub answering by URL. +""" +import hashlib +import importlib +import time +import urllib.error +import urllib.request +from collections.abc import Sequence + +import pytest + +from ._differential_fixtures import _Response, load_tool, own_cache + +local = load_tool("local_corpora") +# The modules the fetch reads its constants from, by name +# (test_local_corpora.py says why a second load by path would not do). +my = importlib.import_module("local_mycandidates") +core = importlib.import_module("local_core") + +_SOURCE = my.MY +_ONE = ("name", "ethnicity", "votes") +_TWO = ("name_ballot", "name", "ethnicity") + + +@pytest.fixture(autouse=True) +def _own_cache(monkeypatch: pytest.MonkeyPatch, tmp_path_factory: pytest.TempPathFactory) -> None: + own_cache(monkeypatch, tmp_path_factory) + + +def _csv(header: tuple[str, ...], *rows: tuple[str, ...]) -> bytes: + return "".join(",".join(r) + "\n" for r in (header, *rows)).encode() + + +def _serve(monkeypatch: pytest.MonkeyPatch, + files: Sequence[tuple[str, tuple[str, ...], bytes]], *, + pinned: dict[str, str] | None = None, rows: dict[str, int] | None = None + ) -> list[str]: + """Pin FILES to `files`, each (election, header, body): one ballot + form for a header of one name column, a ballot and a full form for + _TWO, the sha256 being the body's (`pinned`'s where given) and the + rows its lines less the header (`rows`' where given); answer each + pinned URL with its body. The URLs asked.""" + pinned, rows = pinned or {}, rows or {} + answers: dict[str, bytes] = {} + pins = [] + for election, header, body in files: + forms = ((("ballot", "name_ballot"), ("full", "name")) if header == _TWO + else (("ballot", "name"),)) + file = my.File(election, f"candidates_{election}.csv", + pinned.get(election, hashlib.sha256(body).hexdigest()), + rows.get(election, body.count(b"\n") - 1), header, forms) + pins.append(file) + answers[my.MY_URL.format(commit=my.MY_COMMIT, file=file.file)] = body + monkeypatch.setattr(my, "FILES", tuple(pins)) + asked: list[str] = [] + + def urlopen(request: urllib.request.Request, timeout: int) -> _Response: + asked.append(request.full_url) + if request.full_url not in answers: + raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, None) # type: ignore[arg-type] + return _Response(answers[request.full_url]) + monkeypatch.setattr(urllib.request, "urlopen", urlopen) + monkeypatch.setattr(time, "sleep", lambda seconds: None) + return asked + + +#: A general election's ballot names: one candidate standing twice (once +#: padded), and the same name under another ethnicity, which is another +#: record; a state election's ballot and full names, one full name equal +#: to its ballot name. +_FILES = [ + ("ge99", _ONE, _csv(_ONE, ("NORAZLAN BIN ZAKARIM", "bumiputera", "10"), + (" NORAZLAN BIN ZAKARIM ", "bumiputera", "12"), + ("NORAZLAN BIN ZAKARIM", "other", "3"), + ("LIM KOK WEE", "chinese", "7"))), + ("prn99", _TWO, _csv(_TWO, ("USTAZ NORAZLAN", "NORAZLAN BIN ZAKARIM", "malay"), + ("MUTHUVEL A/L SANGARAN", "MUTHUVEL A/L SANGARAN", "indian"))), +] + + +def test_a_fetch_keeps_each_distinct_spelling_with_its_election_form_and_ethnicity( + monkeypatch: pytest.MonkeyPatch) -> None: + asked = _serve(monkeypatch, _FILES) + corpus = local.fetch(_SOURCE) + assert asked == [my.MY_URL.format(commit=my.MY_COMMIT, file=f"candidates_{e}.csv") + for e, _, _ in _FILES] + + def rec(name: str, election: str, form: str, ethnicity: str) -> dict[str, str]: + return {"name": name, "election": election, "form": form, "ethnicity": ethnicity} + assert corpus.records == [ + rec("NORAZLAN BIN ZAKARIM", "ge99", "ballot", "bumiputera"), + rec("NORAZLAN BIN ZAKARIM", "ge99", "ballot", "other"), + rec("LIM KOK WEE", "ge99", "ballot", "chinese"), + # A spelling is distinct within its election, so the full name + # that a general election held as a ballot name is a record here. + rec("USTAZ NORAZLAN", "prn99", "ballot", "malay"), + rec("NORAZLAN BIN ZAKARIM", "prn99", "full", "malay"), + rec("MUTHUVEL A/L SANGARAN", "prn99", "ballot", "indian")] + assert corpus.meta["data_date"] == my.MY_DATE + assert corpus.meta["names"] == 4 + detail = corpus.meta["detail"] + assert detail["commit"] == my.MY_COMMIT and detail["read_version"] == my.MY_READ_VERSION + assert detail["elections"] == {"ge99": {"rows": 4, "ballot": 3, "repeated": 1}, + "prn99": {"rows": 2, "ballot": 2, "full": 1, + "repeated": 1}} + + +def test_the_source_is_grouped_by_ethnicity() -> None: + assert local.SOURCES[_SOURCE].group == "ethnicity" + + +def test_each_pinned_file_reads_columns_its_header_holds() -> None: + assert [f.election for f in my.FILES] == ["ge12", "ge13", "ge14", "ge15", "prn15"] + for file in my.FILES: + assert "ethnicity" in file.header + assert {form for form, _ in file.forms} <= {"ballot", "full"} + assert all(column in file.header for _, column in file.forms) + assert len(file.sha256) == 64 and file.rows > 0 + # GE15's `name` is the full name recased into title case, so only its + # ballot name is read; PRN15 writes both in capitals. + assert dict(my.FILES[3].forms) == {"ballot": "name_display"} + assert dict(my.FILES[4].forms) == {"ballot": "name_ballot", "full": "name"} + + +def test_a_file_other_than_the_pinned_one_is_retried_then_refused( + monkeypatch: pytest.MonkeyPatch) -> None: + asked = _serve(monkeypatch, _FILES[:1], pinned={"ge99": "0" * 64}) + with pytest.raises(ValueError, match="sha256 is .* not the pinned 0000"): + local.fetch(_SOURCE) + assert len(asked) == core.RETRIES + + +@pytest.mark.parametrize(("body", "rows", "match"), [ + (_csv(("name", "ethnicity")), None, "header is not the 3 columns"), + (_FILES[0][2], 5, "holds 4 rows where 5 are pinned"), + # The two arms of a body cut inside its last row: no closing line + # break, and a short last row (a cut inside a quoted name that held a + # line break ends with one). + (_FILES[0][2].rstrip(b"\n"), None, "ends inside a row"), + (_csv(_ONE, ("LIM KOK WEE", "chinese", "7")) + b'"TAN\n', 2, "ends inside a row"), +], ids=["header", "row count", "no closing line break", "short last row"]) +def test_a_changed_or_cut_file_is_refused(monkeypatch: pytest.MonkeyPatch, body: bytes, + rows: int | None, match: str) -> None: + _serve(monkeypatch, [("ge99", _ONE, body)], rows={"ge99": rows} if rows else None) + with pytest.raises(ValueError, match=match): + local.fetch(_SOURCE) + + +def test_a_long_last_row_is_left_to_the_malformed_share( + monkeypatch: pytest.MonkeyPatch) -> None: + rows = [("LIM KOK WEE", "chinese", "7")] * 99 + [("TAN AH KOW", "chinese", "7", "x")] + _serve(monkeypatch, [("ge99", _ONE, _csv(_ONE, *rows))]) + assert local.fetch(_SOURCE).meta["detail"]["elections"]["ge99"]["malformed"] == 1 + + +@pytest.mark.parametrize(("bad", "share", "kind"), [ + (("TAN AH KOW", "chinese"), "MY_MAX_BAD", "are not 3 fields"), + (("", "chinese", "7"), "MY_MAX_NAMELESS", "have an empty name"), +], ids=["malformed", "nameless"]) +def test_the_rows_read_past_are_refused_past_their_shipped_share( + monkeypatch: pytest.MonkeyPatch, bad: tuple[str, ...], share: str, kind: str) -> None: + # At the shipped share, one row in a hundred: accepted at it, and + # refused one past it. The last row is whole, so the wholeness check + # does not answer first. + assert getattr(my, share) == 1 / 100 + whole = ("LIM KOK WEE", "chinese", "7") + _serve(monkeypatch, [("ge99", _ONE, _csv(_ONE, bad, *[whole] * 99))]) + local.fetch(_SOURCE) # the control: 1 of 100 + _serve(monkeypatch, [("ge99", _ONE, _csv(_ONE, bad, bad, *[whole] * 98))]) + with pytest.raises(ValueError, match=f"2 of 100 rows of candidates_ge99.csv {kind}"): + local.fetch(_SOURCE) + + +@pytest.mark.parametrize(("constant", "value", "match"), [ + ("MY_COMMIT", "f" * 40, "read at commit .* reads f{40}"), + ("MY_READ_VERSION", 99, "read by version 1 of _read.*version 99"), +], ids=["commit", "read version"]) +def test_a_corpus_read_another_way_is_refused_on_load( + monkeypatch: pytest.MonkeyPatch, constant: str, value: object, match: str) -> None: + _serve(monkeypatch, _FILES) + local.fetch(_SOURCE) + assert local.load(_SOURCE) is not None # the control + monkeypatch.setattr(my, constant, value) + with pytest.raises(ValueError, match=f"{match}.*fetch {_SOURCE} --refresh"): + local.load(_SOURCE) + + +def test_a_row_with_every_name_column_empty_counts_once( + monkeypatch: pytest.MonkeyPatch) -> None: + # Counted per cell, the one row below would be 2 of 100 and refused. + whole = ("CIKGU LIM", "LIM KOK WEE", "chinese") + _serve(monkeypatch, [("prn99", _TWO, _csv(_TWO, ("", "", "chinese"), *[whole] * 99))]) + detail = local.fetch(_SOURCE).meta["detail"]["elections"]["prn99"] + assert detail["nameless"] == 1 diff --git a/tests/v2/test_local_parliaments.py b/tests/v2/test_local_parliaments.py index 2a2d32ad3..5ad0c75e1 100644 --- a/tests/v2/test_local_parliaments.py +++ b/tests/v2/test_local_parliaments.py @@ -279,4 +279,4 @@ def test_a_corpus_fetched_another_way_is_refused_on_load( def test_the_source_pairs_spellings_and_names_its_group() -> None: assert _SOURCE in local.ALIKE_SOURCES assert local.SOURCES[_SOURCE].group == "dataset" - assert len(parl.DATASETS) == len(set(parl.DATASETS)) == 24 + assert len(parl.DATASETS) == len(set(parl.DATASETS)) == 29 diff --git a/tools/differential/README.md b/tools/differential/README.md index e57f78ede..e4482695f 100644 --- a/tools/differential/README.md +++ b/tools/differential/README.md @@ -291,7 +291,7 @@ uv run python tools/differential/build_shapes_corpus.py --coverage A local corpus holds real names that are not committed: fetched into the cache by `local_corpora.py`, read by `snapshot.py --local` and by a row of `tools/name_usage.py`, scored by `local_agreement.py` where its records carry their fields, and seen by no reviewer and no CI run (the SURVEY job in mechanisms.md#NAME-DATA-JOBS, and WATCH and SCORE outside CI). What reaches the repository is what a contributor cites from it, counts and shapes written with made-up names. -`local_corpora.py` holds the `SOURCES` registry, the cache's files, the views and the command line; each source's fetch is a module of its own (`local_ctgov.py`, `local_fec.py`, `local_tse.py`, `local_tw.py`, `local_ukec.py`, `local_govuk.py`, `local_psc.py`, `local_jrc.py`, `local_nepal.py`, `local_orcid.py`, `local_patentsview.py`, `local_volby.py`, `local_dof.py`, `local_uit.py`, `local_vnassembly.py`, `local_parliaments.py`) whose docstring says what the source is and what its terms allow, built on the retry policy, share gate and downloads in `local_core.py`. A new source is a module and a `SOURCES` row. A source whose records hold a value its own code derives, rather than one the source gave (`jrc-names`' script label), stores a read version in `meta.json`'s detail and refuses on load a corpus read by another (`JRC_READ_VERSION`, bumped by hand with any change to how a record is built, and `CTGOV_READ_VERSION` likewise for the ctgov corpora's country; `psc-individuals` does the same for its cached extracts, with `PSC_EXTRACT_VERSION` in each extract's file name): the sha256 checks prove the files are the ones fetched, not that today's code would write them. A constant such as `TSE_MAX_BAD` or `RETRIES` lives in one module, which every reader reads it through, so a test patches it there; no other module `from`-imports it, so a patch set elsewhere raises rather than missing the code (`test_no_module_imports_a_sibling_constant` holds this). +`local_corpora.py` holds the `SOURCES` registry, the cache's files, the views and the command line; each source's fetch is a module of its own (`local_ctgov.py`, `local_fec.py`, `local_tse.py`, `local_tw.py`, `local_ukec.py`, `local_govuk.py`, `local_psc.py`, `local_jrc.py`, `local_nepal.py`, `local_orcid.py`, `local_patentsview.py`, `local_volby.py`, `local_dof.py`, `local_uit.py`, `local_vnassembly.py`, `local_parliaments.py`, `local_mycandidates.py`) whose docstring says what the source is and what its terms allow, built on the retry policy, share gate and downloads in `local_core.py`. A new source is a module and a `SOURCES` row. A source whose records hold a value its own code derives, rather than one the source gave (`jrc-names`' script label), stores a read version in `meta.json`'s detail and refuses on load a corpus read by another (`JRC_READ_VERSION`, bumped by hand with any change to how a record is built, and `CTGOV_READ_VERSION` likewise for the ctgov corpora's country; `psc-individuals` does the same for its cached extracts, with `PSC_EXTRACT_VERSION` in each extract's file name): the sha256 checks prove the files are the ones fetched, not that today's code would write them. A constant such as `TSE_MAX_BAD` or `RETRIES` lives in one module, which every reader reads it through, so a test patches it there; no other module `from`-imports it, so a patch set elsewhere raises rather than missing the code (`test_no_module_imports_a_sibling_constant` holds this). ``` uv run python tools/differential/local_corpora.py fetch ctgov-officials @@ -336,7 +336,8 @@ Any snapshot reading of 5,000 entries or more, committed or local, parses in a w | `dof-signatures` | the signatures in the notes of Mexico's Diario Oficial de la Federación (DOF) for 2025, read through SIDOF's web services (a listing per day, each note's HTML; the notes its robots.txt disallows are skipped), each name cut from the clause that signs it (`local_dof.cut`): the last run of bold words, with the titles before it, which the DOF mostly sets in roman, or with no bold the run a title opens, up to a comma. A record is one signature (a signatory signs many notes): the name, the rule that cut it, the layout (`stacked`, the office on lines above the name and `Rúbrica.` on a line below; `inline`, `Office, Title Name.- Rúbrica.-` in a paragraph), the title the name opens with, how it meets the text before it, and the clause. Of the 35,305 `Rúbrica`s in 2025's notes (fetched 2026-10-31: of the 26,752 notes listed with HTML, 2,936 were published as page images, stating a size of 0, and 22 came back blank though they stated one), 33,565 were cut, to 6,644 distinct names, and the 1,740 left are counted by reason in `meta.json` (neither bold nor a title, an office signing without a name, a date, one word); every day's listing was read again on 2026-10-31 and held all three editions and as many notes as cached, the 7 weekdays listing none being public holidays. Of the signatures, 65.4% open with a title (`Lic.` 27.7%, `Dr.`/`Dra.` 9.3%, `Mtro.`/`Mtra.` 8.2%, `C.` 5.1%, `Ing.` 3.6%, a spelled-out `Licenciado`/`Licenciada` 2.9%, a dotted acronym degree such as `C.P.` or `L.C.P.` in most of the rest), and 45.5% are stacked, 45.3% under their office in the block above, glued to it with no comma once the lines are read as one (the rest with no block above the name in its excerpt). Of 200 cuts drawn at random and checked by hand on 2026-10-31 under cut version 5, 199 were exactly a name and 1 a name behind a rank (`VICEALMIRANTE`), none not a name; under cut version 3, 196, 3 behind an office or degree (`Juez`, `Magistrado`, `Doctora en Derecho.`) and 1 not a name (`f`, a one-word cut refused since). The population for Spanish titles in front of a name. The DOF's texts are not protected by copyright (LFDA art. 14 VIII), and SIDOF permits reproduction without profit with the source cited, which the credit line says | the office before the name, which the cut drops, so a snapshot reads names with nothing before them, and the comma; names a person typed themselves, since the DOF's typesetters write every one; private persons, a signatory being an official, a judge or a party's representative; names outside Mexico and in any script but Latin. The `title` field reads an abbreviation in capitals by shape, so a lone initial counts as one (`J. Guadalupe`, José's), as would a short surname in capitals ending a sentence; one in mixed case only from `local_dof._ABBREVIATED`'s list, so `Ma.` (María's) does not | | `uit-vinames` | the distinct full names of UIT-ViNames, the gender-labelled dataset of the University of Information Technology (VNU-HCM) NLP group (To et al., NLPIR 2020), from the zip in the authors' GitHub repository, pinned by commit and sha256: 26,851 rows, 21,090 distinct names of two words or more on 2026-11-05 (3 rows of one word read past), each with its gender (`female`, `male`, or `both` for the 127 labelled both ways). Written in the Vietnamese order, family name first and given name last, with diacritics (all but 109), 20,593 of the 21,090 three or four words long. The dataset states the name whole, so a record's family, middle and given are DERIVED by the convention a reader assumes (`local_uit.split`: first word the family, last the given, the words between the middle name), versioned by `SPLIT_VERSION`. The population for a family-first reading, and one whose middle names are scored apart from the given name, which ORCID's given-names box, holding both, cannot do. No licence stated; offered for research use, citing the paper | two-word family names (`Tôn Nữ`, `Nguyễn Phúc`), which the convention splits as family and middle; the order of the foreign students' names it keeps (most of the 11 written wholly in capitals are Lao and Khmer names, and others are in mixed case), split the same way; titles, suffixes, commas; names written without diacritics or in the Western order | | `vn-assembly` | the 499 deputies of Vietnam's 15th National Assembly (2021-2026) as the Assembly's deputy database (dbqh.quochoi.vn) lists them, read through OpenSanctions' `vn_national_assembly` dataset (one FollowTheMoney file, crawled weekly; the 2026-11-04 export). Each name in the Vietnamese order with diacritics, beside the deputy's gender, ethnicity (410 Kinh), education and any alias (a religious name with its title, `Hòa thượng Thích ...`, or a former name). A record's name is COMPOSED: the academic rank and degree the education states in words, abbreviated as the press writes them before a name (`local_vnassembly.title_of`: the higher rank, `GS.` or `PGS.`, then the higher degree, `TS.` or `ThS.`, glued, `PGS.TS.`), then the official name, which the record keeps too (`official`, a second corpus key); of the 499, 7 `GS.TS.`, 9 `PGS.TS.`, 142 `TS.`, 241 `ThS.` and 100 untitled. Its parts are derived by `uit-vinames`' convention. The population for Vietnamese titles stated apart from the name. OpenSanctions licenses it under CC BY-NC 4.0, crediting OpenSanctions, and the composed names are derived, which the credit line says | the convention's misses outside Kinh names (an Ê-đê name gives the given name first), which the score cannot see, since it derives its truth by position; the doctor of science (`TSKH`), the medical titles (`BS.`, `BSCKII`), military ranks and religious titles, none composed; private persons; case, spacing and punctuation of a writer's own | -| `opensanctions-parliaments` | the members of twenty-three national chambers as each parliament's own website writes them, read through OpenSanctions' parliament datasets (`local_parliaments.DATASETS`: Azerbaijan, Kyrgyzstan, Uzbekistan's two chambers, Kazakhstan's two, Turkmenistan, Turkey, Croatia, Slovenia, Slovakia, Portugal, India's Sansad, Ukraine's Rada, Belarus's Council of the Republic, Russia's Duma and Federation Council, Indonesia's DPR and DPD, Ethiopia's House of Peoples' Representatives, South Korea's National Assembly, Israel's Knesset, Mongolia's State Great Khural), and the governors, regents and mayors Indonesia elected in 2018 (`id_regional_2018`, read beside its chambers because it writes names as they do and holds 128 of the corpus's 138 Indonesian names opening with `H.`, Haji), one `targets.simple.csv` per dataset, crawled from the parliaments' and the election commission's sites: a record is one distinct spelling of one member, the `name` column or one of the `;`-joined `aliases`, with the member (`entity`, the dataset and OpenSanctions' id), the spelling's script (`local_jrc.script`), the dataset (`dataset`, the group `config_diff.py --group` keeps) and the `form` it stood in (`name` or `alias`). On 2026-11-08 (exports dated 2026-10-08 to 2026-11-08), 19,216 members, 3,479 of them spelled two ways or more, and 24,084 spellings, distinct within each member (23,970 distinct names in the corpus): 19,738 Latin, 2,362 Cyrillic (Ukraine's Rada, Russia's Duma, Kyrgyzstan's, Kazakhstan's Mazhilis in its Kazakh and Russian forms, Uzbekistan's Senate's Cyrillic beside its Latin), 915 Devanagari (India's), 432 Hebrew (the Knesset's, one beside each member's Latin), 299 Hangul and 295 Han (Korea's, beside its Latin), 8 Ethiopic and 35 `mixed` (26 of them Ethiopia's, 4 Korea's). The first seventeen datasets held 13,354 members and 17,041 spellings that day; the four added after them (Indonesia's three and Ethiopia's) 5,131 members and 5,284 spellings, and Korea's and Israel's 731 members and 1,759 spellings. Mongolia's Khural, added 2026-11-12 (export of 2026-11-06), holds 126 members, each written once in Cyrillic with the father's name first; the fetch of that day held 19,283 members and 24,302 spellings (24,192 distinct names), the other datasets' exports unchanged from the same day's earlier fetch. The aliases are other scripts, a parliamentary short name (Portugal's `Jorge Costa` for the full name), the name with its title (India's `Shri`, `Smt.`, `श्री`) and, in Ukraine's 12, another surname (a maiden or married name, or another spelling). Issues #1186 to #1192 were read from it in the 2026-11-07/08 check of the shipped packs, and it holds the shapes they ask about; the Indonesian datasets, 90% in capitals with no family name (`H.` for Haji, `R.` for Raden, `Imam` as a given name), measure #1205 and #1206 but not #1204, holding no degrees, Ethiopia's, a given, a father's and a grandfather's name, measures #1203, Korea's, every member in Latin, Hangul and Hanja, measures #1213, #1215 and #1216, Israel's, every member in Latin and Hebrew, #1209, #1210 and #1211, and Mongolia's #1237: Turkic patronymics (`qızı`, `oğlu`, `-uly`, `-yevich`, `o‘g‘li`) and East Slavic ones, in Cyrillic and Latin, family first and last, the family often in capitals (`AĞAZADƏ Əminə`, `Mehmet DEMİR`); Indic titles and initials; Slavic and Portuguese double surnames. OpenSanctions licenses it under CC BY-NC 4.0, crediting OpenSanctions | private persons, and how anyone but a parliament's web team writes a name: most chambers write every member one way (India's Sansad is the exception, a title before some names and not others, and freeform entries such as two people in one name); the parliaments not listed (OpenSanctions crawls more) | +| `opensanctions-parliaments` | the members of twenty-eight national chambers as each parliament's own website writes them, read through OpenSanctions' parliament datasets (`local_parliaments.DATASETS`: Azerbaijan, Kyrgyzstan, Uzbekistan's two chambers, Kazakhstan's two, Turkmenistan, Turkey, Croatia, Slovenia, Slovakia, Portugal, India's Sansad, Ukraine's Rada, Belarus's Council of the Republic, Russia's Duma and Federation Council, Indonesia's DPR and DPD, Ethiopia's House of Peoples' Representatives, South Korea's National Assembly, Israel's Knesset, Mongolia's State Great Khural, Malaysia's Dewan Rakyat, Pakistan's National Assembly and Senate, Egypt's House of Representatives, Somalia's House of the People), and the governors, regents and mayors Indonesia elected in 2018 (`id_regional_2018`, read beside its chambers because it writes names as they do and holds 128 of the corpus's 138 Indonesian names opening with `H.`, Haji), one `targets.simple.csv` per dataset, crawled from the parliaments' and the election commission's sites: a record is one distinct spelling of one member, the `name` column or one of the `;`-joined `aliases`, with the member (`entity`, the dataset and OpenSanctions' id), the spelling's script (`local_jrc.script`), the dataset (`dataset`, the group `config_diff.py --group` keeps) and the `form` it stood in (`name` or `alias`). On 2026-11-08 (exports dated 2026-10-08 to 2026-11-08), 19,216 members, 3,479 of them spelled two ways or more, and 24,084 spellings, distinct within each member (23,970 distinct names in the corpus): 19,738 Latin, 2,362 Cyrillic (Ukraine's Rada, Russia's Duma, Kyrgyzstan's, Kazakhstan's Mazhilis in its Kazakh and Russian forms, Uzbekistan's Senate's Cyrillic beside its Latin), 915 Devanagari (India's), 432 Hebrew (the Knesset's, one beside each member's Latin), 299 Hangul and 295 Han (Korea's, beside its Latin), 8 Ethiopic and 35 `mixed` (26 of them Ethiopia's, 4 Korea's). The first seventeen datasets held 13,354 members and 17,041 spellings that day; the four added after them (Indonesia's three and Ethiopia's) 5,131 members and 5,284 spellings, and Korea's and Israel's 731 members and 1,759 spellings. Mongolia's Khural, added 2026-11-12 (export of 2026-11-06), holds 126 members, each written once in Cyrillic with the father's name first; the fetch of that day held 19,283 members and 24,302 spellings (24,192 distinct names), the other datasets' exports unchanged from the same day's earlier fetch. The five chambers added 2026-11-19 (#1465) hold 1,572 members and 2,211 spellings: Malaysia's 276 (16 with an alias writing the `bin` or `a/l` the name leaves out), Pakistan's 332 and 95, each written once, Egypt's 594 in Arabic script, 588 of them written twice, a short name and the full chain of names, and Somalia's 275 (35 with an alias holding a nickname in brackets); the fetch of that day held 20,856 members and 26,515 spellings (26,400 distinct names), some of the other datasets' exports having moved since 2026-11-12. The aliases are other scripts, a parliamentary short name (Portugal's `Jorge Costa` for the full name), the name with its title (India's `Shri`, `Smt.`, `श्री`) and, in Ukraine's 12, another surname (a maiden or married name, or another spelling). Issues #1186 to #1192 were read from it in the 2026-11-07/08 check of the shipped packs, and it holds the shapes they ask about; the Indonesian datasets, 90% in capitals with no family name (`H.` for Haji, `R.` for Raden, `Imam` as a given name), measure #1205 and #1206 but not #1204, holding no degrees, Ethiopia's, a given, a father's and a grandfather's name, measures #1203, Korea's, every member in Latin, Hangul and Hanja, measures #1213, #1215 and #1216, Israel's, every member in Latin and Hebrew, #1209, #1210 and #1211, Mongolia's #1237, and Malaysia's and Egypt's #1468, #1072 and #1464: Turkic patronymics (`qızı`, `oğlu`, `-uly`, `-yevich`, `o‘g‘li`) and East Slavic ones, in Cyrillic and Latin, family first and last, the family often in capitals (`AĞAZADƏ Əminə`, `Mehmet DEMİR`); Indic titles and initials; Slavic and Portuguese double surnames. OpenSanctions licenses it under CC BY-NC 4.0, crediting OpenSanctions | private persons, and how anyone but a parliament's web team writes a name: most chambers write every member one way (India's Sansad is the exception, a title before some names and not others, and freeform entries such as two people in one name); the parliaments not listed (OpenSanctions crawls more) | +| `my-candidates` | the candidates of Malaysia's general elections GE12 (2008) to GE15 (2022) and of the six state elections of 2023 (PRN15), from Thevesh Theva's analysis-election-msia repository on GitHub (`data/candidates_ge12.csv` to `candidates_ge15.csv` and `candidates_prn15.csv`), pinned by commit and each file's sha256 (`local_mycandidates.FILES`): a record is one distinct spelling within an election and ethnicity, with the `election`, the `form` (`ballot`, or `full` for PRN15's full names) and the candidate's `ethnicity` as the file writes it (the group `config_diff.py --group` keeps: `bumiputera` in the general elections, `malay` in PRN15, `chinese`, `indian`, `other`). The names are in capitals, as gazetted. Each file's ballot name is read (GE12 to GE14's `name`, GE15's `name_display`, PRN15's `name_ballot`), and PRN15's full `name` beside it; GE15's `name` is the full name recased into title case by the repository's author, and is read past. On 2026-11-19, 3,261 rows gave 3,683 spellings (3,260 ballot, 423 full) and 3,077 distinct names: 2,759 records `bumiputera` or `malay` (the general elections' `bumiputera` is the wider, taking in Sabah's and Sarawak's peoples, the Iban among them; PRN15's six states are all in the peninsula, where it writes `malay`), 665 `chinese`, 247 `indian`, 12 `other`. The population for `BIN`, `BINTI` and their short forms `B.` and `BT` (#1467), `A/L`, `A/P` and `ANAK` (#1468), the `@` alias (#1164), `MD` and `MOHD` before a name, honorifics opening a ballot name (`USTAZ`, `CIKGU`, `DR`, `HJ`, #1179) and Chinese names written family first (#1183). The repository is licensed under the GPL-3.0; the names are cached, never committed or shipped | how a candidate writes their own name, mixed case (one candidate's name, recorded in three elections, is not in capitals), commas; the full names behind the general elections' ballot names; candidates of other years | A live source has no fixed snapshot to pin, so the cached copy is the pin: `meta.json` holds the source's data date and the sha256 of `raw.jsonl` and `corpus.jsonl`, checked on every load, and every report, the `name_usage.py` row included, carries the source and that date. Quote a count with the date, and expect a later fetch to differ. A local snapshot records which fetch it was read from, and `snapshot.py --local` refuses to compare it with a corpus fetched since, which would report the names the source gained and lost as moves: after a `fetch --refresh`, record again from the base checkout. ClinicalTrials.gov's terms ask anyone redistributing its data to credit it, show NLM's processing date and say what was changed; keeping the names in the cache and citing counts with that header meets them. The FEC's bar on soliciting and commercial use is in the credit line of every `fec-individuals` report, so a count quoted from it carries the bar with it. A record there is a distinct name, not a contribution or a contributor: one donor gives many times (34,264,742 rows held 1,893,964 names in the file dated 2026-10-18), and counting contributions would weight a shape by how often its bearers give. `tools/name_usage.py` looks a word up in each corpus's word index, cached as `wordindex.json` beside it on first use and keyed to the records' sha256, to the code that cuts and folds a word and to the record keys it reads (`Source.corpus_keys`; a record whose two names write one word counts once), so a refetch, a change to the fold or a change to which of a record's names are read rebuilds it; a single-word lookup it answers parses neither the records nor the names. Measured 2026-10-22 with both corpora fetched, a single-word `name_usage.py --no-wikidata` run took 2.5s with their indexes cached (12.5s before the cache, 14.8s on the run that builds it). A spaced word (`Ph. D.`) still scans every name, which took 8.6s, nearly all of it the FEC corpus's. For `orcid-researchers` and `patentsview-inventors`, whose extracts keep every record's boxes and country uncapped, `name_usage.py --boxes` adds a row by box and country, read from a second index, `boxindex.json.gz` beside the corpus (`cached_box_index`): per word and country the people whose given box or family box writes it, each country shown as a share of its people, so a word can be weighed in the country a language pack is for (`--country CC`). It is keyed to the extract's sha256, taken from the bytes as they are read, and to a fingerprint of the reader and the fold, so a refetch rebuilds it. Building it took 2 min 19 s for ORCID's 24,990,909 records (3,780,309 words in 6,660,756 word-and-country cells, 41 MB cached) on 2026-10-28. With both indexes cached a lookup took 10.4 s with `--boxes` against 5.3 s without, the difference nearly all reading the two indexes (the 369 MB extract hashes in a fraction of a second once the system has it cached), which is why the rows are asked for rather than always built; an extract that cannot be read fails its own row, naming the refresh. `fetch --refresh` re-downloads the FEC's zip rather than re-reading the cached one, replacing it only once the new one is whole, and a corpus fetched for another cycle than `FEC_CYCLE` is refused on load. The `fec-individuals` fetch refuses a file whose lines stop matching the 21 columns it reads, or whose names stop holding a comma, rather than read it as a smaller or a different corpus. A `ukec-individuals` record is a distinct name too, not a donation or a `DonorId`: one name often holds several IDs, which seem to come with reports rather than with people (15,214 names held 24,473 on 2026-10-22, the IDs counted in `meta.json`'s detail; 2,663 names held several at one `RegulatedEntityId` alone, counted from the export and not kept, though some of those may be two people of one name), so a count of IDs would weight a name by how often it was reported. Its fetch reads the register's total from the JSON search under the same filter before and after the export, and refuses an export holding another number of rows, or a register that changed in between: the export ignores `rows=`, so the total is what tells a cut or capped export from the whole register. It refuses an export whose last row is cut short (Python's `csv` returns a body cut inside a row as a short last row, which the row count would otherwise take for a whole one), and a header other than the 29 columns `UKEC_COLUMNS` names, and counts into `meta.json`'s detail the rows it skips: rows not 29 fields, rows from a donor that is not an individual (the filter asks the server to leave those out), and individuals with no name. Past `UKEC_MAX_BAD` of either of the first two, or `UKEC_MAX_NAMELESS` of the third (4 of 42,355 rows were nameless on 2026-10-22), it refuses the export. The data date is when the first search answered, in UTC: the register states no date of its own, so the counts above, dated by the day they were fetched (2026-10-22), carry the data date 2026-10-23T03:13:19Z in their header. `tw-donors` keeps one zip per report under `reports/`, whole, its masked ID, address and phone columns included, as the FEC's zip is kept: the platform's download answers a report that does not exist and a fault alike, with a 500 and an incident number, so the fetch reads which reports exist from the platform's listing and refuses a listed report it cannot download. It reads each file's columns by name, since a 2020 report lacks a column the newest ones write, and refuses a column it does not know, a category it does not know, a row whose serial column names another report (the zip is not the one asked for), a listing that changes during the fetch, and a report past `TW_MAX_REPORT_BAD` of whose rows it reads past. It reads back the rows a stray quote took into one field (169 rows in 12 records of three reports on 2026-10-22, 8 of them two rows joined by two stray quotes), counts donor cells that hold no name (匿名, a dash) or a masked one, and caches a downloaded zip only once its rows are read, so a refused zip is asked for again. A zip the platform rebuilt under the name it had is not seen: delete `reports/` to download every report again. A layout check written from one surveyed file meets every other file only at fetch time: `tw-donors`' first three fetches were each refused partway, by a report with no income writing one row of dashes, by a 2020 report with 24 columns where the surveyed one had 25, and by a row with no category. Each refusal cost every download again until the source cached its zips, so a new source that downloads many files caches each one before its checks run. `tse-donors` caches nothing but the corpus: each election's national member (`receitas_candidatos__BRASIL.csv`) is read from the TSE's CDN in HTTP Range requests, 209 MB for the two elections where their zips are 1.82 GB (2026-10-22), because the TSE regenerates the zips every few days and a cached one would be stale within the week. Every range request carries `If-Range` with the ETag the HEAD gave if it is strong, else its `Last-Modified`, and every part must state the `Content-Range` asked for, so a zip replaced during the read is refused rather than read across two versions; a HEAD that states no length, neither a strong ETag nor a `Last-Modified`, or `Accept-Ranges` other than `bytes` is refused before the read. A fetch took 69s on 2026-10-22. It refuses a zip without the national member, a header that is not 60 columns or lacks its three columns, a `DS_ORIGEM_RECEITA` value it does not know (a renamed category, or the file no longer in Latin-1), malformed rows or lines folded into a field past `TSE_MAX_BAD`, an election with too few rows from individuals (`TSE_MIN_INDIVIDUALS`: a member cut to its header, or the donations moved under another category) too many without a name or registry name (`TSE_MAX_MISSING`, counting a placeholder such as `#NULO` or `***` as none: a masked column) or with a number in one (`TSE_MAX_NUMBERED`: a numeric column moved under a name), too few distinct filed or registry names (`TSE_MIN_DISTINCT`: a column masked with one word), and a corpus fetched for other elections than `TSE_ELECTIONS`. The CPF in each row is unmasked in the file, and like every other column it is read past, never stored or printed; a pair either of whose names holds more than `TSE_MAX_DIGITS` digits is dropped and counted, since campaigns sometimes typed a number, a CPF among them, into the name field. A record is a pair, so the counts in its reports (`tally`, the `name_usage.py` row) are of pairs, and a filed name standing beside two registry names counts twice. @@ -356,7 +357,9 @@ Its score reads the title before the name against `TITULPRED`, the given and mid `uit-vinames` downloads one zip, the pinned commit's `UIT-ViNames-v1.zip`, and refuses a body whose sha256 is not the pinned one (retried first, as a body cut short), so a cut or changed zip never reads as a smaller corpus; it reads `Full.csv` alone (the train, dev and test files are its splits), and refuses a header other than `Full_Name,Gender`, another row count than `UIT_ROWS` and a row that is not a name and a gender of 0 or 1. The data date is the commit's. `vn-assembly` reads the dataset's `index.json` first (`datasets/latest/` redirects to the newest export), which states the FtM file's URL, size and sha1 and the deputies it counts, and refuses a file of another size or sha1 (retried first), one holding another number of deputies, a deputy with no name, several, or one of a single word, and one under `VN_MIN_TITLED` titled (an education field emptied or moved). Its data date is the index's `updated_at`; `meta.json` holds the export's version, `TITLE_VERSION`, the version of `title_of`, and `local_uit.SPLIT_VERSION`, the split's, and a corpus derived or split by another version is refused on load, as `uit-vinames` refuses one read by another `UIT_READ_VERSION` or split by another `SPLIT_VERSION`. Each scores family, middle and given against the derived parts, and `vn-assembly` the title against the composed one too, never set aside, since its title box holds what the education states; `vn-assembly` is grouped by ethnicity from 10 records (its `Fielded`'s `group_floor`), its 499 being too few for the 1,000 the others use. A score that agrees with the convention says the parser reads a Vietnamese name by position as a reader would, not that the convention is right for that name. Each fetch took under 5s on 2026-11-05. -`opensanctions-parliaments` reads each dataset's `index.json` first (`datasets/latest//` redirects to the newest export), and refuses one that states no `target_count`, no `updated_at`, or no URL, size and sha1 for the CSV. It refuses a file of another size or sha1 (retried first, as the index is), then, in this order, one lacking the `id`, `schema`, `name` or `aliases` column, one whose body does not end with a line break or whose last row is short (Python's `csv` reads a body cut inside a row as a short last row, as `ukec-individuals`' check says), one holding another number of rows than the targets, a person with an empty or repeated id (which would merge two members into one entity), past their shares malformed rows (`MAX_BAD`), people with no name (`MAX_NAMELESS`) and cells joined by another separator than `;` (`FOREIGN_SEPARATORS`, `MAX_BAD`), and a file holding no row of the `Person` schema or fewer than `MIN_PERSONS`; every row of the twenty-three was a person on 2026-11-08. A multi-valued column is split at `;`, the name's too (one of India's cells held two names, counted as `name cells split`), and an alias repeating the name is dropped. Its data date is the newest dataset's `updated_at`, and `meta.json`'s detail holds each dataset's version, date and counts; a corpus fetched over another `DATASETS`, read by another `READ_VERSION`, or labelled by another version of `local_jrc.script()` (`JRC_READ_VERSION`) or under another Unicode version is refused on load. It holds no fields, so it is a `snapshot.py --local` population and a `groups` and `alike` one, not a `local_agreement.py` one. The fetch took 10s on 2026-11-08 over the first seventeen datasets, 30s over twenty-one, and 40s over all twenty-three. On that fetch `groups` read 44.1% of the 3,479 members spelled two ways or more alike (its `any` row; `Latin / Latin`, 2,611 members, 37.3%; over the first seventeen datasets, 37.5% of 2,602 and 34.0% of 2,465). Korea's spellings read alike in almost no member: Hangul / Latin in none of 297, because the Latin is written family first (`Kim Hyung Yun`) and read in the positional default, given `Kim`, while the Hangul reads family `김`; Han / Hangul in 0.3% of 295, the Hanja staying one family word (`金炯淵`), which is #1216. Hebrew / Latin read alike in 97.5% of 432. By its cross-script measure, some spelling on each side reading alike, Cyrillic / Cyrillic (77) and Cyrillic / Latin (59) read alike in every member, and Devanagari / Latin in 23.6% of 915, differing in the title in 73.2%: `parse()` reads `श्री` as a title and a Latin `Shri` as the given name (`Samanta, Shri Achyutananda` → given `Shri`), which is #1192. +`opensanctions-parliaments` reads each dataset's `index.json` first (`datasets/latest//` redirects to the newest export), and refuses one that states no `target_count`, no `updated_at`, or no URL, size and sha1 for the CSV. It refuses a file of another size or sha1 (retried first, as the index is), then, in this order, one lacking the `id`, `schema`, `name` or `aliases` column, one whose body does not end with a line break or whose last row is short (Python's `csv` reads a body cut inside a row as a short last row, as `ukec-individuals`' check says), one holding another number of rows than the targets, a person with an empty or repeated id (which would merge two members into one entity), past their shares malformed rows (`MAX_BAD`), people with no name (`MAX_NAMELESS`) and cells joined by another separator than `;` (`FOREIGN_SEPARATORS`, `MAX_BAD`), and a file holding no row of the `Person` schema or fewer than `MIN_PERSONS`; every row of the twenty-three was a person on 2026-11-08. A multi-valued column is split at `;`, the name's too (one of India's cells held two names, counted as `name cells split`), and an alias repeating the name is dropped. Its data date is the newest dataset's `updated_at`, and `meta.json`'s detail holds each dataset's version, date and counts; a corpus fetched over another `DATASETS`, read by another `READ_VERSION`, or labelled by another version of `local_jrc.script()` (`JRC_READ_VERSION`) or under another Unicode version is refused on load. It holds no fields, so it is a `snapshot.py --local` population and a `groups` and `alike` one, not a `local_agreement.py` one. The fetch took 10s on 2026-11-08 over the first seventeen datasets, 30s over twenty-one, and 40s over all twenty-three, and 49s over all twenty-eight on 2026-11-19. On the 2026-11-08 fetch `groups` read 44.1% of the 3,479 members spelled two ways or more alike (its `any` row; `Latin / Latin`, 2,611 members, 37.3%; over the first seventeen datasets, 37.5% of 2,602 and 34.0% of 2,465). Korea's spellings read alike in almost no member: Hangul / Latin in none of 297, because the Latin is written family first (`Kim Hyung Yun`) and read in the positional default, given `Kim`, while the Hangul reads family `김`; Han / Hangul in 0.3% of 295, the Hanja staying one family word (`金炯淵`), which is #1216. Hebrew / Latin read alike in 97.5% of 432. By its cross-script measure, some spelling on each side reading alike, Cyrillic / Cyrillic (77) and Cyrillic / Latin (59) read alike in every member, and Devanagari / Latin in 23.6% of 915, differing in the title in 73.2%: `parse()` reads `श्री` as a title and a Latin `Shri` as the given name (`Samanta, Shri Achyutananda` → given `Shri`), which is #1192. + +`my-candidates` downloads the five pinned files and refuses one whose sha256 is not the pinned one (retried first, as a body cut short), then, in this order, one of another header than the file's pinned one, one whose body does not end with a line break or whose last row is short (as `opensanctions-parliaments` does), one holding another number of rows than pinned, and past their shares rows of another width (`MY_MAX_BAD`) and rows with an empty name in a column read (`MY_MAX_NAMELESS`), a row counted once however many of its columns are empty. Its data date is the pinned commit's, and a corpus read at another `MY_COMMIT` or by another `MY_READ_VERSION` is refused on load. It holds no fields, so it is a `snapshot.py --local` population, not a `local_agreement.py` one. The fetch took under a second on 2026-11-19. `local_agreement.py` does the SCORE job for a local corpus. It parses each filed display name and compares the parser's roles with the boxes the source states (title, given, middle and family for `psc-individuals`; given and middle joined against the given-names box, then family, for `orcid-researchers` and `patentsview-inventors`; title, given and middle joined, family and suffix for `cz-candidates`; family, middle and given, the parts derived, for `uit-vinames`; and title, family, middle and given for `vn-assembly`), folding case, periods, commas and spacing. Where the source has no box after the name, a suffix the parser peels is compared inside the surname box: the display name joins the surname last, so a trailing suffix was typed into it whenever it is filled, with or without a comma (`Smith, Jr.`); the fold read the comma as a miss until 2026-10-28, which moved 83 `psc-individuals` records and 561 `orcid-researchers` records to agreeing and none away. Where a source has a title box, and save `cz-candidates` (above), a title the parser reads otherwise, holding a word the vocabulary lists as neither a title nor a connective (a job typed as a title), is set aside as filer error rather than scored, and the report lists the commonest such titles as leads for the vocabulary. The report gives agreement overall and by the group the source states (nationality, country), misses per field, and the commonest disagreement shapes, as counts, word counts and the commonest set-aside titles; `--list N` prints moved records, names and all, for reading locally. Its record, `agreement.jsonl` beside the corpus, holds every record that did not wholly agree, so a re-run reports what moved. As with the local snapshot, check it from the branch against a base you name (`--base `, whose record is kept under `agreements/` beside the corpus, keyed by the fetch, the base's `nameparser/` files, the interpreter's minor version and the scorer, the ten most recent kept; the scorer's fingerprint reads only its own source's `FIELDED` entry, so adding a source leaves the others' records standing, which the whole table, hashed until `patentsview-inventors` was added on 2026-10-28, did not), or, alone, record the shared one from the base checkout (`--record --tree `) and run it from the branch; it refuses a record from another fetch, or one written by another version of the scorer, whose own change would otherwise read as the parser's moves. `--locale cs` scores the parser of a locale pack, `parser_for(locales.CS)`, against a record of its own (`agreement.cs.jsonl`, and kept records keyed by the locale too), so a pack's score and the default's never stand for each other; `measure.py` runs the default's alone. No CI run sees it. @@ -396,7 +399,7 @@ uv run python tools/differential/measure.py --base ../master-checkout The steps: the committed snapshot (`snapshot.py`, the check `tests/v2/test_snapshot.py` makes), `cldr_agreement.py`, `snapshot.py --local --base` for every fetched local corpus, `local_agreement.py SOURCE --base` for every fetched source whose records carry their fields (`psc-individuals`, `orcid-researchers`, `patentsview-inventors`, `cz-candidates`, `uit-vinames`, `vn-assembly`), and `local_corpora.py alike --base` for every fetched source that pairs spellings. Only the local steps read `--base`: the first two compare the tree with the records committed on its branch, so on a branch that has re-recorded `snapshot.jsonl` the committed snapshot says no moves and the moves are in the PR's diff of that file, and the summary labels each step with what it compared against. A local corpus that is not fetched gets no step, the summary names it, and a run in which no step read `--base` exits 1. Each step's whole output goes to a file of its own under `--out`, by default a folder named for the time under the cache's `measure/`, outside the repository, since a local snapshot lists its moves by name. The summary, `summary.txt` beside them and printed, gives each step's status (no moves, moves, or failed with its exit code), its time, and its unindented lines (the first few and the last, where the verdicts are, up to `SUMMARY_LINES`, and any line saying part of a check was not measured), never the indented ones where the tools list names; a crash's traceback is indented below a line naming only its type, since its message may hold a name. A step that fails makes the run exit 1; one that finds moves does not. Each tool refuses with `SystemExit("message")`, which exits 1 as a move does, so measure runs every step through its own `--step` wrapper, which turns a message exit or an uncaught exception into exit 2: a refused base or a damaged corpus is reported as a failure, never as moves. -**Comparing configurations in one tree.** `snapshot.py --local` compares two trees under one configuration and `local_agreement.py` scores one configuration against the filed boxes; `config_diff.py diff` compares two or more CONFIGURATIONS in the tree it runs in, over the committed corpora, any fetched local corpus (`--local SOURCE`, or `all`), a fielded corpus's countries or nationalities as it writes them, `opensanctions-parliaments`' datasets, or the ctgov corpora's ISO country codes (`--group`, which needs `--local` and refuses a group no record holds; a corpus with no fields names its group key in its `Source`'s `group`), the names a regular expression finds (`--match`) and a hash sample (`--sample N`), each name rewritten first where `--spelling` asks (`stripped`, `upper`, `lower`, comma-separated: `--spelling stripped,upper` reads a Vietnamese population as plain-ASCII data in capitals writes it, #1108). A configuration is `default`, `plain:` or `strict:` (`parser_for` over the items joined by `+`: a shipped pack in capitals, `ES`, `PT_BR`, a bare language tag in lower case, `pt-BR`), or `expr:` for any other lexicon or policy; the first is the baseline. It compares the seven roles, the ambiguity kinds and 3.0's views (`generation`, `credentials`, `honorifics`, `patronymic`, `surname2`), and prints, per configuration, the names that moved by input and grouped by the fields that changed, and the words whose token changed role, ranked, each with an example; `--json` keeps the counts and the moved names, `--readings` every name's readings one line a name, so a run in each of two trees compares line by line. Every parse runs in `--jobs` worker processes (`snapshot.parallel`). Reach for it before writing a script that parses the corpora under two configurations: #1000, #1005, #1017 and #1019 each wrote one. +**Comparing configurations in one tree.** `snapshot.py --local` compares two trees under one configuration and `local_agreement.py` scores one configuration against the filed boxes; `config_diff.py diff` compares two or more CONFIGURATIONS in the tree it runs in, over the committed corpora, any fetched local corpus (`--local SOURCE`, or `all`), a fielded corpus's countries or nationalities as it writes them, `opensanctions-parliaments`' datasets, the ctgov corpora's ISO country codes, or `my-candidates`' ethnicities (`--group`, which needs `--local` and refuses a group no record holds; a corpus with no fields names its group key in its `Source`'s `group`), the names a regular expression finds (`--match`) and a hash sample (`--sample N`), each name rewritten first where `--spelling` asks (`stripped`, `upper`, `lower`, comma-separated: `--spelling stripped,upper` reads a Vietnamese population as plain-ASCII data in capitals writes it, #1108). A configuration is `default`, `plain:` or `strict:` (`parser_for` over the items joined by `+`: a shipped pack in capitals, `ES`, `PT_BR`, a bare language tag in lower case, `pt-BR`), or `expr:` for any other lexicon or policy; the first is the baseline. It compares the seven roles, the ambiguity kinds and 3.0's views (`generation`, `credentials`, `honorifics`, `patronymic`, `surname2`), and prints, per configuration, the names that moved by input and grouped by the fields that changed, and the words whose token changed role, ranked, each with an example; `--json` keeps the counts and the moved names, `--readings` every name's readings one line a name, so a run in each of two trees compares line by line. Every parse runs in `--jobs` worker processes (`snapshot.parallel`). Reach for it before writing a script that parses the corpora under two configurations: #1000, #1005, #1017 and #1019 each wrote one. ``` uv run python tools/differential/config_diff.py diff default strict:PT_BR --local orcid-researchers --group BR diff --git a/tools/differential/config_diff.py b/tools/differential/config_diff.py index 75dbe35ac..535e6dba8 100644 --- a/tools/differential/config_diff.py +++ b/tools/differential/config_diff.py @@ -31,8 +31,9 @@ `--local SOURCE` (repeatable, or `all`) a fetched local corpus's distinct names. With neither, the committed corpora. `--group` keeps a grouped local corpus's records of that country or nationality, or for -opensanctions-parliaments that dataset, or for ctgov-officials and -ctgov-contacts that ISO country code (local_agreement.FIELDED names the +opensanctions-parliaments that dataset, for ctgov-officials and +ctgov-contacts that ISO country code, or for my-candidates that +ethnicity (local_agreement.FIELDED names the key, and Source.group for a corpus with no fields; matched exactly as the corpus writes it), and needs `--local`: with `--committed` beside it, which has no groups, it is refused, as is a group no record read holds; with @@ -421,7 +422,7 @@ def group_keys() -> dict[str, str]: """The record key naming each grouped local corpus's group: a fielded corpus's (local_agreement.FIELDED), then a source's own (Source.group: opensanctions-parliaments' dataset, the ctgov corpora's - country).""" + country, my-candidates' ethnicity).""" keys = {source: fielded.group for source, fielded in local_agreement.FIELDED.items()} return keys | {source: s.group for source, s in local_corpora.SOURCES.items() if s.group and source not in keys} @@ -1129,7 +1130,7 @@ def main(argv: list[str] | None = None) -> int: d.add_argument("--committed", action="store_true", help="the committed corpus*.jsonl") d.add_argument("--local", action="append", metavar="SOURCE", help="a local corpus, or all") d.add_argument("--group", action="append", default=[], help="a grouped corpus's country, " - "nationality or dataset, as the corpus writes it (repeatable; needs --local)") + "nationality, dataset or ethnicity, as the corpus writes it (repeatable; needs --local)") d.add_argument("--match", help="keep the names this regular expression finds") d.add_argument("--sample", type=int, help="one name in N, by a hash of the name") d.add_argument("--spelling", type=_spellings, help="rewrite every name before it is " diff --git a/tools/differential/local_core.py b/tools/differential/local_core.py index ed97ade0d..2a4169fca 100644 --- a/tools/differential/local_core.py +++ b/tools/differential/local_core.py @@ -72,7 +72,7 @@ class Source: #: For a source with no fields to score (no local_agreement.FIELDED #: entry) whose records name a group all the same: the record key #: holding it (opensanctions-parliaments' "dataset", the ctgov - #: corpora's "country"), which + #: corpora's "country", my-candidates' "ethnicity"), which #: config_diff.py --group keeps, as it keeps a fielded source's. group: str = "" diff --git a/tools/differential/local_corpora.py b/tools/differential/local_corpora.py index e723fb067..a22f749d8 100644 --- a/tools/differential/local_corpora.py +++ b/tools/differential/local_corpora.py @@ -57,7 +57,10 @@ states, with the official name, the title, the derived parts, the gender and the ethnicity; one distinct spelling of a member of a national parliament, with the member, its script, the dataset and - whether it is the name or an alias. The counts are counted from here. + whether it is the name or an alias; one distinct spelling of a + Malaysian election candidate within an election, with the election, + the form (ballot or full name) and the ethnicity. The counts are + counted from here. - corpus.jsonl -- the distinct names, in the corpus line format snapshot.py and compare.py --corpus read: each record's "name", and for nepal-candidates its Devanagari name too, and for @@ -99,8 +102,9 @@ local_nepal.py (nepal-candidates), local_orcid.py (orcid-researchers), local_patentsview.py (patentsview-inventors), local_volby.py (cz-candidates), local_dof.py (dof-signatures), -local_uit.py (uit-vinames), local_vnassembly.py (vn-assembly) and -local_parliaments.py (opensanctions-parliaments). +local_uit.py (uit-vinames), local_vnassembly.py (vn-assembly), +local_parliaments.py (opensanctions-parliaments) and +local_mycandidates.py (my-candidates). """ from __future__ import annotations @@ -145,6 +149,7 @@ from local_fec import check_fec, fetch_fec, renew_fec # noqa: E402 from local_govuk import fetch_govuk # noqa: E402 from local_jrc import JRC, check_jrc, fetch_jrc, renew_jrc # noqa: E402 +from local_mycandidates import MY, check_my, fetch_my # noqa: E402 from local_nepal import check_nepal, fetch_nepal # noqa: E402 from local_orcid import (ORCID, check_orcid, extract_path as orcid_extract, # noqa: E402 fetch_orcid, orcid_boxes, renew_orcid) @@ -312,6 +317,11 @@ def index(self) -> WordIndex: "parliament datasets (CC BY-NC 4.0; credit OpenSanctions)", unit="spellings", fetch=fetch_parliaments, check=check_parliaments, group="dataset"), + MY: Source( + credit="Malaysian election candidates, GE12-GE15 and the 2023 state " + "elections, from Thevesh Theva's analysis-election-msia " + "(github.com/Thevesh/analysis-election-msia, GPL-3.0)", + unit="spellings", fetch=fetch_my, check=check_my, group="ethnicity"), } diff --git a/tools/differential/local_mycandidates.py b/tools/differential/local_mycandidates.py new file mode 100644 index 000000000..a3caafbe2 --- /dev/null +++ b/tools/differential/local_mycandidates.py @@ -0,0 +1,219 @@ +"""The my-candidates local corpus: Malaysia's election candidates, as +their ballots name them. + +my-candidates -- the candidates of Malaysia's general elections GE12 +(2008) to GE15 (2022) and of the six state elections of 2023 (PRN15), +from Thevesh Theva's analysis-election-msia repository on GitHub +(`data/candidates_.csv`), pinned here by commit and by each +file's sha256. A row is one candidacy: on 2026-11-19 the five files held +480, 579, 687, 945 and 570 rows. The names are written in capitals, as +the Election Commission gazettes them, save one candidate's, written in +mixed case in each of GE12 to GE14 (`Xxx Yyy ZZZ`, its last word in +capitals). + +Which column holds that writing differs by file, and is read so +(FILES): GE12 to GE14 have one, `name`, the name as it stood on the +ballot (often shortened: the full name's `BIN X` dropped, an honorific +added). GE15 has two: `name_display`, the ballot name in capitals, +and `name`, the full name recased by the repository's author into title +case (`Xxx Bin Yyy`); the capitals it was recased from are not in the +file, and recasing it back would be a guess (the mixed-case name above +shows a writer's case is not always capitals), so only `name_display` +is read. PRN15 has two, both in capitals: `name_ballot`, the ballot +name, and `name`, the full name; both are read, as the forms `ballot` +and `full`. So every election gives its ballot names, and PRN15 its full +names too, the population with the most `BIN` and `BINTI`. + +The shapes it holds and the other corpora barely do: Malay names joined +by `BIN`, `BINTI`, `B.`, `BT` and `@` (an alias, `X @ Y`); Indian names +joined by `A/L` and `A/P`; Iban and other Sarawak names joined by +`ANAK`; `MD` and `MOHD` as given names; honorifics opening a ballot name +(`USTAZ`, `CIKGU`, `DR`, `HJ`, `KAPT (B)`); and Chinese names written +family first in capitals, beside a Western given name or not (#1467, +#1468, #1164, #1183, #1179). Each record keeps the candidate's +`ethnicity` as the file writes it, the group config_diff.py --group +keeps (GE12 to GE15 write `bumiputera`, which takes in Sabah's and +Sarawak's peoples beside the Malays, and PRN15, whose six states are all +in the peninsula, writes `malay`; `chinese`, `indian` and `other` in +all), and its `election`. + +A record is one distinct spelling within an election and ethnicity: a +candidate standing in two seats of one election is one record, and a +full name equal to its ballot name is recorded once, as the ballot +name. It holds no fields, so it is a snapshot.py --local population, +not a local_agreement.py one. + +The repository is licensed under the GPL-3.0; the names are candidates' +as the Election Commission published them. They are cached, never +committed or shipped, and what reaches the repository is counts and +made-up names. +""" +from __future__ import annotations + +import csv +import hashlib +import io +import sys +from collections import Counter +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +from local_core import Fetched, _pinned, _refuse_past, _retried + + +MY = "my-candidates" +#: The commit the files are read from: the repository's last, of +#: 2023-08-13, when read on 2026-11-19, so a pin both names the data +#: exactly and refuses a file cut in transit or changed upstream. +MY_COMMIT = "b20331b0aef7efa4ab3ad6df83b188663771d9eb" +MY_DATE = "2023-08-13" +MY_URL = ("https://raw.githubusercontent.com/Thevesh/analysis-election-msia/" + "{commit}/data/{file}") + + +@dataclass(frozen=True) +class File: + """One election's file: its name, sha256 and rows at MY_COMMIT, its + header exactly, and the column read for each form.""" + election: str + file: str + sha256: str + rows: int + header: tuple[str, ...] + forms: tuple[tuple[str, str], ...] + + +_GE_HEADER = ("state", "parlimen", "ballot_order", "name", "age", "sex", "ethnicity", + "party", "votes", "result", "result_desc") +#: The files read, in order. A form is ("ballot", column) or ("full", +#: column); the module docstring says why each column is the one read. +FILES = ( + File("ge12", "candidates_ge12.csv", + "592ab00dbf96fc643ccbfd5c0715ed5b6ae55470e263cd2a13dff268bc60980f", 480, + _GE_HEADER, (("ballot", "name"),)), + File("ge13", "candidates_ge13.csv", + "dee0046e7e47210f93893c9749b968420da9e5baca21b07a5ad57eab14d7fc4e", 579, + _GE_HEADER, (("ballot", "name"),)), + File("ge14", "candidates_ge14.csv", + "4a8c0c4db659c572522b701e60b80c9d945f23e439a657c00fe4e55dda03fb8e", 687, + _GE_HEADER, (("ballot", "name"),)), + File("ge15", "candidates_ge15.csv", + "6eef7ef032a64bd3492812b3971ca0e2a4204cb71d72e8daef0559146b4c0204", 945, + ("state", "parlimen", "ballot_order", "name", "name_display", "age", "sex", + "ethnicity", "party", "votes", "result", "result_desc", "new_mp"), + (("ballot", "name_display"),)), + File("prn15", "candidates_prn15.csv", + "1669a1e78bbdc67347f549fa091032d94071a5cc207ccaef1c2bc5db12ef5c0c", 570, + ("state", "parlimen", "dun", "ballot_order_x", "name", "name_ballot", "party", + "acronym", "age", "sex", "ethnicity", "ballot_order_y", "votes", "votes_perc", + "result"), + (("ballot", "name_ballot"), ("full", "name"))), +) +#: How a record is read from the files (_read): a change to what is kept +#: or how a spelling is read bumps it, and a corpus read by another +#: version is refused on load (check_my). +MY_READ_VERSION = 1 +#: The share of a file's rows that may be another number of fields than +#: its header before the file is refused: none was on 2026-11-19. +MY_MAX_BAD = 1 / 100 +#: The share of a file's rows that may have an empty name in a column +#: read (a row counted once, however many) before the file is refused: +#: none had on 2026-11-19. +MY_MAX_NAMELESS = 1 / 100 + + +def _sha256_checked(file: File) -> Callable[[bytes], bytes]: + """A reader returning a body that is `file`'s pinned bytes, else + raising ValueError, which _retried takes for a body cut short.""" + def read(body: bytes) -> bytes: + digest = hashlib.sha256(body).hexdigest() + if digest != file.sha256: + raise ValueError(f"{file.file}'s sha256 is {digest}, not the pinned {file.sha256}") + return body + return read + + +def _read(file: File, text: str) -> tuple[list[dict[str, str]], Counter[str]]: + """The records of one election's file, which must have exactly its + header and its rows, and end with a whole row.""" + rows = list(csv.reader(io.StringIO(text, newline=""))) + header = tuple(rows[0]) if rows else () + if header != file.header: + raise ValueError(f"{file.file}'s header is not the {len(file.header)} columns " + f"this reads: {', '.join(header)}") + # csv returns a body cut inside its last row as a short last row, + # which the count below would take for a whole one (local_ukec's + # _ukec_rows says so too). A cut only shortens a row, so a long last + # row is left to the malformed share. Every file ended with a line + # break on 2026-11-19. + if not text.endswith("\n") or len(rows) > 1 and len(rows[-1]) < len(header): + raise ValueError(f"{file.file} ends inside a row: cut short; fetch again") + body = rows[1:] + if len(body) != file.rows: + raise ValueError(f"{file.file} holds {len(body):,} rows where {file.rows:,} are " + f"pinned: a cut or changed file; fetch again") + ethnicity_at = header.index("ethnicity") + columns = [(form, header.index(column)) for form, column in file.forms] + counts: Counter[str] = Counter() + records: list[dict[str, str]] = [] + seen: set[tuple[str, str]] = set() + for row in body: + if len(row) != len(header): + counts["malformed"] += 1 + continue + ethnicity = row[ethnicity_at].strip() + if any(not row[at].strip() for _, at in columns): + counts["nameless"] += 1 + for form, at in columns: + name = " ".join(row[at].split()) + if not name: + continue + if (name, ethnicity) in seen: + counts["repeated"] += 1 + continue + seen.add((name, ethnicity)) + records.append({"name": name, "election": file.election, "form": form, + "ethnicity": ethnicity}) + counts[form] += 1 + of = f"rows of {file.file}" + _refuse_past([(counts["malformed"], len(body), MY_MAX_BAD, + f"{of} are not {len(header)} fields"), + (counts["nameless"], len(body), MY_MAX_NAMELESS, + f"{of} have an empty name")], + "the file is not the one this reads") + return records, counts + + +def fetch_my() -> Fetched: + """Every distinct spelling of every candidate in FILES, one record + each, with its election, form and ethnicity. A file other than the + pinned one (retried first, as a body cut short), of another header + or row count, or not ending with a whole row, is refused, as is one + past MY_MAX_BAD rows of another width or MY_MAX_NAMELESS rows with an + empty name. The data date is the pinned commit's.""" + records: list[dict[str, str]] = [] + elections: dict[str, dict[str, int]] = {} + for file in FILES: + url = MY_URL.format(commit=MY_COMMIT, file=file.file) + print(f"downloading {url} ...", file=sys.stderr) + body = _retried(url, _sha256_checked(file), 0) + read, counts = _read(file, body.decode("utf-8")) + records += read + elections[file.election] = {"rows": file.rows, **counts} + detail: dict[str, Any] = {"commit": MY_COMMIT, "read_version": MY_READ_VERSION, + "elections": elections} + return Fetched(records, MY_DATE, detail) + + +_check_commit = _pinned("commit", lambda: MY_COMMIT, + "the corpus was read at commit {held}, and this tool reads {wanted}") +_check_read = _pinned("read_version", lambda: MY_READ_VERSION, + "the corpus was read by version {held} of _read, and this tool is " + "version {wanted}") + + +def check_my(meta: dict[str, Any]) -> str: + """Why a corpus read at another MY_COMMIT or by another + MY_READ_VERSION is refused, or "".""" + return _check_commit(meta) or _check_read(meta) diff --git a/tools/differential/local_parliaments.py b/tools/differential/local_parliaments.py index 332568e13..fab9df31a 100644 --- a/tools/differential/local_parliaments.py +++ b/tools/differential/local_parliaments.py @@ -2,7 +2,7 @@ parliaments, as each parliament writes their names. opensanctions-parliaments -- the members OpenSanctions' crawlers read -off twenty-three national chambers' own websites, and the regional heads +off twenty-eight national chambers' own websites, and the regional heads Indonesia elected in 2018 (DATASETS), each dataset's `targets.simple.csv`: a row per person, the `name` column as the parliament writes it and `aliases` the other forms the crawler @@ -25,11 +25,20 @@ of given, father's and grandfather's name; Korean names in Hangul and Hanja, and Hebrew ones; and Mongolian names in Cyrillic, the father's name first (`mn_parliament`, added 2026-11-12: 126 members, each written -once). Issues #1186 to #1192 were +once). Five chambers were added 2026-11-19 (#1465): Malaysia's Dewan +Rakyat (`my_parliament`, 276 members, 16 of them with an alias writing +the `bin` or `a/l` the name leaves out), Pakistan's National Assembly +and Senate (`pk_na_members`, `pk_senate_members`, 427 members, each +written once), Egypt's House of Representatives +(`eg_house_representatives`, 594 members in Arabic script, nearly every +one written twice, a short name and the full chain of father's and +grandfather's names, `X الدين` and `X الله` among them) and Somalia's +House of the People (`so_house_people`, 275 members, 35 with an alias +holding a nickname in brackets). Issues #1186 to #1192 were read from it, in a 2026-11-07/08 check of the shipped packs; the Indonesian datasets measure #1205 and #1206, Ethiopia's #1203, Korea's #1213, #1215 and #1216, Israel's #1209, #1210 and #1211, and -Mongolia's #1237. +Mongolia's #1237, and Malaysia's and Egypt's #1468, #1072 and #1464. A record is one distinct spelling of one member: the spelling (`name`), the member (`entity`, the dataset and OpenSanctions' id, so a member of @@ -71,7 +80,9 @@ "si_dz_rs", "sk_nrsr_poslanci", "pt_parliament", "in_sansad", "ua_rada", "by_council_republic", "ru_duma_deputies", "ru_federation_council", "id_dpr", "id_dpd", "id_regional_2018", "et_hopr", - "kr_assembly", "il_knesset_members", "mn_parliament") + "kr_assembly", "il_knesset_members", "mn_parliament", "my_parliament", + "pk_na_members", "pk_senate_members", "eg_house_representatives", + "so_house_people") INDEX_URL = "https://data.opensanctions.org/datasets/latest/{dataset}/index.json" RESOURCE = "targets.simple.csv" #: The columns read; the file holds others (birth dates, contacts), and