diff --git a/AGENTS.md b/AGENTS.md index e9e3e7d19..2fcc4b860 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -154,12 +154,18 @@ uv run sphinx-build -b html docs dist/docs # "Reads:". That is checkable, so check it rather than reading it: # compare it against grep -oE '\b(policy|lexicon|lex)(\._sets)?\.[a-z][a-z_]*' # on the module (a vocabulary set is read as `lexicon._sets.titles` -# since 4i-a, and a Reads: line names it `Lexicon.titles`). A Reads: -# line may name a set of fields at once: _classify's "every Lexicon -# vocabulary field except surnames and honorific_tails, ... and -# given_names" stands for every `_lexicon._VOCAB_FIELDS` entry but -# those three, most read in the module (the grep lists them) and the -# rest through _vocab's helpers, so check what it leaves out +# since 4i-a, and a Reads: line names it `Lexicon.titles`). The grep +# sees only reads spelled in the module itself: not a read through a +# `sets = lexicon._sets` alias (`sets.titles`; 20 such bindings in +# _pipeline/ on 2026-11-16) and not a read a stage makes through a +# helper in _vocab or _pieces (assign reads the suffix sets that way, +# through is_suffix_lenient). `uv run python tools/stage_reads.py` +# sees both: it runs every tests/v2/cases.py row through the stages +# with the Lexicon and Policy wrapped to record each read, and lists +# per stage what was read and a text that read it (`--stage classify` +# for one); it cannot see a read no row reaches. A Reads: line may +# name a set of fields at once, as _classify's does by naming the +# fields it leaves out, so check what it leaves out against the trace # - tests/v2/cases.py notes, which explain why a row lands where it does # - docs/design/rules/, decisions/ and mechanisms.md -- READ, don't # grep: the excerpt and example tests catch citation and example drift, @@ -204,7 +210,10 @@ uv run sphinx-build -b html docs dist/docs # gh api -X PATCH repos/derek73/python-nameparser/milestones/$MILESTONE -f state=closed # gh api -X POST repos/derek73/python-nameparser/milestones -f title="Next Release" # 8. Set DEFAULT_BASELINE in tools/differential/compare.py to the version -# just released, so a bare compare.py measures against it. +# just released, so a bare compare.py measures against it. This runs +# on the branch released from, so a release cut from a maintenance +# branch (3.0.1 from 3.0.x) needs it applied on master too: master's +# stayed on 3.0.0 until the 3.1 sweep. # 9. Open the next cycle's VERSION: bump VERSION in nameparser/_version.py to # the minor now being worked, and set PRE_RELEASE = 'dev'. The tree then says # what it is building rather than what it last shipped -- docs/conf.py reads @@ -279,7 +288,7 @@ The compiled sets, read by `Lexicon` (mostly as the `_sets` field of the same na The 2.0 rewrite landed as underscore-private modules beside the v1 code, which 2.0 and then 3.0 deleted. These conventions apply to all of it. The design record (rationale, settled-decision logs, dated amendments) is docs/design/: `nameparser-2.0-rfc.md`, the rules, the decisions entries and mechanisms.md; this section is the enforceable subset. **A commit that establishes or amends one of these conventions must update this section in the same commit** — grep-driven staleness sweeps miss paraphrased prose (see Workflow above), so write-time maintenance is the mechanism, audits are the backstop. - **Module layout**: every module is underscore-private (`_types.py`, `_lexicon.py`, `_policy.py`, `_locale.py`, `_render.py`, `_reading_index.py`, `_pipeline/`, `_parser.py`, and `_match.py`, which holds name matching: `Matching`, the settings object `Parser.matching()` builds, and its result types, and `_suggest.py`, the group suggester: `Parser.suggest` tallies one vote per name from per-name signals and returns a `Suggestion`, decided under the thresholds in the decisions file group-suggestion). The public import surface is exactly `nameparser` and `nameparser.locales` (the vocabulary's compiled sets are private since 3.0, #1007, the Korean surname list since #1077 (2.8.2 warning of it, #1076), and `regexes` went with #1008; `tests/v2/test_layering.py` refuses a public module in `nameparser/config/`); `nameparser/__init__.py` holds re-exports and `__all__` only — no logic. -- **Layering is enforced by `tests/v2/test_layering.py`** (exact-module matching; `if TYPE_CHECKING:` imports don't count): `_types` imports nothing internal at module level — its rendering delegates import `_render`, and `ParsedName.matches` `_parser`, at call time; `_lexicon` and `_policy` sit above `_types` independently (`_lexicon` may import `nameparser.config.*` DATA modules, e.g. `config/_ko_surnames.py` and `config/_compiled.py`, and `_reading_index` at call time only, to compile a configured lexicon's readings, since `tools/vocab/build.py` loads it by path, 3.0's 4i-b); `_reading_index` imports nothing internal at module level and the index, `config/_index.py`, at call time, since `tools/vocab/build.py` loads it by path; `_locale` sits on `_lexicon`+`_policy` (plus `_types` for the shared pickle mixin, and `config/_rules.py` at call time, in `rules_patch`); `_render` imports `_types`, `_lexicon` (for `Lexicon.default()` and `_normalize`) and `_policy` (for the scripts that write no initials); `_match` imports `_types`, `_policy` (for `Policy()`, which its repr compares a parser's policy with), `_lexicon` (for `_normalize`, which tells a hyphen half that is a listed particle by `lexicon._sets.particles`, and `Lexicon.default()`, which the repr compares a parser's lexicon with) and `_pipeline/_vocab` (for `_HYPHEN_CHARS`, rules/O6's hyphens, each of which the match reads as the hyphen-minus, `_HYPHENS`, the pattern it cuts a word at them by, #1264, and `in_initialless_script`, the scripts that write no initials), `_parser` at call time only, in `Matching`'s constructor, which requires a `Parser`, and its repr, which tells a `Parser` from a subclass, and `Parser` under `TYPE_CHECKING` for its annotations; `_suggest` imports `_types`, `_policy`, `_lexicon` (the particles, the titles and `_normalize`), the pipeline's predicates (`_pipeline/_vocab`'s patronymic, title, suffix, numeral and capitals-word tests, `_pipeline/_state`'s commas, `_pipeline/_post_rules`'s `_listed_suffix`, rules/O9's credential and numeral test) and `config/_order_names.py`, imports `_parser` at call time, in `Suggestion.__post_init__`, to check that the base is a `Parser`, and names `Parser` under `TYPE_CHECKING` for its annotations; `_pipeline/*` imports `_types`+`_lexicon`+`_policy` plus in-package `_pipeline` helpers, `_assemble` also `_reading_index`, for the kinds `Reading.languages` matches (`CATEGORY`; the files themselves it reads through `Lexicon._files`, 4i-d; `_vocab` imported it in 3.0's 4b and 4c for a listed suffix word's kind and a patronymic particle's, which since 4i-b the lexicon compiles into `_sets`); `_parser` sits on everything except `_render`, `_match` at call time only, in `Parser.matching()`, `_suggest` at call time only, in `Parser.suggest()`, and `_reading_index` at call time only, to validate a choice's tags and move the case masks it moves (the choice itself compiles in `_lexicon._built`); `__main__` imports only the public package; locale pack modules (`locales/*.py`) import `_locale`/`_lexicon`/`_policy`/`_types` only (`_types` joined the list in #272 — `locales/ja.py`'s segmenter factory constructs a `Segmentation`), and the `locales/__init__` additionally lazy-imports its packs (PEP 562). Extend the test's `ALLOWED` table when adding a module. +- **Layering is enforced by `tests/v2/test_layering.py`** (exact-module matching; `if TYPE_CHECKING:` imports don't count): `_types` imports nothing internal at module level — its rendering delegates import `_render`, and `ParsedName.matches` `_parser`, at call time; `_lexicon` and `_policy` sit above `_types` independently (`_lexicon` may import `nameparser.config.*` DATA modules, e.g. `config/_ko_surnames.py` and `config/_compiled.py`, and `_reading_index` at call time only, to compile a configured lexicon's readings, since `tools/vocab/build.py` loads it by path, 3.0's 4i-b); `_reading_index` imports nothing internal at module level and the index, `config/_index.py`, at call time, since `tools/vocab/build.py` loads it by path; `_locale` sits on `_lexicon`+`_policy` (plus `_types` for the shared pickle mixin, and `config/_rules.py` at call time, in `rules_patch`); `_render` imports `_types`, `_lexicon` (for `Lexicon.default()` and `_normalize`) and `_policy` (for the scripts that write no initials); `_match` imports `_types`, `_policy` (for `Policy()`, which its repr compares a parser's policy with), `_lexicon` (for `_normalize`, which tells a hyphen half that is a listed particle by `lexicon._sets.particles`, and `Lexicon.default()`, which the repr compares a parser's lexicon with) and `_pipeline/_vocab` (for `_HYPHEN_CHARS`, rules/O6's hyphens, each of which the match reads as the hyphen-minus, `_HYPHENS`, the pattern it cuts a word at them by, #1264, and `in_initialless_script`, the scripts that write no initials), `_parser` at call time only, in `Matching`'s constructor, which requires a `Parser`, and its repr, which tells a `Parser` from a subclass, and `Parser` under `TYPE_CHECKING` for its annotations; `_suggest` imports `_types`, `_policy`, `_lexicon` (the particles, the titles and `_normalize`), the pipeline's predicates (`_pipeline/_vocab`'s patronymic, title, suffix, numeral and capitals-word tests, `_pipeline/_state`'s commas, `_pipeline/_post_rules`'s `_listed_suffix`, rules/O9's credential and numeral test) and `config/_order_names.py`, imports `_parser` at call time, in `Suggestion.__post_init__`, to check that the base is a `Parser`, and names `Parser` under `TYPE_CHECKING` for its annotations; `_pipeline/*` imports `_types`+`_lexicon`+`_policy` plus in-package `_pipeline` helpers, `_assemble` also `_reading_index`, for the kinds `Reading.languages` matches (`CATEGORY`; the files themselves it reads through `Lexicon._files`, 4i-d; `_vocab` imported it in 3.0's 4b and 4c for a listed suffix word's kind and a patronymic particle's, which since 4i-b the lexicon compiles into `_sets`); `_parser` sits on everything except `_render`, `_match` at call time only, in `Parser.matching()`, `_suggest` at call time only, in `Parser.suggest()`, and `_reading_index` at call time only, to validate a choice's tags and move the case masks it moves (the choice itself compiles in `_lexicon._built`); `__main__` imports only the public package; every locale pack module (`locales/*.py`) imports `_locale`/`_lexicon`/`_policy`/`_types` and its own private data modules in `locales/` only (`es.py` imports `_es_given_names.py`, `es_ar.py` `_es_ar_given_names.py`; `_types` joined the list in #272 — `locales/ja.py`'s segmenter factory constructs a `Segmentation`), a data module (a leading underscore) imports nothing internal, and the `locales/__init__` additionally lazy-imports its packs (PEP 562). No pack is keyed by hand: the test's `_locale_rules()` holds every file in `locales/` to that rule, a relative import read by the absolute name it resolves to, so a new pack is checked from its first commit. Extend the test's `ALLOWED` table when adding any other module; its completeness checks fail on a `_pipeline/` module it does not key and on a `locales/` module no rule reaches. - **Canonical field order** — the seven roles in `Role` enum declaration order, defined once and derived everywhere (properties, `as_dict`, reprs, `comparison_key`). Never restate the order literally. `Role` is a `StrEnum`: members compare as their field-name strings, and `tokens_for()` coerces strings via `_coerce_enum`. - **Method organization**, fixed section order in every class: fields + `__post_init__` validation → alternative constructors → dunders (construction/equality → protocol → operators) → properties → public methods by concern (access → editing → comparison → rendering delegates) → private helpers last, except a helper serving exactly one section may sit at that section's head. - **Validation is eager and fail-loud**: every `raise` states the offending value, the expected form, and the fix. Exception taxonomy: wrong type — including wrong element type inside a collection, bare `str` where an iterable of strings is expected, or a `Mapping` where a plain iterable is expected — raises `TypeError`; well-typed but unacceptable values raise `ValueError`; failed enum lookups stay `ValueError` for any input (stdlib `EnumType` precedent). **When the message hands the reader code to paste, that code has to survive a type checker, and then RUN** — nameparser ships `py.typed`, and a placeholder can type-check and still raise: the 2.4 release sweep's first fix to the `capitalization_exceptions` hint offered `('key', 'Value')`, which passes mypy and fails #459's mask check, so `test_add_capitalization_exceptions_raises_pointing_at_replace` now executes the offered code. #337's segmenterless warning offered `Policy(segment_scripts=())`, an `arg-type` error, because these fields are annotated with what they STORE rather than everything the constructor accepts. Prefer the `frozenset()` / `()` spellings in messages and docstrings, and pin the offered spelling in a test — the warning tests matched on `ja_segmenter` and never checked the actionable half of the message. **A warning emitted in `Parser.__post_init__` needs `parser_for` to re-emit it from its own frame** (the `catch_warnings(record=True)` block at its return): `__post_init__`'s `stacklevel` is sized for direct `Parser(...)` construction, and through `parser_for`'s extra frame the default one-line rendering attributes the warning to the library's own `return Parser(...)` — the exact call the message tells the user to change becomes invisible. No single stacklevel serves both entry points; a new construction warning gets the re-emission for free, but a new CONSTRUCTION SITE for `Parser` inside this package needs its own re-emission or its callers get library-attributed warnings (#337 review). @@ -289,8 +298,8 @@ The 2.0 rewrite landed as underscore-private modules beside the v1 code, which 2 - **Parser owns config-dependent conveniences**: `Parser.matches`/`Parser.capitalized`/`Parser.revise` exist because the `ParsedName` equivalents fall back to DEFAULT config for str/omitted arguments (documented loudly in both docstrings). `revise` harvests tokens from a full sub-parse of each replacement value (tags kept minus `FOLDED_TAG`, roles forced, the R1 entry pass `suffix_entries` re-run over the forced state so a suffix value's entries follow its own commas, ambiguities discarded); the merge tail is shared with `replace()` via `ParsedName._with_field_tokens`. `Parser.capitalized` delegates through `name.capitalized(self.lexicon)` specifically so `_parser` never imports `_render` — keep it that way. - **A reading is of one word, save a birth marker and a title addressing the given name** (the build's check 8, which `_lexicon._make_edit` runs on every `add` and RAISES on, since a reading is now a caller's statement the compile can refuse as the build does: 3.0's 4i-b). The two lists, `surnames` and `given_names`, and `capitalization_exceptions` keys still WARN on a multi-word entry (`_normset`/`_normpairs` via `_warn_at_caller`, UserWarning, never a raise — an inert entry produces nothing). The default vocabulary and every locale pack must stay warning-free (`test_default_lexicon_builds_warning_free`, `test_pack_vocabulary_entries_are_single_words`). - **Invariants guard harm, not no-ops**: add a constructor check when violating it produces a *wrong parse*, not when it produces *nothing*. A false positive costs a working configuration; a true positive on an inert condition costs the user nothing, so that trade is never worth taking. Since 3.0's 4i-b a `Lexicon` compiles from readings, which hold the 2.x marker-over-base relations by construction; the checks a caller's edit reaches are the build's checks 3 (a kind and its properties, `may_be_initial` on a single cased letter alone), 4 (one suffix kind per word), 8 (a phrase), 9 (a bound given name that is a particle has a `given` reading) and 11's agnomen clause (an agnomen has a name reading), in `_lexicon._make_edit` and `_check_pool`, which `_lexicon._built` runs again under a choice of languages, refusing a caller's reading that clashes with one the choice turns on and naming the edit, each raising with the call that fixes it, because each is a wrong parse. A given-addressing title run the parse can never build is not checked, because an unreachable entry is simply never consulted (see Gotchas). Before adding one, construct the config it forbids and check what actually breaks. **Between raise and silence sits the construction-time `UserWarning`**, for a gap that is statically decidable, harmless to SOME deliberate caller, and indistinguishable-from-working for everyone else: the segmenterless activation (#337 — `parser_for(locales.JA)` without a segmenter behaved exactly like a working parser minus the feature) warns rather than raises because the segmentation-inert JA registration is itself a pinned property, and a warning is filterable by the caller who wants exactly that. The message must carry every applicable remedy and no inapplicable one (the `ja_segmenter` hint fires only when a Japanese script is among the dead ones). Test fuzzers that legitimately construct such configs suppress the warning by MESSAGE, never by category — a blanket `UserWarning` ignore would mask the next construction diagnostic (`_quiet_parser` in `tests/v2/test_properties.py` is the pattern). -- **Reprs are bounded**: render which fields deviate from a named baseline and by how much, never contents (`Lexicon(default + titles: +2)`). `PolicyPatch`'s repr shows only set (non-UNSET) fields; `_order_repr` must never raise even on an unvalidated patch's garbage `name_order` (PolicyPatch defers validation to apply time); the sweep test in `tests/v2/test_reprs.py` pins that no config repr leaks the UNSET sentinel. -- **Every pipeline stage is one module holding one public function of the same name** (`_tokenize.py`/`tokenize`), with the exceptions named where they stand — `_group.py`'s `marker_run_length`, a shared predicate (mechanisms.md#ONE-PREDICATE-PER-QUESTION), and since #511 `_post_rules.py`'s `suffix_entries`, the R1 entry pass as a function, because `Parser.revise` runs that one pass over a forced-role sub-parse and a stage's tail cannot be called on its own — **and its module docstring declares the contract in three labelled lines**: `Consumes:` what it takes from `ParseState`, `Produces:` what it hands back, `Reads:` which `Policy`/`Lexicon` fields it consults. `Reads:` is the load-bearing one — it makes "which stage do I touch for this feature?" a grep rather than a read-through. A `Reads:` line names a vocabulary set as `Lexicon.`, and every library module but `_lexicon` reads it as `lexicon._sets.` (`_lexicon._LexiconSets`, #754's 4i-a), never off the public field, `surnames` and `given_names` included though they stay public, which let 4i-b make the other twenty internal without touching a reader; `tests/v2/test_layering.py` refuses a direct read, field by field, in the library and in every tool. The authority for the stage set is `_pipeline/__init__.py`'s `STAGES` (eight, and not public API) with the field-ownership map in `ParseState`'s docstring, pinned by `tests/v2/pipeline/test_state.py`; NOT the rules, which are implementation-free by their own preamble and whose `implemented:` names modules honoring a rule rather than stages. A `_pipeline/` module that is not a stage says so in its first line instead (`_assemble.py`: "Not a stage: …", with a `Reads:` line all the same, since it reads `Policy` and `Lexicon` fields too (its `Reads:` line lists them)), so absence of the three lines is a claim about the module rather than an oversight. Provenance: §5 of the 2026-07-11 conventions spec, recorded here 2026-08-16. +- **Reprs are bounded**: render which fields deviate from a named baseline and by how much, never contents (`Lexicon(default + title: +2)`). `PolicyPatch`'s repr shows only set (non-UNSET) fields; `_order_repr` must never raise even on an unvalidated patch's garbage `name_order` (PolicyPatch defers validation to apply time); the sweep test in `tests/v2/test_reprs.py` pins that no config repr leaks the UNSET sentinel. +- **Every pipeline stage is one module holding one public function of the same name** (`_tokenize.py`/`tokenize`), with the exceptions named where they stand — `_group.py`'s `marker_run_length`, a shared predicate (mechanisms.md#ONE-PREDICATE-PER-QUESTION), and since #511 `_post_rules.py`'s `suffix_entries`, the R1 entry pass as a function, because `Parser.revise` runs that one pass over a forced-role sub-parse and a stage's tail cannot be called on its own — **and its module docstring declares the contract in three labelled lines**: `Consumes:` what it takes from `ParseState`, `Produces:` what it hands back, `Reads:` which `Policy`/`Lexicon` fields it consults. `Reads:` is the load-bearing one — it makes "which stage do I touch for this feature?" a grep rather than a read-through. A `Reads:` line names a vocabulary set as `Lexicon.`, and every library module but `_lexicon` reads it as `lexicon._sets.` (`_lexicon._LexiconSets`, #754's 4i-a), never off the public field, `surnames` and `given_names` included though they stay public, which let 4i-b make the other twenty internal without touching a reader; `tests/v2/test_layering.py` refuses a direct read, field by field, in the library and in every tool. The authority for the stage set is `_pipeline/__init__.py`'s `STAGES` (eight, and not public API) with the field-ownership map in `ParseState`'s docstring, pinned by `tests/v2/pipeline/test_state.py`; NOT the rules, which are implementation-free by their own preamble and whose `implemented:` names modules honoring a rule rather than stages. A `_pipeline/` module that is not a stage says what it is in its first line instead (`_assemble.py` and `_comma.py`: "Not a stage: …"; `_vocab.py`, `_pieces.py` and `_state.py` name themselves shared predicates or the pipeline's state), `_assemble.py` with a `Reads:` line all the same, since it reads `Policy` and `Lexicon` fields too (its `Reads:` line lists them), so absence of the three lines is a claim about the module rather than an oversight. Provenance: §5 of the 2026-07-11 conventions spec, recorded here 2026-08-16. - **Frames are a budget for hot and scaling paths; everywhere else, prefer the shared predicate.** The parser's cost is counted in Python frames (`sys.setprofile` "call" events — deterministic and load-immune, which is why #475 chose them over wall-clock timing), but one frame is small: measured 2026-09-28 on py3.11, a trivial call costs about 13 ns against 40–80 µs for a whole parse, so one frame per parse is roughly 0.03% of it. What the budget exists to catch is how a cost SCALES and how it ACCUMULATES, so weigh an extra frame by four questions, in order. (1) Does it multiply with the input — per token, per member, per pair? Then it matters, and a hand-inlined fast path can earn its place (the inline tag tests ahead of `_pieces.starts_a_credential_run` in its loops, each a necessary half of the predicate so nothing can drift; `_vocab.run_word_fold` was the measured example until #613 deleted the run test it served). Folding a copy into a shared helper is where such a pre-check gets lost: #617 replaced `_comma._title_chains`, whose loop tested the conjunction tag inline, with a call into group's loop, which asks `is_conj_piece` per piece, and every family-comma parse paid two frames per word of the part (`Smith, John` +2) while the reference row fell -- review caught it; the fix gates the call on the tag walk the caller already makes, and `test_a_comma_part_with_no_free_connective_skips_the_join` holds it. Count a comma name, not only the reference row, when a fold touches the comma path. (2) How many names pay it — every parse, where plain names like `Smith, John` must keep their cost, or only a rare shape? (3) Does it move an enforced guard — the ±2% reference band in `test_benchmark.py` (`_CALL_BASELINE`, decisions/parse-cost) or a scaling ratio? (4) What does the inline alternative cost to maintain? A hand copy of a predicate that can drift is the defect class mechanisms.md#ONE-PREDICATE-PER-QUESTION names, and it compounds; a NARROWER question stated exactly is not a copy and may stay inline on that ground alone. A constant frame on a rare shape that no guard sees loses to readability: #544's cleanup declined `is_title_piece` for one frame on comma credential runs (24 ns a parse, no guard moved), a stricter call than this rule asks for; by this rule the inline test is still right, but because it asks the narrower question (a lone word in both vocabularies), not because of the frame. The converse holds too: the frame counter cannot see C-level work (`x in some_list`, slices, string concatenation), so "no new frames" is not "no new cost" — #553's quadratic was a list membership test inside a loop, invisible to every frame guard, and #1036's a slice assignment shifting the piece list once per merge, which a dev machine's clock read as linear and only CI's runners did not (`_ShiftCountingList` in `tests/v2/test_benchmark.py` counts those shifts now). - **A claim about WHICH STAGE or WHICH LAYER does something is checkable — check it before writing it.** The pipeline is eight stages with a written ownership map (`ParseState`'s docstring, pinned by `tests/v2/pipeline/test_state.py`), and `parse(s).tokens` prints every token's role and tags, so "extract assigns this", "classify never sees that", "group consumes it" each have a one-command answer. #329's prose claimed delimited maiden content is *"claimed whole before classify has tagged anything inside it"*; measured, `classify` tags the marker fine and only the CONSUMING is missing, because `_group`'s rule walks `pieces` and a token that already carries a role is not in `pieces`. Two different mechanisms, one plausible sentence covering both. That single claim then shipped SIX times across three correction rounds, which is the part worth internalizing: **when a mechanism claim turns out wrong, sweep for where else you wrote it, and sweep again at the END of the change over the words the change itself just added.** Prose density here means one idea lives in a docstring, a case note, a release-log entry and this file at once; the implementer working against a wrong mechanism is the person most likely to restate it; and rewriting a mechanism claim is writing one, so the correction earns the same one-command check as the original — two of the six instances were fresh errors introduced by the sentence fixing the previous one. **Adjacency is the trap.** The claim that feels already-known is the one about the neighbouring stage or the neighbouring layer: one comment block in the 2.x `tests/v2/test_facade_cases.py` got the exception type, the raising layer, the skip mechanism, the count of skipped rows, and which row was blocked all wrong at once — every one a claim about `_config_shim` versus real 1.4.0, written from reasoning, in the file whose whole job is translating between them. What finally held was not better prose but moving the claim into a test (`_CORE_ONLY_IDS`, deleted with the facade in 3.0), which cannot be wrong the way a sentence can. - **Typing/docs**: `from __future__ import annotations`; `frozen=True, slots=True` on every public dataclass; strict-profile mypy flags via per-module overrides in pyproject (`strict = true` itself is not valid per-module). Docstrings state contracts in prose with **no doctest blocks** — `--doctest-modules` makes every example a test; behavior examples go to unit tests per the lean-docs rule. **Document the positive direction of a partial property**: "a non-empty `ambiguities` is a signal to act on" is checkable, while "an empty one means no fork occurred" is a universal negative needing exhaustive verification -- that claim was written twice and falsified twice, at sites the author had not audited. @@ -331,7 +340,7 @@ The 2.0 rewrite landed as underscore-private modules beside the v1 code, which 2 **Titles permanently shadow first names — be conservative** — any word in `TITLES` is always consumed as a title and can never be parsed as a first name. `"Dean"` is the canonical example: it's a common academic title *and* a common given name, so it is not in `TITLES` but in `TITLES_AMBIGUOUS`, a title only inside a title phrase (`Dean of Students`, `Associate Dean`; rules/H9, #752 phase 2i), and users who need it everywhere add it to a `Lexicon` of their own. A title that is also a given name now has that machinery: a `given` reading on the word moves it there, decided word by word in measured batches (decisions/vocabulary-model's 2026-10-24 order). A rule that reads a title by its neighbours in the title run meets more phrase shapes than the qualifier-then-head it was designed on: the object of a connective (`President of the United States`, `the Queen's Bench`, whose `united`, `states` and `bench` are modifiers with no head after them), a head before `of` (`Member of Parliament`), and a qualifier written after its head (`Chargé d'Affaires`, `Princess Royal`). Phase 2i's first build, "a modifier needs a head title after it", broke `President of the United States`, `Chargé d'Affaires` and the committed `Queen's Bench` row, found by the case table and the committed corpora, and then read a modifier ENDING the name out of H5's trailing run (`Jane Smith Vice.`), found by the design-docs review; put each shape, and the trailing position, in the grid of any such rule. Before adding a word to `TITLES`, ask: "Could this plausibly be someone's given name in any culture?" If yes, don't add it globally; it belongs in a caller-supplied `Lexicon` instead. This same caution applies to international honorifics — `Frau` is a first name in some contexts, and `Prince` and `Sheikh` were titles until 2.7 gave them a `given` reading, which moved them to `TITLES_AMBIGUOUS` (rules/H9). It also applies to any prefix sub-set gated on "never a first name": obscure-looking foreign particles are surprisingly often real given names — `Von` (Von Miller), `Vander` (Brazilian, also the Arcane character). When unsure, exclude — a missing member just means that name isn't auto-handled, whereas a wrong member misparses a real person. The decided exception is a word borne as a name only RARELY in the leading position — mostly a surname written last (`graf`, `greve`, `knight`), a few with small given-name or surname-first counts (`herra`, `hrabia`): the title claim acts only in front, so it ships, and a name that begins with it (`Greve Anna`, `Herra Wijaya` → title) is the accepted cost. That is a judgment by incidence, made per word, with the counts taken recorded on the word's entry in `nameparser/vocab/` (herra's, hrabia's; graf, which predates #606, and greve and knight, which #606 proposed, carry none) and the class in `decisions/salutation-titles` (rules/H1's Accepted clause states the cost), not a rule a sweep can apply: a word that commonly leads a real name (Vietnamese `Ông`, the given names `thiru`, `puan`) is still out of `TITLES`; `marshal` reads as a title only in a phrase (`Field Marshal`). `tools/name_usage.py` produces the counts this judgment starts from (role counts, plus Wikidata citizenship to tell where a family name is written first); its Wikidata column is a lower bound (Shehu Shagari has no given-name statement), so a small count there proves little and a zero proves nothing, and its nam_dict row gives a band per country rather than a count, with a missing name proving nothing either. -**The period-abbreviation title inference runs at the head of the GIVEN-NAME part, not the head of the name** — an unrecognized multi-letter word ending in a single trailing period (`_pieces._PERIOD_ABBREV`, v1's `period_abbreviation` regex, imported from `_vocab`, `{2,}` letters — it was assign's until #424 and group's until #439) is treated as a title in the leading title run, e.g. `"Insp. Jane Morse"` → `title='Insp.'`. "Leading" is per SEGMENT: `_peel_leading_titles` is called for NO_COMMA segment 0, SUFFIX_COMMA segment 0, and FAMILY_COMMA **segment 1**, so `"Morse, Det. Insp. Jane"` → `title='Det. Insp.'` and a lone `"Smith, Xyz."` → `title='Xyz.'` — long-standing, verified against 1.4.0, and the mechanism behind #296 (`"Smith, Jr."` read title in 1.4.0; the comma's credential read takes it as suffix `Jr.` now). The docs said "leading word" until 2026-08-01 and were wrong for every comma path. FAMILY_COMMA **segment 0** peels too since #701, but by VOCABULARY only (rules/H6, in assign's family-comma branch rather than `_peel_leading_titles`): `Dr. Smith, John` → `title='Dr.'`, while `Xyz. Smith, John` keeps family `Xyz. Smith`, and a title-particle (`St`, `Freiherr`) stops the run, as does a title with nothing but post-nominals behind it (`Dr. Jr., John` keeps family `Dr.`); a title/suffix dual with a name word behind it still peels (`Rev. Sr. Smith, Mary`). It adds nothing to the `Lexicon`, so the periodless form (`"Insp"`) is unaffected elsewhere. The `{2,}` length requirement — not a separate initials check — is what excludes single-letter initials like `"J."`, and since #1136 a closed list of transliteration digraphs (`_vocab._DIGRAPH_INITIALS`, e.g. `Yu.`, `Zh.`, `Kh.`; not `Ts.`, `Ch.` or `Sh.`, which are also titles written short) is declined by spelling in both `is_leading_title` and `is_title_shaped` (rules/H2's transliteration-digraph Except), reading as a name word rather than as T5's initial; the same word after the given name is left as a middle name. **The inference OUTRANKS vocabulary where it runs**: `"Esq. Smith"` → `title='Esq.'` even though `esq` is suffix-only vocabulary, because the shape rule fires before anything consults the suffix sets. The one vocabulary it yields to, since #789 (phase 2k of #752), is a given name written short (a `given` reading with `same_as`, in the TOML or a caller's `add(w, kind="given", same_as=...)`, compiled into the internal `Lexicon._sets.given_name_abbreviations`): `"Chas. Smith"` → `given='Chas.'`, read off classify's `vocab:given-abbreviation` tag in `is_leading_title` and off the lexicon in `_vocab.is_title_shaped`, the two spellings of one test that `test_is_title_shaped_and_is_leading_title_agree` holds together. The second spelling is what rules/C4's comma count and the title phrase's head run ask, so a change to the shape moves comma names nobody wrote it for: #789's first grid held no comma and missed `Chas. Smith, Ed` (given 'Ed', family 'Chas. Smith' before, suffix 'Ed' after), which only mutating `is_title_shaped`'s half alone showed. Put a word of the ambiguous class after a comma behind the shaped word (`X. Smith, Ed`), and a modifier in front of it (`Vice X. Smith, Ed`), in the grid of any change to the shape, and mutate each spelling separately. **The INFERENCE still runs in one direction only, and that is what the two slots share and where they part** (rewritten 2026-09-08, #316): a period-marked word is claimed by SHAPE at the front and by VOCABULARY at the back, so an unlisted abbreviation opening a name is a title while an unlisted abbreviation ending one is a NAME word (`"John Smith Xyz."` → `family='Xyz.'`). A trailing period-marked word the vocabulary knows as a title now IS one (`"John Smith Prof."` → `title='Prof.'`, `rules/H5`) — the comma path read a lone `Smith, Prof.` that way already, and the given part's `Smith, John Prof.` since 2.3.0 (1.4.0 through 2.2.0 read `Doe, Jane Mrs.` middle 'Mrs.'), so the two agree now — and a trailing period-marked word the UNAMBIGUOUS SUFFIX vocabulary knows is still a suffix, the suffix run being peeled first (`"John Smith Esq."` → `suffix='Esq.'`). A BARE trailing title word stays a name word (`"John Smith Sir"`, `"Mary Jane Pope"`), which is the doctrine line below, save a listed salutation ending the given part after a family comma (rules/H8, `"Doe, Jane Mrs"` → `title='Mrs'`). Meanwhile `period_joined_vocab` resolves INTERIOR-period tokens (`Lt.Gov.`, `Msc.Ed.`) to title-or-suffix by vocabulary, and `_extract._period_escape` treats any period-final delimited content that rules/S1 does not set apart as not-a-nickname. The trailing chain's SHAPE is wider than the front's since #1116: a word ending in a period may hold periods or hyphens inside it (`_vocab._TRAILING_TITLE_SHAPE`), so a listed title written that way and a `period_joined_vocab` title ending a name chain (`"Hans Meier Priv.-Doz."`, `"John Smith Lt.Gov."` → title), while H2's front shape stays letters only; a title listed whole with a period inside it needs no final period there (`"Maria Rossi Dott.ssa"`, classify's `JOINED_TITLE_TAG`, #1104). Four sites, and the trailing one now resolves by two vocabularies in order rather than one; a fifth, rules/H10 (#490), reads a run of single letters joined by full stops at the head by vocabulary looked up without its stops, as the title it spells where the vocabulary marks that title `dotted` and a title the run keeps follows it (`U.S. District Judge`, but `U.S. Grant` given 'U.S.'); unifying the rest is open design work, not settled. (#109; see `docs/shapes.rst` "Titles you didn't configure") +**The period-abbreviation title inference runs at the head of the GIVEN-NAME part, not the head of the name** — an unrecognized multi-letter word ending in a single trailing period (`_pieces._PERIOD_ABBREV`, v1's `period_abbreviation` regex, imported from `_vocab`, `{2,}` letters — it was assign's until #424 and group's until #439) is treated as a title in the leading title run, e.g. `"Insp. Jane Morse"` → `title='Insp.'`. "Leading" is per SEGMENT: `_peel_leading_titles` is called for NO_COMMA segment 0, SUFFIX_COMMA segment 0, and FAMILY_COMMA **segment 1**, so `"Morse, Det. Insp. Jane"` → `title='Det. Insp.'` and a lone `"Smith, Xyz."` → `title='Xyz.'` — long-standing, verified against 1.4.0, and the mechanism behind #296 (`"Smith, Jr."` read title in 1.4.0; the comma's credential read takes it as suffix `Jr.` now). The docs said "leading word" until 2026-08-01 and were wrong for every comma path. FAMILY_COMMA **segment 0** peels too since #701, but by VOCABULARY only (rules/H6, in assign's family-comma branch rather than `_peel_leading_titles`): `Dr. Smith, John` → `title='Dr.'`, while `Xyz. Smith, John` keeps family `Xyz. Smith`, and a title-particle (`St`, `Freiherr`) stops the run, as does a title with nothing but post-nominals behind it (`Dr. Jr., John` keeps family `Dr.`); a title/suffix dual with a name word behind it still peels (`Rev. Sr. Smith, Mary`). It adds nothing to the `Lexicon`, so the periodless form (`"Insp"`) is unaffected elsewhere. The `{2,}` length requirement — not a separate initials check — is what excludes single-letter initials like `"J."`, and since #1136 a closed list of transliteration digraphs (`_vocab._DIGRAPH_INITIALS`, e.g. `Yu.`, `Zh.`, `Kh.`; not `Ts.`, `Ch.` or `Sh.`, which are also titles written short) is declined by spelling in both `is_leading_title` and `is_title_shaped` (rules/H2's transliteration-digraph Except), reading as a name word rather than as T5's initial; the same word after the given name is left as a middle name. **The inference OUTRANKS vocabulary where it runs**: `"Esq. Smith"` → `title='Esq.'` even though `esq` is suffix-only vocabulary, because the shape rule fires before anything consults the suffix sets. The one vocabulary it yields to, since #789 (phase 2k of #752), is a given name written short (a `given` reading with `same_as`, in the TOML or a caller's `add(w, kind="given", same_as=...)`, compiled into the internal `Lexicon._sets.given_name_abbreviations`): `"Chas. Smith"` → `given='Chas.'`, read off classify's `vocab:given-abbreviation` tag in `is_leading_title` and off the lexicon in `_vocab.is_title_shaped`, the two spellings of one test that `test_is_title_shaped_and_is_leading_title_agree` holds together. The second spelling is what rules/C4's comma count and the title phrase's head run ask, so a change to the shape moves comma names nobody wrote it for: #789's first grid held no comma and missed `Chas. Smith, Ed` (given 'Ed', family 'Chas. Smith' before, suffix 'Ed' after), which only mutating `is_title_shaped`'s half alone showed. Put a word of the ambiguous class after a comma behind the shaped word (`X. Smith, Ed`), and a modifier in front of it (`Vice X. Smith, Ed`), in the grid of any change to the shape, and mutate each spelling separately. **The INFERENCE still runs in one direction only, and that is what the two slots share and where they part** (rewritten 2026-09-08, #316): a period-marked word is claimed by SHAPE at the front and by VOCABULARY at the back, so an unlisted abbreviation opening a name is a title while an unlisted abbreviation ending one is a NAME word (`"John Smith Xyz."` → `family='Xyz.'`). A trailing period-marked word the vocabulary knows as a title now IS one (`"John Smith Prof."` → `title='Prof.'`, `rules/H5`) — the comma path read a lone `Smith, Prof.` that way already, and the given part's `Smith, John Prof.` since 2.3.0 (1.4.0 through 2.2.0 read `Doe, Jane Mrs.` middle 'Mrs.'), so the two agree now — and a trailing period-marked word the UNAMBIGUOUS SUFFIX vocabulary knows is still a suffix, the suffix run being peeled first (`"John Smith Esq."` → `suffix='Esq.'`). A BARE trailing title word stays a name word (`"John Smith Sir"`, `"Mary Jane Pope"`), which is the doctrine line below, save a listed salutation ending the given part after a family comma (rules/H8, `"Doe, Jane Mrs"` → `title='Mrs'`). Meanwhile `period_joined_vocab` resolves INTERIOR-period tokens (`Lt.Gov.`, `Msc.Ed.`) to title-or-suffix by vocabulary, and `_extract._period_escape` treats any period-final delimited content that rules/S1 does not set apart as not-a-nickname. The trailing chain's SHAPE is wider than the front's since #1116: a word ending in a period may hold periods or hyphens inside it (`_vocab._TRAILING_TITLE_SHAPE`), so a listed title written that way and a `period_joined_vocab` title ending a name chain (`"Hans Meier Priv.-Doz."`, `"John Smith Lt.Gov."` → title), while H2's front shape stays letters only; a title listed whole with a period inside it needs no final period there (`"Maria Rossi Dott.ssa"`, classify's `JOINED_TITLE_TAG`, #1104). Four sites, and the trailing one now resolves by two vocabularies in order rather than one; a fifth, rules/H10 (#490), reads a run of single letters joined by full stops at the head by vocabulary looked up without its stops, as the title it spells where the vocabulary marks that title `dotted` and a title the run keeps follows it (`U.S. District Judge`, but `U.S. Grant` given 'U.', middle 'S.', its given names 'U.S.'); unifying the rest is open design work, not settled. (#109; see `docs/shapes.rst` "Titles you didn't configure") **Cyrillic suffix regexes need `re.I` even when the pattern is suffix-only** — a Latin title-cased word (`Ivanovich`) keeps its suffix lowercase, so `re.I` seemed skippable; but an irregular Cyrillic suffix can be nearly the whole word (`ильич`), so title-casing capitalizes into the suffix itself (`Ильич`). `east_slavic_patronymic_cyrillic` (v1's name for what is `_vocab._EAST_SLAVIC_CYR` since 3.0 removed `config/regexes.py`, #1008) shipped without `re.I` on the Latin reasoning and silently failed on capitalized irregular forms — don't assume Latin's title-case safety transfers to Cyrillic. (#185) @@ -339,7 +348,7 @@ The 2.0 rewrite landed as underscore-private modules beside the v1 code, which 2 **Comparing against v1 needs `PYTHONSAFEPATH=1` AND a directory outside the worktree** — `uv run --isolated --no-project --with 'nameparser==1.4.0'` still puts the checkout's `nameparser/` ahead of the pinned wheel on `sys.path`, so the "v1" side silently imports the branch and every comparison reports parity. Run it as `cd && PYTHONSAFEPATH=1 uv run --isolated --no-project --with 'nameparser==1.4.0' python -c "..."`. This produces false confidence rather than an error, so it invalidates results without ever looking wrong. **A `tests/v2/cases.py` row's `parity` means 1.4.0, and nothing checks it** -- the table runs every row against the tree, so a row labelled `parity` that only matches master passes for good. #614 added eight such rows, compared against master; #620 found them by running the wheel this way and relabelled each with the change its reading came from, found by `git bisect run` in a scratch worktree (`git worktree add --detach`, never this one). Run the wheel before writing `parity`. -**A group-side reading of a family comma's given part that asks `tail_reading` disagrees with the given part's own walk, and the disagreement is accepted.** `tail_reading` reads the part as the comma-less name reads it, plus the bare salutations rules/H8 adds after a family comma, which a predictor of this part asks for with `salutations=True` (#835); assign's walk over the given part after a family comma reads by its own predicates -- V before a third comma part is read strictly (#144), staying a name word (`Smith, John van der Berg V, Jr.` reads middle 'van der Berg V'), and P6 attaches a period-marked title-particle (`St.`) the comma-less reading takes as a title. So a bound or a decline group computes with `tail_reading` acts where the walk then reads no title: #623's chain bound (`Smith, John Mc Prof. V, Jr.` → suffix 'Mc, Jr.', middle 'Prof. V') and #637's join decline (`Smith, abdul Prof. V, Jr.` → middle 'Prof. V', `Smith, abdul St.` → family 'St. Smith'); a numeral VI to X was a third such shape until #784 read it as a suffix on both sides. Both were recorded rather than narrowed (Derek: garbage input; decisions/H5 and #P5, rules/P5's Accepted clause). Before writing another group-side predictor of the given part, sweep those two shapes and decide, rather than rediscovering the gap in review. And a change to the trailing peel ITSELF reaches the given part through those predictors without touching them: #718's words-to-spare count for a one-letter numeral, asked through `trailing_run_start`, made the chain take the V in `Smith, Freiherr von Berg V` (given 'von Berg V', unreported) while assign's walk, which never counts there (S4: "read without it"), read it as the suffix -- found by review on a grid of family-comma and empty-head shapes behind a title-particle; the predictor now passes `count_numeral=False`. When a change moves what the peel takes, put a family comma with a title-particle head in its grid. +**A group-side reading of a family comma's given part that asks `tail_reading` disagrees with the given part's own walk, and the disagreement is accepted.** `tail_reading` reads the part as the comma-less name reads it, plus the bare salutations rules/H8 adds after a family comma, which a predictor of this part asks for with `salutations=True` (#835); assign's walk over the given part after a family comma reads by its own predicates -- V before a third comma part is read strictly (#144), staying a name word (`Smith, John van der Berg V, Jr.` reads middle 'van der Berg V'), and P6 attaches a period-marked title-particle (`St.`) the comma-less reading takes as a title. So a bound or a decline group computes with `tail_reading` acts where the walk then reads no title: #623's chain bound (`Smith, John Mc Prof. V, Jr.` → suffix 'Mc, Jr.', middle 'Prof. V') and #637's join decline (`Smith, abdul Prof. V, Jr.` → middle 'Prof. V', `Smith, abdul St.` → family 'St. Smith'); a numeral VI to X was a third such shape until #784 read it as a suffix on both sides. Both were recorded rather than narrowed (decided as garbage input; decisions/H5 and #P5, rules/P5's Accepted clause). Before writing another group-side predictor of the given part, sweep those two shapes and decide, rather than rediscovering the gap in review. And a change to the trailing peel ITSELF reaches the given part through those predictors without touching them: #718's words-to-spare count for a one-letter numeral, asked through `trailing_run_start`, made the chain take the V in `Smith, Freiherr von Berg V` (given 'von Berg V', unreported) while assign's walk, which never counts there (S4: "read without it"), read it as the suffix -- found by review on a grid of family-comma and empty-head shapes behind a title-particle; the predictor now passes `count_numeral=False`. When a change moves what the peel takes, put a family comma with a title-particle head in its grid. **A comparison that runs both sides in one tree reports 0 differences, which is what success looks like.** `tools/differential/compare.py` has been hardened against this — it generates its baseline worker into a temp dir, strips `PYTHONPATH` from the child, and aborts unless both the version AND the resolved path check out on each side; its README's three invocation traps are the analysis behind that design, worth reading before changing the harness. **The exposure is ad-hoc comparisons you write yourself**, where the same collapse has a cause the harness cannot disarm for you: **the shell's working directory persists between tool calls**, so a two-tree comparison written as two `cd`s silently runs both halves in whichever tree it landed in. Pin absolute paths, and assert `nameparser.__file__` on both sides the way `compare.py` does. The general rule outlives any particular trap: before believing a null result, prove the harness can report a difference — a clean run and a broken harness are the same output. The proof has to come from the input class the null result is about: #683 moved `tools/name_usage.py` to a POST and checked it with `shehu`, which is ASCII and so cannot show that the server decodes a Cyrillic body. A misdecoded query still runs and matches nothing, so the Cyrillic zeros it was meant to vouch for proved nothing until `Иван` (17,119 given) went through the same path. The converse trap is a mutation that moves nothing: it shows the code is unexercised by your grids, not that it is dead. #638 was filed calling group's chain re-ask dead on a grid with no title-particle head before a particle run and a dotted acronym; the next review found 400 moves (`Smith, Freiherr van Berg X.Y.Z.`) and the issue closed the same day. Before calling code dead, look for the input that reaches it. A CACHE of readings is the same trap one step removed: a wrong key copies one tree's readings in as another's, and the check then reports nothing. #859 first keyed `snapshot.py --local`'s kept baselines by `git rev-parse HEAD:nameparser`, which answers for the enclosing checkout, so a gitignored copy inside one (`build/lib`) took the checkout's key; two reviewers found it. Key a cached reading by what the import reads -- the files on disk, hashed again after the read -- never by what version control says should be there. And a switch that changes no file defeats any file key: #752's spike set its options by environment variable, so after the first run every option copied that run's cached local readings until the variables joined the key (2026-10-24). A SHARED file of readings is the same trap with no key at all: a local corpus's `snapshot.jsonl` and `psc-individuals`' `agreement.jsonl` are one file per corpus for every worktree, decided by whoever recorded last, and on 2026-10-25 parallel sessions of #752's phase 2 read a sibling's re-record as their own moves -- the silent case being a sibling's record from a branch holding the same change, which reads as "no moves". Use `--base ` whenever another session may be measuring: it reads the base from a baseline keyed by its package's files and never touches the shared file. A kept reading is published under its key only once it is whole and its tree unchanged: `--base`'s first draft had the agreement child write straight to the kept path, through a temporary name every session shared, so two sessions scoring one base could keep a record cut on a line boundary, which every later session would reuse. Write into a folder of the run's own, read it back against a count, take the digest again, then rename it into place. And the cache itself is shared: a test's corpus reaches a temporary cache only where a fixture has set `NAMEPARSER_TOOLS_CACHE` (each local-corpus test module's autouse wrapper of `_differential_fixtures.own_cache`), so a probe that plants one from anywhere else -- a scratch file, a test written outside those modules -- writes the real corpus. On 2026-11-04, during a review that probed `config_diff.py score` that way, `psc-individuals` was replaced by a one-record fixture, and every session's PSC score read one record until it was restored. Brief a reviewer to set `NAMEPARSER_TOOLS_CACHE` to a folder of its own before planting anything; `local_corpora.fetch(source)` called directly rebuilds `psc-individuals` from its cached parts (the CLI's `fetch` skips a corpus already present), and the rebuilt raw file's sha256 matching the kept agreement records' `raw_sha256` shows it whole. @@ -379,7 +388,7 @@ Don't use the bare `python3 -m doctest .rst` CLI (no `optionflags`) to che A parse-behavior test can still be a disguised constant-content test if it only exercises one or two hardcoded entries from a large list (e.g. guarding a specific missing-comma typo in `SUFFIX_ACRONYMS`) — it documents that one instance without catching the same bug class elsewhere in the list. Prefer a test on the structural property itself, or skip a dedicated test for narrow, unrepeatable typo fixes. -**A guard that decides its own scope can stop guarding without failing.** Two shapes hit in #329, both in live code. `_POLICY_SHAPES` in `test_benchmark.py` had one entry, and pytest turns an **empty parametrize into a skip, not a failure**, so deleting it would have dissolved the quadratic guard into the skip count. And the 2.x `test_facade_cases.py::_constants_for` decided which case rows it could express: its gate had been structurally unsatisfiable since the maiden-wins canonicalization landed, silently skipping seven rows, while an unenumerated `Policy` field would instead let a row run MISTRANSLATED. Neither could fail, because a skip is indistinguishable from "correctly declined". Assert the table is non-empty, give each shape a reachability probe, and tie any hand-written field enumeration to `dataclasses.fields(...)` the way `test_policy.py`'s `test_policy_patch_mirrors_policy_field_names` does. **A component that filters its own input needs a test on the filter, not only on what survives it.** A filter whose only witnesses are shipped files loses them when the data changes: `_reading_index.tags()` leaves out a file of familiar readings alone, and #1370's follow-up deleted `mt.toml` and `sq.toml` and emptied `hu.toml`'s familiar readings, the last such files, leaving the filter untested until review planted one (`test_a_file_holding_only_familiar_readings_is_chosen_only_strictly`); when a change removes data, ask which guard used it as its example. The same holds for a record split by scope: a check that reads each scope's share of a record never sees an entry that falls in no scope, so test that every entry has one — #672's per-pack CLDR ratchet missed record entries for a file dropped from `LOCALE_FILES`, and its re-record carried them over as if their pack were merely unmeasured. +**A guard that decides its own scope can stop guarding without failing.** Two shapes hit in #329, both in live code. `_POLICY_SHAPES` in `test_benchmark.py` had one entry, and pytest turns an **empty parametrize into a skip, not a failure**, so deleting it would have dissolved the quadratic guard into the skip count. And the 2.x `test_facade_cases.py::_constants_for` decided which case rows it could express: its gate had been structurally unsatisfiable since the maiden-wins canonicalization landed, silently skipping seven rows, while an unenumerated `Policy` field would instead let a row run MISTRANSLATED. Neither could fail, because a skip is indistinguishable from "correctly declined". Assert the table is non-empty, give each shape a reachability probe, and tie any hand-written field enumeration to `dataclasses.fields(...)` the way `test_policy.py`'s `test_policy_patch_mirrors_policy_field_names` does. **A component that filters its own input needs a test on the filter, not only on what survives it.** A filter whose only witnesses are shipped files loses them when the data changes: `_reading_index.tags()` leaves out a file of familiar readings alone, and #1370's follow-up deleted `mt.toml` and `sq.toml` and emptied `hu.toml`'s familiar readings, the last such files, leaving the filter untested until review planted one (`test_a_file_holding_only_familiar_readings_is_chosen_only_strictly`; #1379 has since given `hu.toml` a familiar reading again, `zsuzsa`, so a shipped file is a witness today, which the planted one does not depend on); when a change removes data, ask which guard used it as its example. The same holds for a record split by scope: a check that reads each scope's share of a record never sees an entry that falls in no scope, so test that every entry has one — #672's per-pack CLDR ratchet missed record entries for a file dropped from `LOCALE_FILES`, and its re-record carried them over as if their pack were merely unmeasured. **Deleting a test module: sort its tests by the code they exercise, not by their names.** A module named for a retired tool also holds tests of code that survives it. #664 deleted `test_ledger_guards.py` and rewrote `test_differential.py`, triaging both by test name, and review found five tests guarding live code in the discard pile: four of `build_issues_corpus.py`'s harvester, and the check that `compare.py` reports the entries it skips. For each test, grep its module-level handles (`load_tool("...")`, imports) and ask whether that code is also being deleted. The converse holds for rewriting tests: a tool that reads test SOURCE by its syntax breaks when the tests change form though no assertion moved. #357 ported the 1.x suite from `HumanName(...)` to `parse(...)` and helpers wrapping it, and `tools/differential/build_corpus.py`, which collected the first argument of `HumanName` calls, returned 183 of the 566 names it reads now, with no warning, until review ran it; grep `tools/` for the call names a port rewrites. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2b905d2a6..661de49a7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,8 +23,9 @@ Why the maintainer makes the changes Most changes here also move documented rules, the design records and a snapshot of thousands of parsed names. The maintainer checks every change -against about 30 million records of real names from thirteen sources -(election candidates, donors, researchers, patent inventors, company filings). +against about 9 million records of real names from sixteen sources +(election candidates, donors, researchers, patent inventors, company filings; +counted 2026-11-16). The tools that fetch them are in this repository, but the names are not: the cache is about 12 GB, and one source alone takes about twelve hours to download. A change that passes the committed tests can still move thousands diff --git a/docs/migrate.rst b/docs/migrate.rst index fb2abc968..4efbbcdb1 100644 --- a/docs/migrate.rst +++ b/docs/migrate.rst @@ -721,6 +721,11 @@ that wrote it: - loads - loads - Nothing + * - ``Policy``, ``PolicyPatch``, and anything holding a ``Lexicon`` + - 3.1 + - ``ValueError`` + - loads + - Keep a 3.0 copy while 3.0 must read it (below) * - ``ParsedName`` - 2.x - loads, rendering as 2.x did @@ -729,8 +734,9 @@ that wrote it: * - any of the rows above but the first - 3.0 - loads - - loads - - Nothing + - loads, keeping 3.0's vocabulary, save a caller's word written with a + tatweel (below) + - Build a new ``Parser()`` for 3.1's readings A ``HumanName`` or a ``Constants`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -761,6 +767,29 @@ loads it depends on the release that wrote it: A re-pickled object keeps the vocabulary it was first pickled with, not this release's; build a new ``Parser()`` for that. +Between 3.0 and 3.1 +~~~~~~~~~~~~~~~~~~~ + +A pickle keeps the vocabulary of the release that wrote it. A +``Parser`` or locale pack pickled by 3.0 loads under 3.1 and reads and +matches as 3.0 did: it reads ``Md. Rahim Uddin`` with the title +``Md.``, does not split the Thai title off ``นายสมชาย``, finds no +familiar form between ``Bill`` and ``William``, and a pickled +``locales.NE`` lacks the ``initials_as_family`` 3.1 gives it. Build the +object again under 3.1 to read the 3.1 way. + +A 3.0 ``Lexicon`` or ``Parser`` holding a word a caller added with an +Arabic tatweel (``ـ``) raises ``ValueError`` under 3.1, which deletes +the tatweel when it normalizes a word (:issue:`1151`): build it again +with the same ``add()`` calls. + +The other way, 3.0.x refuses with ``ValueError`` anything holding a +``Lexicon``, ``Policy`` or ``PolicyPatch`` pickled by 3.1, a bare +``Policy()`` and a locale pack included: 3.1's vocabulary has readings +3.0 does not take, its ``Policy`` has two new fields, and +``Script.CYRILLIC`` is new. A ``ParsedName`` or ``Ambiguity`` loads +both ways. + Pickles between 2.x releases ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/release_log.rst b/docs/release_log.rst index a513580af..37c7284ce 100644 --- a/docs/release_log.rst +++ b/docs/release_log.rst @@ -6,7 +6,7 @@ Release Log - **Change README's License section to credit the sources nameparser's word lists were measured on.** The ``License-Expression`` stays ``LGPL-2.1-or-later``, as in every release through 3.0.1: no list copied whole from a third party ships, the familiar forms being pairs the project found in ORCID and US public records and reviewed. No release shipped data from nam_dict (GNU FDL) or Old Dominion University's nicknames list (Apache 2.0), which the 3.1 cycle's familiar forms, and for nam_dict the suggester's table, held until they were rebuilt. The section names Spain's INE and Taiwan's surname ranking, whose counts two locale lists were measured on. :issue:`1370`, :issue:`1382` - **Change locales.ZH's simplified surnames to the ones Wikidata's family-name items write, no longer Unihan's.** ``parser_for(locales.ZH).parse("谌龙")`` gives family ``谌龙``, undivided, where 2.5.0 through 3.0.1 gave family ``谌``, given ``龙``; seven simplified forms no Wikidata item attests (买, 厐, 盖, 篮, 芈, 诸, 谌) left the list, and their traditional forms (``諶龍``) still divide. 2.5.0 through 3.0.1 shipped those forms from Unihan, whose Unicode License v3 their metadata did not name; 3.1 ships no Unihan-derived data. :issue:`1370` - - **Remove loading a Lexicon, Parser or locale pack pickled by 2.x, which 3.0 deprecated.** ``pickle.loads`` of a ``Parser`` pickled by 2.8.0 raises ``ValueError`` saying to re-pickle it under 3.0, where 3.0.x loaded it with a ``DeprecationWarning``; the error for a 2.x ``Lexicon`` spelling now names :doc:`migrate`'s table rather than each word's calls. A ``Lexicon``, ``Parser`` or locale pack pickled by 3.1 does not load under 3.0.x, which refuses the readings 3.1 adds (a ``same_as`` on a title reading, or naming several words) and its new ``Policy`` fields. :issue:`1003` + - **Remove loading a Lexicon, Parser or locale pack pickled by 2.x, which 3.0 deprecated.** ``pickle.loads`` of a ``Parser`` pickled by 2.8.0 raises ``ValueError`` saying to re-pickle it under 3.0, where 3.0.x loaded it with a ``DeprecationWarning``; the error for a 2.x ``Lexicon`` spelling now names :doc:`migrate`'s table rather than each word's calls. A ``Lexicon``, ``Parser``, locale pack or ``Policy`` pickled by 3.1 does not load under 3.0.x; :ref:`migrate-pickles` lists what loads where. :issue:`1003` - **Change PolicyPatch.script_orders to merge by script.** ``Policy().patched(PolicyPatch(script_orders={Script.HAN: GIVEN_FIRST}))`` keeps the Hangul and hiragana entries beside its Han one, where 2.1.0 through 3.0.1 replaced the whole table with the patch's; an empty patch no longer clears the table, which ``Policy(script_orders=())`` on the base parser does. A pack can now add one script's order without erasing a caller's own, and ``parser_for`` warns where two packs set one script differently. :issue:`1237` - **Add locales.MN, a Mongolian pack.** ``parser_for(locales.MN).parse("Батын Сүхээ")`` gives family ``Батын``, the father's name, given ``Сүхээ``, where the default, as 1.4.0 through 3.0.1, gives given ``Батын``, family ``Сүхээ``. It reads a name written wholly in Cyrillic family first with the given name last, Russian and Kazakh names included, so keep it for Mongolian data; a romanized name keeps the caller's order, since Mongolians mostly write their names given-first in Latin letters. See :ref:`mongolian-names`. :issue:`1237` - **Fix a Kyrgyz name with no surname reading the patronymic marker alone as the family under locales.TR_AZ.** ``parser_for(locales.TR_AZ).parse("Bekmyrza Cholponbai uulu")`` gives given ``Bekmyrza``, family ``Cholponbai uulu``, where 1.4.0 (with Turkic handling) through 3.0.1 gave middle ``Cholponbai``, family ``uulu``; a name of three name words ending in a standalone marker (``kyzy``, ``oğlu``, ``qizi``) reads the same way, and two still read the marker alone (``Cavad oğlu``). :issue:`1187` diff --git a/nameparser/AGENTS.md b/nameparser/AGENTS.md index d2614db33..a6da52d2c 100644 --- a/nameparser/AGENTS.md +++ b/nameparser/AGENTS.md @@ -22,7 +22,7 @@ Read a generated grid's moves by SHAPE, not by corpus membership: #614's first d ### Heads and title runs -#614's second review found two gaps. The first was a shape: no grid put TWO words that are both a title and a particle at the head (`Freiherr St van Berg MA`, where an index into the pieces was applied to a merged view of them -- `TITLES ∩ particles_ambiguous` is `{freiherr, st}` with the ranks `graf`, `gräfin`, `fürst` and `prinz` since #709, so put `Freiherr` and `St` (and one rank) in every head list, each in its bare and its period-marked spelling -- #637's grid had `St` and `Freiherr` alone and missed that `St.` and `Freiherr.` are declined by the bound join and then attached by P6). #701's review added one: put a title/suffix dual (`Ms`, `Sr.`, `Cpl`) SECOND in a title run, behind an ordinary title. A stop that asks only "is this word suffix vocabulary" passes every row that opens with the dual and fails `Rev. Sr. Smith, Mary`; it was found by comparing `T Smith, John` against `T John Smith` over every title word, and a comma-versus-comma-less comparison is the cheap check for any rule that moves a word between the two slots. +#614's second review found two gaps. The first was a shape: no grid put TWO words that are both a title and a particle at the head (`Freiherr St van Berg MA`, where an index into the pieces was applied to a merged view of them -- `TITLES ∩ particles_ambiguous` is `{freiherr, st}` with the ranks `graf`, `gräfin`, `fürst` and `prinz` since #709 and the Armenian `տեր` since #1320 (2026-11-16, `sorted(L.titles & L.particles_ambiguous)` with `L = Parser().lexicon._sets`), so put `Freiherr` and `St` (and one rank) in every head list, each in its bare and its period-marked spelling -- #637's grid had `St` and `Freiherr` alone and missed that `St.` and `Freiherr.` are declined by the bound join and then attached by P6). #701's review added one: put a title/suffix dual (`Ms`, `Sr.`, `Cpl`) SECOND in a title run, behind an ordinary title. A stop that asks only "is this word suffix vocabulary" passes every row that opens with the dual and fails `Rev. Sr. Smith, Mary`; it was found by comparing `T Smith, John` against `T John Smith` over every title word, and a comma-versus-comma-less comparison is the cheap check for any rule that moves a word between the two slots. ### A report's field diff --git a/nameparser/_pipeline/AGENTS.md b/nameparser/_pipeline/AGENTS.md index 8d12754d2..b948dab0f 100644 --- a/nameparser/_pipeline/AGENTS.md +++ b/nameparser/_pipeline/AGENTS.md @@ -32,7 +32,7 @@ The decision site also has the token index and the detail text in hand, which th **If a fork's two branches are taken in DIFFERENT stages, every one of them needs the emitter** -- `PARTICLE_OR_GIVEN` is decided in `_assign` when the ambiguous particle stays a lone leading piece, in `_group` when something shifts it off the name's leading piece and the prefix chain claims it, and wherever P6's attachment takes a trailing particle into the family -- in `_assign` after a family comma (since #613, and behind an empty part before the comma since #892), in `post_rules` at the end of a name read family-first (#467) -- so every one of them reports; for two years only the first did. -What can still do the shifting is narrow, and #367 is why: a plain title no longer can (`Dr. Van Johnson` reads as `Van Johnson` does and reports from `_assign`), so the `_group` emitter needs a word that is BOTH a title and a particle — measured, `TITLES ∩ particles_ambiguous` is `{freiherr, st}` in the default vocabulary, and the ranks `graf`, `gräfin`, `fürst` and `prinz` since #709 (2026-11-04) (`do` left TITLES in #296's audit; the particle-line block in decisions/vocabulary-exclusions records the before and after), plus any overlap a caller's config creates — standing ahead of the chained particle as the LEADING NAME word. Titles may precede it, so `Dr. St van Johnson` reaches the emitter and `St van Johnson` does too; a given name may not, so `Jan Freiherr von Richthofen` does not reach it while `Freiherr von Richthofen` and `Dr. Freiherr von Richthofen` do. Two shapes that look like they should reach it and do NOT, both measured by stepping `STAGES` and watching where `ambiguities` grows: `Dr. Do van Johnson` and `Do St Johnson` report from `assign`, not `group`, because `do` is no longer a title and so stays the leading name piece assign reports on — a both-vocabulary word CHAINED (`Jan St Johnson`) reports nothing at all. When checking whether that emitter is dead, a both-vocabulary word in the leading name position is the thing to look for, and the answer is that it is not dead. +What can still do the shifting is narrow, and #367 is why: a plain title no longer can (`Dr. Van Johnson` reads as `Van Johnson` does and reports from `_assign`), so the `_group` emitter needs a word that is BOTH a title and a particle — measured, `TITLES ∩ particles_ambiguous` is `{freiherr, st}` in the default vocabulary, the ranks `graf`, `gräfin`, `fürst` and `prinz` since #709, and the Armenian `տեր` since #1320 (2026-11-16, `sorted(L.titles & L.particles_ambiguous)` with `L = Parser().lexicon._sets`) (`do` left TITLES in #296's audit; the particle-line block in decisions/vocabulary-exclusions records the before and after), plus any overlap a caller's config creates — standing ahead of the chained particle as the LEADING NAME word. Titles may precede it, so `Dr. St van Johnson` reaches the emitter and `St van Johnson` does too; a given name may not, so `Jan Freiherr von Richthofen` does not reach it while `Freiherr von Richthofen` and `Dr. Freiherr von Richthofen` do. Two shapes that look like they should reach it and do NOT, both measured by stepping `STAGES` and watching where `ambiguities` grows: `Dr. Do van Johnson` and `Do St Johnson` report from `assign`, not `group`, because `do` is no longer a title and so stays the leading name piece assign reports on — a both-vocabulary word CHAINED (`Jan St Johnson`) reports nothing at all. When checking whether that emitter is dead, a both-vocabulary word in the leading name position is the thing to look for, and the answer is that it is not dead. The stage-ownership map in `tests/v2/pipeline/test_state.py` must list `ambiguities` for each such stage, and it passes vacuously until a case row exercises the path, so add the row too. Report BOTH directions of a two-way fork — "John Smith V" (read as a suffix) and "John V" (read as the family name) are equally guesses. diff --git a/nameparser/vocab/AGENTS.md b/nameparser/vocab/AGENTS.md index 68de22371..62885d02a 100644 --- a/nameparser/vocab/AGENTS.md +++ b/nameparser/vocab/AGENTS.md @@ -4,7 +4,7 @@ Loaded when a session reads a vocabulary TOML file. The steps for adding a word ## Step 1: its other readings -First check the word's OTHER readings: `uv run python tools/vocab/query.py --word ` lists every reading and exclusion of it in every file, which is where the overlaps between categories now show. Real overlaps exist: `st`/`freiherr` and the ranks `graf`, `gräfin`, `fürst`, `prinz` (#709) ∈ `PARTICLES` ∩ `TITLES`, and `do`/`mc`/`vd` ∈ `PARTICLES` ∩ `SUFFIX_ACRONYMS`; `abd` = "ABD" ∈ `SUFFIX_ACRONYMS`; `abu` ∈ `PARTICLES` ∩ `BOUND_GIVEN_NAMES` (position-dependent: leading token → given-name join, mid-name → family-name join). Usually position-dependent and harmless, but can force a guard or an exclusion (the `last_base` all-particles guard; `abd`, kept out of `BOUND_GIVEN_NAMES` until decisions/P5 found the credential collision cost nothing at either end). +First check the word's OTHER readings: `uv run python tools/vocab/query.py --word ` lists every reading and exclusion of it in every file, which is where the overlaps between categories now show. Real overlaps exist: `st`/`freiherr`, the ranks `graf`, `gräfin`, `fürst`, `prinz` (#709) and the Armenian `տեր` (#1320) ∈ `PARTICLES` ∩ `TITLES` (2026-11-16, `sorted(L.titles & L.particles)` with `L = Parser().lexicon._sets`), and `do`/`mc`/`vd` ∈ `PARTICLES` ∩ `SUFFIX_ACRONYMS`; `abd` = "ABD" ∈ `SUFFIX_ACRONYMS`; `abu` ∈ `PARTICLES` ∩ `BOUND_GIVEN_NAMES` (position-dependent: leading token → given-name join, mid-name → family-name join). Usually position-dependent and harmless, but can force a guard or an exclusion (the `last_base` all-particles guard; `abd`, kept out of `BOUND_GIVEN_NAMES` until decisions/P5 found the credential collision cost nothing at either end). ## Step 2: real names, not memory diff --git a/nameparser/vocab/README.md b/nameparser/vocab/README.md index 0b0551cc9..cf27af796 100644 --- a/nameparser/vocab/README.md +++ b/nameparser/vocab/README.md @@ -2,7 +2,7 @@ This folder holds the parser's default vocabulary: the titles, suffixes, particles, conjunctions, bound given names and maiden markers it recognizes, and the case of the words it capitalizes specially, written one word at a time. It is the place to edit when a word should be recognized, should stop being recognized, or should be recognized differently. -The parser never reads these files. `tools/vocab/build.py` compiles them into `nameparser/config/_compiled.py`, a committed module of sorted `frozenset` literals and one `dict` (`CAPITALIZATION_EXCEPTIONS`), which `Lexicon` reads; since 3.0 they are private (#1007), a caller listing a kind's words with `Lexicon.words(kind=...)`. Beside it the build writes a second committed module from the same readings, the reading index `nameparser/config/_index.py`, which keeps every reading with the tag of the file it is in and the properties the compiler reads, which a choice of languages (`Locale.languages`, 3.0's phase 3) compiles from, and a third, `nameparser/config/_rules.py`, holds the files' [rules](#rules) tables. So an edit here does nothing until you rebuild, and the tests fail, naming the command, when a committed module and the files disagree. +The parser never reads these files. `tools/vocab/build.py` compiles them into `nameparser/config/_compiled.py`, a committed module of sorted `frozenset` literals and five `dict`s (`CAPITALIZATION_EXCEPTIONS`, and the name match's `SAME_AS`, `SAME_AS_NAMED`, `FAMILIAR` and `ALTERNATE_SPELLINGS`), which `Lexicon` reads; since 3.0 they are private (#1007), a caller listing a kind's words with `Lexicon.words(kind=...)`. Beside it the build writes a second committed module from the same readings, the reading index `nameparser/config/_index.py`, which keeps every reading with the tag of the file it is in and the properties the compiler reads, which a choice of languages (`Locale.languages`, 3.0's phase 3) compiles from, and a third, `nameparser/config/_rules.py`, holds the files' [rules](#rules) tables. So an edit here does nothing until you rebuild, and the tests fail, naming the command, when a committed module and the files disagree. Why the model looks this way, and what each decision cost, is recorded in [decisions/vocabulary-model](../../docs/design/decisions/vocabulary-model.md). The plan it was built to, phase by phase (phases 2 to 4, each section saying what has landed), is in [the vocabulary model RFC](../../docs/design/vocabulary-model-rfc.md). @@ -95,7 +95,7 @@ The build checks the order and never rewrites a file, because a comment above an ## Kinds -A reading's key is its **kind**. The table lists the kinds in their canonical order, which is the [word order](#word-order)'s first key and `CATEGORY`'s order in `nameparser/_reading_index.py`, the compiler the build shares with the package. Each kind belongs to one **category**, and the category decides which compiled set the reading feeds. For title, suffix, particle and conjunction the category's own name is also a kind (`title = {}`: a title not yet classified), so classifying a word later is a data edit that moves no compiled set. The one exception: a generic `suffix = {}` classified as `credential` moves from `SUFFIX_WORDS` to `SUFFIX_ACRONYMS`, because a credential's `acronym` is true unwritten; write `acronym = false` to keep it where it was. The suffix and particle categories are classified (two particles of unrecorded origin, `bon` and `dí`, keep the generic kind in `und.toml`); so are the titles (#750); the others carry their generic kind. +A reading's key is its **kind**. The table lists the kinds in their canonical order, which is the [word order](#word-order)'s first key and `CATEGORY`'s order in `nameparser/_reading_index.py`, the compiler the build shares with the package. Each kind belongs to one **category**, and the category decides which compiled set the reading feeds. For title, suffix, particle and conjunction the category's own name is also a kind (`title = {}`: a title not yet classified), so classifying a word later is a data edit that moves no compiled set. The one exception: a generic `suffix = {}` classified as `credential` moves from `SUFFIX_WORDS` to `SUFFIX_ACRONYMS`, because a credential's `acronym` is true unwritten; write `acronym = false` to keep it where it was. The suffix and particle categories are classified (the last two generic particles, `bon` and `dí` in `und.toml`, lost their particle readings in #766); so are the titles (#750); the others carry their generic kind. | Kind | Category | Compiled into | |---|---|---| @@ -191,7 +191,7 @@ A property is **behavioral** when it compiles into a set and so changes how name | `shared` | behavioral | `name` | false | `SHARED_NAMES`: a name a community gives every member, written after the personal name and before a family name where there is one (Sikh `kaur` and `singh`), no personal or family name of the bearer's own: two-family-name handling ([rules/O6](../../docs/design/rules/O6-two-family-names.md)) and two-given-name handling ([rules/O7](../../docs/design/rules/O7-two-given-names.md)) neither take it nor complete one with it, so `Harpreet Kaur Dhillon` keeps middle `Kaur` under either, and a given name a particle completes ([rules/P10](../../docs/design/rules/P10-given-name-a-particle-completes.md)) is never one, so `Kaur del Carmen García` keeps family `del Carmen García` by default (#704) | | `after_particle` | behavioral | `name` | false | `PARTICLE_GIVEN_NAMES`, on a `given` reading only: a given name written behind a particle as the second of a compound given name (`carmen` in `María del Carmen`): behind a one-word given name the particle run and the word are a middle name, though the chain would run on into the family, as in `María del Carmen García` ([rules/P10](../../docs/design/rules/P10-given-name-a-particle-completes.md), a given name a particle completes, which states the conditions), which two-given-name handling ([rules/O7](../../docs/design/rules/O7-two-given-names.md)) then takes into the given name and two-family-name handling ([rules/O6](../../docs/design/rules/O6-two-family-names.md)) leaves where it stands. A word is marked where, of the names its reading moves to the boxes their filers filled or away from them, at least 75% move to them, with ten such names or more: on by default where that holds over every language's countries pooled, written `default = false` in its language's file where it holds in that language's countries alone, for a choice of the language to turn on, and left out where it fails (`kassia`); a word with fewer than ten such names keeps the tier an earlier measure gave it (`ribamar`, `piedade`), and `luz` was left out by #704's given-box share (decisions/P10, #704, #1118, #1122) | | `completed_by` | behavioral | `bound_given` | none | `BOUND_PHRASES`: the words that complete the bound given name into one name unit past the first name word, a list (`completed_by = ["الله", "الرحمن"]` on `عبد`), each one word written folded: `سعيد عبد الله` reads family `عبد الله` ([rules/P12](../../docs/design/rules/P12-bound-given-name-and-the-word-that-completes-it.md), a bound given name and the word that completes it), while a word left off the list after it is a name of its own, as in `نوال عبد هاشم` (#694) | -| `dotted` | behavioral | `title` | false | `DOTTED_TITLES`: the title abbreviates several words and is written with a full stop after each letter (`us`, `uk`, German `pd`), so a run of single letters joined by full stops that spells it is that title at the head of a name where a title the name keeps follows it, as in `U.S. District Judge Marc Treadwell`, and the initials it is written as otherwise (`U.S. Grant`) ([rules/H10](../../docs/design/rules/H10-title-written-as-a-run-of-letters.md), a title written as a run of letters). A title abbreviating one word (`dr`, `mr`, `lt`) is left unmarked, since two initials spell it (`D.R. Judge Smith` keeps given `D.R.`) | +| `dotted` | behavioral | `title` | false | `DOTTED_TITLES`: the title abbreviates several words and is written with a full stop after each letter (`us`, `uk`, German `pd`), so a run of single letters joined by full stops that spells it is that title at the head of a name where a title the name keeps follows it, as in `U.S. District Judge Marc Treadwell`, and the initials it is written as otherwise (`U.S. Grant`) ([rules/H10](../../docs/design/rules/H10-title-written-as-a-run-of-letters.md), a title written as a run of letters). A title abbreviating one word (`dr`, `mr`, `lt`) is left unmarked, since two initials spell it (`D.R. Judge Smith` reads given 'D.', middle 'R. Judge', its given names 'D.R. Judge', no title) | | `capital_opening` | behavioral | `particle` | false | `CAPITAL_OPENING_PARTICLES`: the particle is written with a capital where the word before it in the family name is no particle, nor, where it opens the family name, the word written right before it in any role (`Van der Walt` keeps its lowercase `der`), as the Armenian priestly prefix is (`ter` and `der`: `LEVON TER PETROSYAN` repairs to `Levon Ter Petrosyan`), and keeps its lowercase after one (`Jan van der Berg`) ([rules/R12](../../docs/design/rules/R12-particle-opening-the-family-name-with-a-capital.md), a particle opening the family name with a capital); it moves no parse. A Dutch surname opened by `ter` takes the capital too (`Gerard Ter Borch`), a cost accepted in decisions/R12 | | `may_be_given` | stated | `particle` | none: required where the word has no `given` reading | `false` is required where the word has no `given` reading in any file, and that absence, not the property, is what puts the word in `NON_GIVEN_NAME_PARTICLES`: a particle opening the name starts the family name ([rules/P1](../../docs/design/rules/P1-lone-particle-fold.md), the lone particle fold). `true` is refused, naming the `given` reading to write instead (check 11) | | `may_be_initial` | behavioral | `conjunction` | false | `CONJUNCTIONS_AMBIGUOUS`, on a cased single letter only: read as an initial in a name written in one case, as in `JOHN E SMITH` ([rules/P8](../../docs/design/rules/P8-single-letter-connective-against-the-initial-it-spells.md), a single-letter connective against the initial it spells) | diff --git a/tests/v2/test_layering.py b/tests/v2/test_layering.py index 5f3b0c3ae..b802ec081 100644 --- a/tests/v2/test_layering.py +++ b/tests/v2/test_layering.py @@ -10,6 +10,7 @@ import nameparser import nameparser._pipeline +import nameparser.locales PKG = pathlib.Path(nameparser.__file__).parent @@ -27,9 +28,7 @@ "_pipeline/_pieces.py", "_pipeline/_assign.py", "_pipeline/_post_rules.py", "_pipeline/_assemble.py", "_parser.py", - "locales/__init__.py", "locales/ja.py", - "locales/ru.py", "locales/tr_az.py", "locales/zh.py", - "locales/_es_given_names.py"} + "locales/__init__.py"} _PIPELINE_STAGE_ALLOWED = ( "nameparser._types", "nameparser._lexicon", "nameparser._policy", @@ -42,6 +41,9 @@ # access (mechanisms.md#LOCALE-PACKS-PURE-DATA) -- one contract # shared by every pack, like # _PIPELINE_STAGE_ALLOWED above, so tightening it is a one-line edit. +# No pack is keyed in ALLOWED: _locale_rules() gives every +# nameparser/locales/*.py but __init__.py this rule, plus the pack's own +# private data module, so a new pack is checked from its first commit. # _types joined the three in #272: the ja pack's segmenter factory # constructs a Segmentation, and _types is the bottom of the graph # (Locale itself imports it), so this widens the base types, not the @@ -162,13 +164,6 @@ # "nameparser.locales." prefix documents that reach for humans even # though the walker never exercises it. "locales/__init__.py": ("nameparser._locale", "nameparser.locales."), - "locales/ja.py": _LOCALE_PACK_ALLOWED, - "locales/ru.py": _LOCALE_PACK_ALLOWED, - "locales/tr_az.py": _LOCALE_PACK_ALLOWED, - "locales/zh.py": _LOCALE_PACK_ALLOWED, - # a pack's data, no pack itself: rules/O6's given-name list (#959), - # which the es pack will carry as a lexicon fragment - "locales/_es_given_names.py": (), # the data modules' package: a docstring, no imports "config/__init__.py": (), # CLI: imports only the public package, same as @@ -182,11 +177,32 @@ def _is_type_checking(test: ast.expr) -> bool: isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING") -def _nameparser_imports(path: pathlib.Path) -> list[str]: +def _package_of(path: pathlib.Path) -> str: + """The dotted package a module at `path` sits in: `nameparser` for + a file outside the package (a test's planted snippet).""" + try: + parts = path.resolve().relative_to(PKG.resolve()).parent.parts + except ValueError: + return "nameparser" + return ".".join(("nameparser", *parts)) + + +def _nameparser_imports(path: pathlib.Path, + package: str | None = None) -> list[str]: """All nameparser-internal imports in the module, at any nesting depth, EXCEPT those under `if TYPE_CHECKING:` -- annotation-only - imports are not runtime dependencies.""" + imports are not runtime dependencies. + + A relative import is recorded by its absolute name, resolved against + `package` (by default the one `path` sits in): `from ._lexicon import + X` in `_suggest.py` is `nameparser._lexicon`, and `from .. import + _parser` in a pack is `nameparser._parser`, each name of a bare + `from import` being taken as a module. Until 3.1 the walker + read `node.module` alone, so a relative import was recorded as a + name the filter below dropped or not at all, and `_suggest.py`, which + imports nothing else, was checked by nothing.""" found: list[str] = [] + base = (package or _package_of(path)).split(".") def _record(node: ast.AST) -> None: # guard checked on EVERY node uniformly, so `elif TYPE_CHECKING:` @@ -197,6 +213,12 @@ def _record(node: ast.AST) -> None: return if isinstance(node, ast.Import): found.extend(a.name for a in node.names) + elif isinstance(node, ast.ImportFrom) and node.level: + anchor = ".".join(base[:len(base) - node.level + 1]) + if node.module: + found.append(f"{anchor}.{node.module}") + else: + found.extend(f"{anchor}.{a.name}" for a in node.names) elif isinstance(node, ast.ImportFrom) and node.module: found.append(node.module) for child in ast.iter_child_nodes(node): @@ -219,8 +241,43 @@ def _permitted(imported: str, allowed: tuple[str, ...]) -> bool: return False +def _locale_rules() -> dict[str, tuple[str, ...]]: + """The rule for every module in nameparser/locales/ but __init__.py. + + A pack (`es.py`) may import _LOCALE_PACK_ALLOWED and its own + private data modules: `_es_given_names.py` belongs to `es.py`, the + pack with the LONGEST stem the data module's name opens with, so + `_es_ar_given_names.py` is `es_ar.py`'s and not `es.py`'s. A data + module (a leading underscore, rules/O6's given-name lists, #959) + imports nothing internal.""" + locales_dir = pathlib.Path(nameparser.locales.__file__).parent + stems = sorted(p.stem for p in locales_dir.glob("*.py") + if not p.stem.startswith("_")) + rules: dict[str, tuple[str, ...]] = {} + for path in sorted(locales_dir.glob("*.py")): + stem = path.stem + if stem == "__init__": + continue + if stem.startswith("_"): + rules[f"locales/{path.name}"] = () + continue + own = tuple( + f"nameparser.locales.{data.stem}" + for data in sorted(locales_dir.glob("_*.py")) + if data.stem != "__init__" + and max((s for s in stems if data.stem.startswith(f"_{s}_")), + key=len, default=None) == stem) + rules[f"locales/{path.name}"] = _LOCALE_PACK_ALLOWED + own + return rules + + +def _checked() -> dict[str, tuple[str, ...]]: + """Every module test_layering_contract checks, with its rule.""" + return {**_locale_rules(), **ALLOWED} + + def test_layering_contract() -> None: - for mod, allowed in ALLOWED.items(): + for mod, allowed in _checked().items(): path = PKG / mod if not path.exists(): assert mod not in _MUST_EXIST, ( @@ -233,6 +290,32 @@ def test_layering_contract() -> None: ) +@pytest.mark.parametrize("pack,data,allowed", [ + ("es", "_es_given_names", True), + ("es_ar", "_es_ar_given_names", True), + # a data module is its longest-stemmed pack's alone + ("es", "_es_ar_given_names", False), + ("pt", "_es_given_names", False), +]) +def test_a_pack_may_import_its_own_data_module_only( + pack: str, data: str, allowed: bool) -> None: + rule = _locale_rules()[f"locales/{pack}.py"] + assert _permitted(f"nameparser.locales.{data}", rule) is allowed + + +def test_the_pack_rule_refuses_what_a_pack_may_not_import() -> None: + # the negative control: the rule every pack is held to refuses the + # pipeline, the parser, the config data and another pack + rule = _locale_rules()["locales/es.py"] + for imported in ("nameparser._pipeline._vocab", "nameparser._parser", + "nameparser.config._compiled", "nameparser.locales.pt", + "nameparser._reading_index"): + assert not _permitted(imported, rule), imported + for data in _locale_rules(): + if pathlib.PurePath(data).stem.startswith("_"): + assert _locale_rules()[data] == () + + def test_every_pipeline_module_is_keyed_in_allowed() -> None: """ALLOWED is a hand-maintained list, and test_layering_contract iterates ITS keys -- so a module absent from it is not checked @@ -258,7 +341,7 @@ def test_every_pipeline_module_is_keyed_in_allowed() -> None: check measuring nothing, which is the shape of the bug it exists to prevent. """ - keyed = set(ALLOWED) + keyed = set(_checked()) pipeline_dir = pathlib.Path(nameparser._pipeline.__file__).parent shipped = {f"_pipeline/{p.name}" for p in pipeline_dir.glob("*.py")} assert "_pipeline/_group.py" in shipped, ( @@ -274,6 +357,41 @@ def test_every_pipeline_module_is_keyed_in_allowed() -> None: ) +def test_every_locales_module_is_checked() -> None: + """The same completeness check over nameparser/locales/, where no + pack is keyed by hand. Until 3.1 only four packs and one data module + were keyed, and the other seventeen packs, and + `_es_ar_given_names.py`, were checked by nothing. + + _locale_rules() enumerates the folder with a `*.py` glob, so this + lists it another way, by what the import system finds there + (pkgutil), and holds each module to the rule its name calls for: a + pack to _LOCALE_PACK_ALLOWED and a data module to none. What it + catches: a module the glob does not reach (a subpackage, + `locales/xx/`), and a module given a rule other than its kind's. + What it cannot: a module neither the glob nor the import system + lists, which no import can load either.""" + import pkgutil + rules = _checked() + found = {m.name: m.ispkg for m in pkgutil.iter_modules( + nameparser.locales.__path__)} + assert {"ja", "es", "_es_given_names"} <= set(found), ( + f"the listing found no locale modules, so this check can no " + f"longer fail: {sorted(found)}") + missing = sorted(name for name, ispkg in found.items() + if ispkg or f"locales/{name}.py" not in rules) + assert not missing, ( + f"locale modules the layering contract does not check: {missing}") + for name in found: + rule = rules[f"locales/{name}.py"] + if name.startswith("_"): + assert rule == (), name + else: + assert rule[:len(_LOCALE_PACK_ALLOWED)] == _LOCALE_PACK_ALLOWED + assert all(extra.startswith(f"nameparser.locales._{name}_") + for extra in rule[len(_LOCALE_PACK_ALLOWED):]), name + + def test_lexicon_never_imports_config_package_root_or_parser() -> None: for imported in _nameparser_imports(PKG / "_lexicon.py"): assert imported != "nameparser.config" @@ -379,6 +497,47 @@ def test_type_checking_imports_do_not_count(tmp_path: pathlib.Path) -> None: assert _nameparser_imports(mod) == ["nameparser.util", "nameparser"] +@pytest.mark.parametrize("package,source,expected", [ + ("nameparser.locales", "from .. import _parser\n", + ["nameparser._parser"]), + ("nameparser.locales", "from ._es_given_names import GIVEN_NAMES\n", + ["nameparser.locales._es_given_names"]), + ("nameparser.locales", "from . import pt\n", ["nameparser.locales.pt"]), + ("nameparser", "from ._pipeline._vocab import x\n", + ["nameparser._pipeline._vocab"]), + ("nameparser._pipeline", "from .._parser import Parser\n", + ["nameparser._parser"]), +]) +def test_a_relative_import_is_recorded_by_its_absolute_name( + tmp_path: pathlib.Path, package: str, source: str, + expected: list[str]) -> None: + mod = tmp_path / "snippet.py" + mod.write_text(source) + assert _nameparser_imports(mod, package) == expected + + +def test_a_pack_s_relative_import_breaks_the_contract( + tmp_path: pathlib.Path) -> None: + # the planted violation the walker missed before it read node.level + mod = tmp_path / "pt.py" + mod.write_text("from .. import _parser\n" + "from ._es_given_names import GIVEN_NAMES\n") + rule = _locale_rules()["locales/pt.py"] + refused = [m for m in _nameparser_imports(mod, "nameparser.locales") + if not _permitted(m, rule)] + assert refused == ["nameparser._parser", + "nameparser.locales._es_given_names"] + + +def test_the_walker_reaches_the_relative_imports_of_suggest() -> None: + # reachability: _suggest.py writes every internal import relatively, + # so an empty list here is a contract that checks nothing + imports = _nameparser_imports(PKG / "_suggest.py") + assert "nameparser._lexicon" in imports + assert "nameparser.config._order_names" in imports + assert "nameparser._parser" in imports # the call-time one + + def test_every_frozen_dataclass_carries_the_pickle_guards() -> None: # Forgetting the two class-body assignments is SILENT -- # @dataclass(slots=True) installs its own working pickle methods diff --git a/tests/v2/test_stage_reads_tool.py b/tests/v2/test_stage_reads_tool.py new file mode 100644 index 000000000..155750c4b --- /dev/null +++ b/tests/v2/test_stage_reads_tool.py @@ -0,0 +1,109 @@ +"""tools/stage_reads.py, the trace of what each pipeline stage reads. + +The tool exists to show the reads a grep of a stage module cannot: a +read made through a helper in ``_vocab`` or ``_pieces``. One test pins a +read of that kind, one the stage's own module never spells; the others +pin where a read is charged, that a policy read follows the row's +policy, and that the traced fold reads every row as ``Parser.parse`` +does, so the trace watches the real parse rather than another one. + +tools/ is not a package, so the module is loaded by path. +""" +from dataclasses import dataclass +from pathlib import Path +from types import ModuleType +from typing import Any + +import pytest + +from nameparser import Parser, Policy +from tests.checkout import needs_checkout + +from ._differential_fixtures import load_by_path + +_PATH = Path(__file__).parents[2] / "tools" / "stage_reads.py" + + +@dataclass(frozen=True) +class _Case: + text: str + policy: Any = None + locale: str | None = None + + +@pytest.fixture(scope="module") +def tool() -> ModuleType: + return load_by_path("stage_reads", _PATH) + + +@needs_checkout +def test_it_sees_a_read_made_through_a_helper(tool: ModuleType) -> None: + # assign's given-part walk reads the suffix sets through + # _vocab.is_suffix_lenient; _assign.py spells none of them + source = (_PATH.parents[1] / "nameparser" / "_pipeline" + / "_assign.py").read_text() + assert "_sets.suffix_words" not in source + reads = tool.trace([_Case("Salem, Abdul Rahman Ahmed")]) + assert reads["assign"]["L.suffix_words"] == "Salem, Abdul Rahman Ahmed" + + +@needs_checkout +def test_it_charges_a_read_to_the_stage_and_the_decision_apart( + tool: ModuleType) -> None: + reads = tool.trace([_Case("John Smith, PhD")]) + assert "group/_comma.decide" in reads + assert not any(stage.endswith("_comma.decide/_comma.decide") + for stage in reads) + assert "L.titles" in reads["classify"] + + +@needs_checkout +def test_it_records_policy_reads_under_the_case_s_policy( + tool: ModuleType) -> None: + # post_rules asks the order only once two_family_names is on: a read + # the row's policy causes, where tokenize's P.strip_bidi is read for + # any row at all + plain = tool.trace([_Case("Juan Pérez García")]) + switched = tool.trace([_Case("Juan Pérez García", + policy=Policy(two_family_names=True))]) + assert "P.name_order" not in plain["post_rules"] + assert switched["post_rules"]["P.name_order"] == "Juan Pérez García" + + +@needs_checkout +def test_tracing_restores_the_decision_it_wraps(tool: ModuleType) -> None: + from nameparser._pipeline import _comma + before = _comma.decide + tool.trace([_Case("John Smith, PhD")]) + assert _comma.decide is before + + +_ROWS = ( + _Case("John Smith, PhD"), + _Case("Salem, Abdul Rahman Ahmed"), + _Case("Juan Pérez García", policy=Policy(two_family_names=True)), + _Case("Dr. Juan Q. Xavier de la Vega III (Doc)"), + _Case("김민준"), + _Case("Ivan Petrovich Sidorov", locale="ru"), +) + + +@needs_checkout +@pytest.mark.parametrize("case", _ROWS, ids=lambda c: c.text) +def test_the_traced_fold_reads_as_parser_parse_does( + tool: ModuleType, case: _Case) -> None: + from nameparser import locales, parser_for + parser = (parser_for(getattr(locales, case.locale.upper())) + if case.locale else Parser(policy=case.policy or Policy())) + seen: list[Any] = [] + tool.trace([case], assembled=seen.append) + assert seen == [parser.parse(case.text)] + + +@needs_checkout +def test_an_unknown_stage_is_an_error(tool: ModuleType, + capsys: pytest.CaptureFixture[str]) -> None: + with pytest.raises(SystemExit) as exit_: + tool.main(["--stage", "no_such_stage"]) + assert exit_.value.code == 2 + assert "classify" in capsys.readouterr().err diff --git a/tools/differential/README.md b/tools/differential/README.md index 124e2774d..521700714 100644 --- a/tools/differential/README.md +++ b/tools/differential/README.md @@ -45,7 +45,8 @@ so a line with neither has a suffix of credentials and honorifics only, or none; `honorifics` where it is not empty; and the `patronymic` and `surname2` views (rules/R9, rules/R10) where each is not empty, which for `surname2` is never: only -`two_family_names` fills it, and the snapshot parses the default. +`two_family_names` and, under `locales.ZH`, a Han surname pair +(rules/W5) fill it, and the snapshot parses the default. Empty values are left out, so a reading that gains a field shows as one added key. The file's first line is a header, `{"recorded": [...]}`, naming the keys added @@ -265,7 +266,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`) 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; `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`) 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; `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 @@ -288,7 +289,7 @@ uv run python tools/differential/snapshot.py --local ctgov-officials --record -- uv run python tools/differential/snapshot.py --local ctgov-officials ``` -Any snapshot reading of 5,000 entries or more, committed or local, parses in a worker process per CPU, as do, past the same floor, `local_agreement.py`'s score and the `pairs --agreement`, `groups` and `alike` views (`--jobs N` to change that; all of them share `snapshot.parallel`, whose workers abort the run where one imported another `nameparser`),. Measured 2026-10-23 on a 12-CPU machine: a 20,000-name sample cost about 120 µs a name for the 2.0 parse and its renders; a check of `fec-individuals` (1,893,964 names) took 49s, and of `ctgov-officials` (352,104) 9.6s. A local recording is kept gzipped in `baselines/` beside the snapshot (41 MB for `fec-individuals` against 249 MB plain, 2026-10-23), under a key of the fetch, a hash of every file in the read tree's `nameparser/` as it is on disk (`__pycache__` aside), the interpreter's minor version and the code that writes a row (`snapshot.py`, `corpus_build.py`, `shapes.py`); recording that base again copies it rather than parsing. The hash is taken again after the read, and a package that changed meanwhile keeps no baseline; a kept baseline that cannot be read, or holds another number of rows than the corpus has entries, is deleted and the names are read. The ten most recently recorded or reused baselines are kept per source, whole and sampled alike, so a few `--sample` recordings can push out a whole one: room for four sessions measuring at once with a base and a head each (four were kept until 2026-10-25, and parallel sessions evicted each other's bases), about 420 MB for `fec-individuals`, whose baseline is the largest (41.7 MB). A snapshot recorded before 2026-10-23 may carry facade rows; a check against one sets them aside. `--sample N` reads a fixed 1-in-N sample, chosen by a hash of the name, into `snapshot.sample-N.jsonl`, for iterating on a change; a sample is never compared with a snapshot of the whole corpus or of another sample, and a count quoted from one says it is a sample. +Any snapshot reading of 5,000 entries or more, committed or local, parses in a worker process per CPU, as do, past the same floor, `local_agreement.py`'s score and the `pairs --agreement`, `groups` and `alike` views (`--jobs N` to change that; all of them share `snapshot.parallel`, whose workers abort the run where one imported another `nameparser`). Measured 2026-10-23 on a 12-CPU machine: a 20,000-name sample cost about 120 µs a name for the 2.0 parse and its renders; a check of `fec-individuals` (1,893,964 names) took 49s, and of `ctgov-officials` (352,104) 9.6s. A local recording is kept gzipped in `baselines/` beside the snapshot (41 MB for `fec-individuals` against 249 MB plain, 2026-10-23), under a key of the fetch, a hash of every file in the read tree's `nameparser/` as it is on disk (`__pycache__` aside), the interpreter's minor version and the code that writes a row (`snapshot.py`, `corpus_build.py`, `shapes.py`); recording that base again copies it rather than parsing. The hash is taken again after the read, and a package that changed meanwhile keeps no baseline; a kept baseline that cannot be read, or holds another number of rows than the corpus has entries, is deleted and the names are read. The ten most recently recorded or reused baselines are kept per source, whole and sampled alike, so a few `--sample` recordings can push out a whole one: room for four sessions measuring at once with a base and a head each (four were kept until 2026-10-25, and parallel sessions evicted each other's bases), about 420 MB for `fec-individuals`, whose baseline is the largest (41.7 MB). A snapshot recorded before 2026-10-23 may carry facade rows; a check against one sets them aside. `--sample N` reads a fixed 1-in-N sample, chosen by a hash of the name, into `snapshot.sample-N.jsonl`, for iterating on a change; a sample is never compared with a snapshot of the whole corpus or of another sample, and a count quoted from one says it is a sample. `compare.py --corpus` takes the cached `corpus.jsonl` too, against a release. @@ -304,7 +305,7 @@ Any snapshot reading of 5,000 entries or more, committed or local, parses in a w | `orcid-researchers` | the public names of ORCID iD holders, researchers worldwide, from ORCID's Public Data File 2025 (`ORCID_2025_10_summaries.tar.gz`, 46.3 GB, data as of 2025-10-17), read as a stream and never stored: each line of its extract is the two boxes the holder typed their own name into (given names, family name), the credit name they publish under where public, other names, and a country, taken from their public address, else the first employment that names one, else the first education that does; a corpus record keeps the boxes, the credit name and the country. The fetch caches an extract of every summary with a public name (24,990,909 of 26,078,951 on 2026-10-27, 1,086,356 private and 1,686 empty), 369 MB, and the corpus keeps at most `ORCID_CAP` (20,000) records a country, the lowest by a hash of the record, so a change to the cap re-reads the extract rather than the 46 GB file: 1,831,533 records: 250 countries, 65 of them at the cap, and the records with no country (14,293,215 of the extract, 57%) as one more group of 20,000, counted in that total. A record's name is its boxes joined, given first; the credit name is a second corpus key (125,960 kept records hold one). Scored by `local_agreement.py` by country, the boxes as the holder split them. CC0, with ORCID asking for credit and respect for the privacy of the people in it | frequency, since the cap flattens every large country to 20,000; people outside research; name order, which ORCID does not record, so a holder who typed a family-first name into the given box reads as a disagreement; names with no family name and names whose family name is private, which look alike (1,308,200 of the extract hold no family name); titles, credentials and suffixes, which the form has no box for | | `patentsview-inventors` | the inventor of every patent the USPTO granted from 1976 to 2025, from PatentsView's granted-patent tables on the USPTO Open Data Portal (release to 2025-12-31): each inventor's name in the filing's two boxes (first name, last name) and the country of the inventor's address. A record is a distinct name in a country, with the number of people who filed under it (`people`, counted by PatentsView's disambiguated inventor id, so a prolific inventor weighs once): 24,037,380 inventor rows, one per inventor per patent, held 5,319,206 such names on 2026-10-28, 99.3% of rows with a country. The extract keeps every name with its count, the corpus at most 20,000 names a country (657,991 records: 202 countries, 23 of them at the cap, and the records with no country as one more group of 20,000, counted in that total). Split by a professional filer, the applicant's attorney, rather than the bearer: `parse()` agreed with 94.7% of the records, 99.8% in Japan, 99.5% in China and 99.0% in the US, so it reads beside `orcid-researchers` as how a name is written against how its bearer types it. A comma stands in the last box of 92,503 of the extract's names, against 129 in the first, before suffixes and legal roles typed after a deceased inventor's name: the text after it is exactly `Jr.` in 55,459 names, `III` in 14,227, `deceased` in 4,635, `heir` in 514, `legal representative` in 393, `executrix` in 328 and `administrator` in 288 (2026-10-28). CC BY 4.0, credit PatentsView; the portal needs an API key | names in any script but Latin, since a filing is romanized; titles and credentials, which a filing has no place for; names outside patenting, which is mostly engineering and science, and its countries' shares are of patents filed in the US, not of their populations | | `jrc-names` | the person entities of the EU Joint Research Centre's JRC-Names, each with the spellings of its name harvested from news text in many languages and scripts: a record is one distinct spelling, with its entity and its script. The file (`entities.gzip`, 14.8 MB) is pinned by sha256 and dated by its Last-Modified, 2024-03-15. Of its 1,317,586 spellings kept, 1,203,634 are Latin, 66,673 Cyrillic, 17,074 Arabic (7,833 persons, 5,347 of them spelled in Latin too), 13,039 Katakana and 8,016 Han, and 218,822 persons have two or more spellings, 25,415 of them in two scripts or more (a spelling whose letters are in two scripts, or none, not counted as one). The population for spelling and transliteration variants of one name, read by the `groups` view, and for Arabic-script names. Licensed under the JRC-Names EULA, personal and non-transferable, with no redistribution or derivative works, so its views' output and its snapshot stay in the cache like every local corpus's, and here the licence, not only the names being real people's, is why | titles and credentials, since the names are harvested from running text (`parse()` read a title in 3,011 of its 1,315,051 names and a suffix in 1,940, 2026-10-24); the ASCII comma, which none holds (1,510 Arabic spellings hold an Arabic comma, U+060C, which the parser reads as one); the Indic scripts (Devanagari 827 spellings, Bengali 419, the others fewer); people the news did not name | -| `nepal-candidates` | every candidate in Nepal's local elections of 2079 BS (2022), from the Election Commission's results site (result.election.gov.np), one file per local body: a record per distinct pair of the Commission's romanization (`name`, the one `parse()` reads) and the name in Devanagari as filed (`devanagari`). The corpus and the word index hold both, so a snapshot and a `name_usage.py` lookup read both scripts; `tally`, which counts what follows a comma, reads the romanized name. Of 126,981 pairs fetched 2026-10-24 (152,960 candidates in 753 files, 26 of whose romanizations were a placeholder such as `- - -` and are dropped), the romanized names carry surnames written as initials (`B.K.`, `K.C.`, `G.C.`), honorific words that are titles in front (`Guru`; `Shekh` until #752's phase 2j made it a title only in a title phrase) and `Md.`, Muhammad's abbreviation, which its period makes a title by shape; the Devanagari ones carry vowel signs and the virama, combining marks the letter-shape tests do not count as letters (decisions/nfd-shapes), and the joiners ZWJ and ZWNJ. The population for romanized South Asian names and for Devanagari. The site states no licence, which the credit line says | case and the comma, since the Commission's romanization is one consistent hand; names a person typed themselves; credentials and generational words; the parliament and provincial candidates, whose files carry Devanagari only; names outside Nepal | +| `nepal-candidates` | every candidate in Nepal's local elections of 2079 BS (2022), from the Election Commission's results site (result.election.gov.np), one file per local body: a record per distinct pair of the Commission's romanization (`name`, the one `parse()` reads) and the name in Devanagari as filed (`devanagari`). The corpus and the word index hold both, so a snapshot and a `name_usage.py` lookup read both scripts; `tally`, which counts what follows a comma, reads the romanized name. Of 126,981 pairs fetched 2026-10-24 (152,960 candidates in 753 files, 26 of whose romanizations were a placeholder such as `- - -` and are dropped), the romanized names carry surnames written as initials (`B.K.`, `K.C.`, `G.C.`), honorific words that are titles in front (`Guru`; `Shekh` until #752's phase 2j made it a title only in a title phrase) and `Md.`, Muhammad's abbreviation, a title by its period's shape until #1383 made it the given name written short; the Devanagari ones carry vowel signs and the virama, combining marks the letter-shape tests do not count as letters (decisions/nfd-shapes), and the joiners ZWJ and ZWNJ. The population for romanized South Asian names and for Devanagari. The site states no licence, which the credit line says | case and the comma, since the Commission's romanization is one consistent hand; names a person typed themselves; credentials and generational words; the parliament and provincial candidates, whose files carry Devanagari only; names outside Nepal | | `cz-candidates` | every candidate on the registers the Czech Statistical Office (ČSÚ) publishes on volby.gov.cz for the 2022 municipal elections (`kv2022`) and the 2025 Chamber of Deputies election (`ps2025`): a record is a distinct candidate's four name boxes in one election, the title before the name (`TITULPRED`), the given names (`JMENO`), the surname (`PRIJMENI`) and the title after it (`TITULZA`), with the election; 165,736 records of kv2022's 197,506 candidates and 4,445 of ps2025's 4,475 on 2026-10-30. A record's name is COMPOSED, not written by anyone: the boxes joined in the Czech convention, `TITULPRED JMENO PRIJMENI, TITULZA` (`Ing. Jan Novák, Ph.D.`). 61,320 of its 170,181 records carry a title (58,667 before the name, 7,687 after it), nearly all academic degrees (`Ing.`, `Mgr.`, `Bc.`, `MUDr.`; `DiS.`, `Ph.D.`, `MBA`): the population for titles and post-nominals the filer kept apart from the name. Scored by `local_agreement.py` by election, under the default parser and under `--locale cs`. ČSÚ licenses it under CC BY 4.0, asking that derived data be marked as derived, which the composed names are and the credit line says | case, spacing and punctuation of a writer's own, since the string is composed; the family-comma shape; courtesy titles and offices; names outside Czechia; the elections not in `VOLBY_ELECTIONS` (the index lists kv2002 to kv2026 and ps2002 to ps2025) | | `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 | @@ -331,7 +332,7 @@ Its score reads the title before the name against `TITULPRED`, the given and mid `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. -`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`; 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. +`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. `pairs` reads a paired source (`tse-donors`, whose records carry the registry's name beside the filed one) as two spellings of one person, and sorts each pair by how the filed name departs from the reference: the first of its shapes that fits, from case, accents (case unchanged) and case and accents together, through words left out, shortened or misspelled, to few words in common. A word left out or added counts once per pair, and is listed only when ten pairs share it. `--agreement` also parses both spellings of every pair with a reference name that differs, and counts the pairs whose two readings end the family name in the same word (two readings with no family name share none). It lists the accents-only pairs read with two surnames by the two spellings' last words, the same ten-pair floor applied. @@ -339,11 +340,11 @@ Its score reads the title before the name against `TITULPRED`, the given and mid uv run python tools/differential/local_corpora.py pairs tse-donors --agreement ``` -On the fetch of 2026-10-22, 205,925 of `tse-donors`' 854,531 pairs differ. The commonest shapes: words left out (22.0%: `DE` left out of 13,412 pairs, `DA` 5,906, `DOS` 3,033, then second surnames, `SILVA` 2,869), accents only (21.1%; 255 of them SÁ / SA pairs read with two surnames until #857), words shortened (15.8%), words misspelled (14.9%) and words left out and shortened (11.8%). Read the agreement per shape, since a shape can change the surname legitimately: a pair that leaves out the last surname ends the family in another word, which is likely most of why only 44% of words left out agree (not measured apart from the other causes). Accents only cannot change the surname, so its 1,304 of 43,552 pairs that disagree are the parser reading one name two ways: by their last words, `JÚNIOR` against `JUNIOR` in 866 (#843) and `SÁ` against `SA` in 255, where `MARIA DE SA` reads `SA` as a credential and `MARIA DE SÁ` as the surname. The run took 39s in one process (15.8s in workers, 2026-10-27). +On the fetch of 2026-10-22, 205,925 of `tse-donors`' 854,531 pairs differ. The commonest shapes: words left out (22.0%: `DE` left out of 13,412 pairs, `DA` 5,906, `DOS` 3,033, then second surnames, `SILVA` 2,869), accents only (21.1%; 255 of them SÁ / SA pairs read with two surnames until #857), words shortened (15.8%), words misspelled (14.9%) and words left out and shortened (11.8%). Read the agreement per shape, since a shape can change the surname legitimately: a pair that leaves out the last surname ends the family in another word, which is likely most of why only 44% of words left out agree (not measured apart from the other causes). Accents only cannot change the surname, so its 1,304 of 43,552 pairs that disagree are the parser reading one name two ways: by their last words, `JÚNIOR` against `JUNIOR` in 866 (#843) and `SÁ` against `SA` in 255, where `MARIA DE SA` read `SA` as a credential and `MARIA DE SÁ` as the surname until #857 took `sa` out of the vocabulary. The run took 39s in one process (15.8s in workers, 2026-10-27). `jrc-names` reads a gzip downloaded once into the cache, and refuses one whose sha256 is not `JRC_SHA256`: the JRC says the resource is updated daily, but the file served on 2026-10-24 was last modified on 2024-03-15, so a new file is measured and the pin moved by hand rather than read under constants measured on another. A download that is not the pinned file replaces nothing: it is kept beside the cached one as `entities.gzip.new`, to be measured, and adopted without another download once the pin moves to it, since the JRC serves only its current file and the pinned one could not be fetched again. For the same reason `fetch --refresh` downloads only where the cached file is not the pinned one; otherwise it reads the cached file again. `meta.json` records the pin, `JRC_READ_VERSION` and the Unicode version `script()` read, and a corpus fetched under another of any is refused on load, so a change to how a spelling is read or its script labelled is not counted under the old records. It keeps the person rows (`P`, 1,338,463 of 1,445,013 lines) and reads past the organisations (`O`). It drops every row the JRC marks with a language (`ru`, `ar`, `sl`, `et`, `pl` and others, 20,819 of the person rows), counted by language in `meta.json`'s detail, on the JRC's marking alone. Where measured, a marked row is a morphological variant of a spelling the JRC leaves unmarked (`u`): an inflected form, or an Arabic spelling with و, ل or ال glued on. Every marked row's entity held an unmarked spelling, and 18,594 of the 20,819 had as many words as one and differed from it only in endings or in glued fronts of three letters or fewer (the rule is stated exactly at `JRC_UNMARKED` in `local_jrc.py`); the other 2,225, 1,680 of them Arabic, fit neither as stated and were not measured further. The unmarked spellings still hold inflected forms the JRC did not mark (by the same rule, 22,732 of the 66,673 distinct unmarked Cyrillic spellings are another Cyrillic spelling of the same person), which are kept. A name's `+` and whitespace are read as single spaces, and an id is kept as written. A line that is not four well-formed columns (the file's first line, `#`, is one) is counted, and past `JRC_MAX_BAD` refuses the file, as do a gzip cut short, a file ending inside a line, person rows under `JRC_MIN_PERSONS` of the lines (a type renamed), more marked rows than `JRC_MAX_MARKED` (a file that marks every spelling), more persons left with only marked spellings than `JRC_MAX_LOST` (none were), and more repeated spellings than `JRC_MAX_REPEATED` (58 were). 99 spellings hold a replacement character (U+FFFD), damage in the source; they are kept and counted. The licence bars redistributing the resource or anything derived from it, so its snapshot, its views' output and every file derived from it stay in the cache, and what is cited from it is counts and shapes written with made-up names. A snapshot of it (`snapshot.py --local jrc-names`) recorded 1,315,051 names in 30s on 12 CPUs (2026-10-24, 128 MB). -`groups` reads a source whose records carry an entity and a script (`jrc-names`, `opensanctions-parliaments`) as several spellings of one person. It parses every spelling of each person with two or more and compares the readings' structure: whether a title, a suffix, a given name and a family name are read, how many words the family is, and where it stands among the given, middle and family words (one run at the front or the end, all of them, none, or otherwise, which 1 of the 1,315,051 distinct spellings is). Words are not compared, so spellings in two scripts can be; but where the family stands moves with a script's order, so a script read family first (Hangul, spaced Han) differs from one read given first in that field by convention, not by error. It counts PERSONS, not pairs, so a person spelled 600 ways weighs what one spelled twice does. A pair of scripts is one row, and a spelling whose letters are in two scripts keys one as `mixed`: within one script (`Latin / Latin`) a field differs where the person's spellings in it read it more than one way, and they read alike where all read one way; across two (`Cyrillic / Latin`) a field differs where no spelling in one reads it as any in the other does, so two Latin spellings that differ between themselves are not counted against the Cyrillic one, and they read alike where some spelling in one reads, in every field, as some spelling in the other. A person across two scripts can be neither: every field has a value in common, yet no one spelling matches; the report counts those as `no one field` (0.4% of Han / Latin, less elsewhere), so each pair's persons are alike, apart in a field, or there. It then lists the title and suffix words of the persons some of whose spellings read one and others none (two spellings with two different titles and no untitled one add nothing), by the persons sharing a word, ten at least: the lead is a word the vocabulary reads as a title or suffix that is a name in some spelling, or a title spelled in a way it does not know. +`groups` reads a source whose records carry an entity and a script (`jrc-names`, `opensanctions-parliaments`) as several spellings of one person. It parses every spelling of each person with two or more and compares the readings' structure: whether a title, a suffix, a given name and a family name are read, how many words the family is, and where it stands among the given, middle and family words (one run at the front or the end, all of them, none, or otherwise, which 1 of `jrc-names`' 1,315,051 distinct spellings was on its fetch of 2026-10-24). Words are not compared, so spellings in two scripts can be; but where the family stands moves with a script's order, so a script read family first (Hangul, spaced Han) differs from one read given first in that field by convention, not by error. It counts PERSONS, not pairs, so a person spelled 600 ways weighs what one spelled twice does. A pair of scripts is one row, and a spelling whose letters are in two scripts keys one as `mixed`: within one script (`Latin / Latin`) a field differs where the person's spellings in it read it more than one way, and they read alike where all read one way; across two (`Cyrillic / Latin`) a field differs where no spelling in one reads it as any in the other does, so two Latin spellings that differ between themselves are not counted against the Cyrillic one, and they read alike where some spelling in one reads, in every field, as some spelling in the other. A person across two scripts can be neither: every field has a value in common, yet no one spelling matches; the report counts those as `no one field` (0.4% of Han / Latin, less elsewhere), so each pair's persons are alike, apart in a field, or there. It then lists the title and suffix words of the persons some of whose spellings read one and others none (two spellings with two different titles and no untitled one add nothing), by the persons sharing a word, ten at least: the lead is a word the vocabulary reads as a title or suffix that is a name in some spelling, or a title spelled in a way it does not know. ``` uv run python tools/differential/local_corpora.py groups jrc-names @@ -351,7 +352,7 @@ uv run python tools/differential/local_corpora.py groups jrc-names On the fetch of 2026-10-24 (data dated 2024-03-15), 93.7% of the 218,822 persons with two or more spellings read alike in every spelling, and the run took 50s (11.8s in workers, 2026-10-27). Within a script the disagreement is mostly the writing, not the parse. Katakana / Katakana reads alike for 0.2% of its 4,289 persons because the JRC writes a transliterated name three ways: unspaced and undivided, which the parser cannot divide and reads as a given name alone (4,347 of the 13,039 Katakana spellings), divided by `・` with no space (4,337), and spaced (4,355), the last two read given then family. Han / Han, 2.2% of 2,420, holds unspaced Han, read as one family word, beside spaced Han, read family first, and Han divided by `·`, read in its written order. Arabic / Arabic reads alike for 67.8% of 3,329 persons, and the Arabic comma is most of why: each of the 736 persons with a spelling holding one differs, of the 1,072 that differ, since the comma moves the family to the front. Across scripts read in the same order most persons read alike (Cyrillic / Latin 99.3% of 20,837, Arabic / Latin 98.2% of 5,347, Greek / Latin 98.6% of 915); Hangul against a script read given first reads alike for 3% or fewer in every such row `--top 40` lists (Hangul / Latin 2.0% of 1,247), its family standing first, while Han / Hangul, both read family first, is 87.1% of 1,002. The title words read in some spellings only start `sheikh` 50, `bard` 33, `shaikh` 27, `sir` 23, `executive` 22 and include `mahdi` 17, a common given name; the suffix words `jr` 62, `sa` 38, `iii` 27, `ii` 27. -`alike` reads the spelling views as one flag per person, for a source whose records pair spellings (`ALIKE_SOURCES`: `jrc-names`' and `opensanctions-parliaments`' persons, `nepal-candidates`' romanized and Devanagari pairs, `tse-donors`' filed and registry pairs): whether the person's spellings read alike, as `groups` compares them for a person, the two readings' structure for a Nepali pair, and one shared family last word, as `pairs --agreement` counts it, for a filed pair that differs. With `--base` it prints how many persons (`jrc-names`, `opensanctions-parliaments`) or pairs now read alike and how many now apart, the counts phase 2j quoted for each batch. It counts flips only: a person whose spellings all read differently and still alike is no move here, though the local snapshot shows it. The base's flags are kept under `alike/` beside the corpus, keyed like the baselines (the fetch, the base's `nameparser/` files, the interpreter's minor version, and the view's code, `alike_fingerprint`), read in a child process where none is kept, and published under their key only once whole and once the base's digest, taken again, is unchanged. A key holds no name: a person is its entity or its record's place in `raw.jsonl`. With `--languages ne` it reads the tree under that choice of languages (`Locale.languages`) and counts the persons or pairs the choice moves against the default's flags, the tree's own or `--base`'s, as `snapshot.py --languages` does for the names: the pair measure a language pack reads. Both read the choice alone, never a registered pack's lexicon fragment or policy patch, which is the whole of a pack only where the pack is nothing but its choice, as `locales.NE` is, the RFC's "Measuring a pack" (`locales.NE`, 2026-10-30: 211 nepal-candidates pairs now alike, 4 now apart). +`alike` reads the spelling views as one flag per person, for a source whose records pair spellings (`ALIKE_SOURCES`: `jrc-names`' and `opensanctions-parliaments`' persons, `nepal-candidates`' romanized and Devanagari pairs, `tse-donors`' filed and registry pairs): whether the person's spellings read alike, as `groups` compares them for a person, the two readings' structure for a Nepali pair, and one shared family last word, as `pairs --agreement` counts it, for a filed pair that differs. With `--base` it prints how many persons (`jrc-names`, `opensanctions-parliaments`) or pairs now read alike and how many now apart, the counts phase 2j quoted for each batch. It counts flips only: a person whose spellings all read differently and still alike is no move here, though the local snapshot shows it. The base's flags are kept under `alike/` beside the corpus, keyed like the baselines (the fetch, the base's `nameparser/` files, the interpreter's minor version, and the view's code, `alike_fingerprint`), read in a child process where none is kept, and published under their key only once whole and once the base's digest, taken again, is unchanged. A key holds no name: a person is its entity or its record's place in `raw.jsonl`. With `--languages ne` it reads the tree under that choice of languages (`Locale.languages`) and counts the persons or pairs the choice moves against the default's flags, the tree's own or `--base`'s, as `snapshot.py --languages` does for the names: the pair measure a language pack reads. Both read the choice alone, never a registered pack's lexicon fragment or policy patch, which is the whole of a pack only where the pack is nothing but its choice, as `locales.NE` was until #1254 gave it `initials_as_family`, the RFC's "Measuring a pack" (`locales.NE`, 2026-10-30: 211 nepal-candidates pairs now alike, 4 now apart). ``` uv run python tools/differential/local_corpora.py alike jrc-names --base ../master-checkout @@ -384,17 +385,17 @@ uv run python tools/differential/config_diff.py diff default 'expr:Parser(lexico uv run python tools/differential/config_diff.py score default plain:ES --switches two_family_names,two_given_names --languages es ``` -**Measuring a change to name matching.** A change to `nameparser/_match.py`, or to the vocabulary it reads (`same_as`, `familiar` and the particles), moves no parse, so the steps above all report none; `match_diff.py --base ` is its check (#1278). It reads one fixed draw of name pairs -- every pair `tests/v2/test_match.py` writes, seeded pairings of those names, and where present jrc-names spellings of one entity and of different entities sharing a last word (mostly different people, where a key-guarantee miss shows), tse-donors' filed and registry names, and PatentsView inventors' spellings of themselves -- under twenty-two settings (the default, each opt-in added, every opt-in, each default outcome but `same` taken out, other readings on with the default and with every opt-in, and `locales.ES` with each of those two), in a child process per tree, and prints every pair whose `check` result or keys moved, grouped by what moved (a role's outcome, the verdict, the cross-role matches, the reading used, the keys), with the setting and the pair; and every pair the head reads consistent that shares no key, the guarantee `keys` gives. A refactor expects no moves, and any exits 1. A clean run vouches only for the shapes its draw holds: it draws its pairs from tests/v2/test_match.py and the corpora, so a change to a shape no drawn pair holds reports 0 moves (#1390 moved 0 of 687,500 rows until its own test rows existed). Add the change's rows to the test file first, then read the run. The two local corpora come from `local_corpora.py fetch`; PatentsView's pairs need its raw table, `g_inventor_not_disambiguated.tsv.zip` of the pinned release, put by hand at the cache's `patentsview-probe/`, since the `patentsview-inventors` fetch reads that table and keeps only an extract with no inventor's id. A source not present is left out with a note saying how to get it, and one present but unreadable stops the run rather than shrinking the measurement. The base's results are kept in the cache under its package's digest, as `snapshot.py --local --base` keeps a base, so the second run reads only the head. A whole run over the three corpora, 30,128 pairs and 602,560 rows, took 1m57s reading both sides with `--jobs 8` on a 12-CPU machine (2026-11-09), about half that once the base is kept; `--sample N` reads every Nth pair. Its proof that it can report a move: taking the family chain's particles-aside step out of `_match.py` moves 426 of 282,560 rows over the test pairs alone, every one `family: particles-aside -> part-of-other` (2026-11-09; `tests/v2/test_match_diff.py` runs the same mutation over three pairs). An outcome's rank alone is not such a mutation: it orders `Outcome.strength` and the pick among other readings, and the row a pair reads is decided by the order the comparator tries the outcomes in, so swapping two ranks (`part-of-other` and `initial`) moved no row of a 1-in-20 sample of them, 14,140 rows. +**Measuring a change to name matching.** A change to `nameparser/_match.py`, or to the vocabulary it reads (`same_as`, `familiar`, `spelling` and the particles), moves no parse, so the steps above all report none; `match_diff.py --base ` is its check (#1278). It reads one fixed draw of name pairs -- every pair `tests/v2/test_match.py` writes, seeded pairings of those names, and where present jrc-names spellings of one entity and of different entities sharing a last word (mostly different people, where a key-guarantee miss shows), tse-donors' filed and registry names, and PatentsView inventors' spellings of themselves -- under twenty-two settings (the default, each opt-in added, every opt-in, each default outcome but `same` taken out, other readings on with the default and with every opt-in, and `locales.ES` with each of those two), in a child process per tree, and prints every pair whose `check` result or keys moved, grouped by what moved (a role's outcome, the verdict, the cross-role matches, the reading used, the keys), with the setting and the pair; and every pair the head reads consistent that shares no key, the guarantee `keys` gives. A refactor expects no moves, and any exits 1. A clean run vouches only for the shapes its draw holds: it draws its pairs from tests/v2/test_match.py and the corpora, so a change to a shape no drawn pair holds reports 0 moves (#1390 moved 0 of 687,500 rows until its own test rows existed). Add the change's rows to the test file first, then read the run. The two local corpora come from `local_corpora.py fetch`; PatentsView's pairs need its raw table, `g_inventor_not_disambiguated.tsv.zip` of the pinned release, put by hand at the cache's `patentsview-probe/`, since the `patentsview-inventors` fetch reads that table and keeps only an extract with no inventor's id. A source not present is left out with a note saying how to get it, and one present but unreadable stops the run rather than shrinking the measurement. The base's results are kept in the cache under its package's digest, as `snapshot.py --local --base` keeps a base, so the second run reads only the head. A whole run over the three corpora, 30,128 pairs and 602,560 rows, took 1m57s reading both sides with `--jobs 8` on a 12-CPU machine (2026-11-09), about half that once the base is kept; `--sample N` reads every Nth pair. Its proof that it can report a move: taking the family chain's particles-aside step out of `_match.py` moves 426 of 282,560 rows over the test pairs alone, every one `family: particles-aside -> part-of-other` (2026-11-09; `tests/v2/test_match_diff.py` runs the same mutation over three pairs). An outcome's rank alone is not such a mutation: it orders `Outcome.strength` and the pick among other readings, and the row a pair reads is decided by the order the comparator tries the outcomes in, so swapping two ranks (`part-of-other` and `initial`) moved no row of a 1-in-20 sample of them, 14,140 rows. ``` uv run python tools/differential/match_diff.py --base ../master-checkout ``` -**Measuring a change to the group suggester.** `Parser.suggest` moves no parse either, so its check is `suggest_measure.py`: it draws groups of 2 to 200 names (`--sizes`, `--trials`, `--seed`) from populations whose order is known because each name is composed from the boxes its filer typed it into -- PatentsView inventors by country, UK company filers (`psc-individuals`) by nationality, Czech candidates, Vietnamese names, the Russian inventors whose given box holds a patronymic (`pv-RU-patronymic`, the list the East Slavic rule is decided on), ORCID's bylines (and the ones written two or three joined initials first) and the ORCID holders who typed one box wholly in capitals (and the ones whose family box is two or three letters), all local corpora -- writes each group given-first and family-first, and prints the share of groups whose suggested `name_order` writes the family at the end the group was written with, under a given-first and a family-first base. The two rows where the group is written in its base's own order are the anti-goal (decisions/group-suggestion): a suggestion must not move a group the base already reads right, and the thresholds in `nameparser/_suggest.py` were chosen so that neither falls below 95% at any size, save `orcid-givcaps`' two, names typed with the given name 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 names, and at 200 until #1357 (bylines written `AM Hoy` and nothing else), one of two cuts added with #1355 to hold the short capitals words in view and explained in that file's 2026-11-14 #1355 entry; the other, `orcid-famcaps-short` (`Zhi LI`), left the list with #1397 (that file's 2026-11-14 #1397 entry). Under the order table it prints the share of groups deciding `capitals_as_family` (rules/O9), for every population where any group did, and `--base` lists those cells too. It also prints each population's votes per name (right, wrong, contested, none) and per signal, with `--wrong-words N` each signal's commonest words in a wrong vote; the opensanctions-parliaments table of the 2026-11-10 TURKIC entry; and every parliament list's own suggestion, under the two bases and `FAMILY_FIRST_GIVEN_LAST`, beside the order it was read by eye to write. Its draws run under the two bases only, so what a suggestion does under `FAMILY_FIRST_GIVEN_LAST`, and the East Slavic rule beside `capitals_as_family`, are held by tests (decisions/group-suggestion, 2026-11-15 #1356). `--set NAME=VALUE` tries another threshold without editing the module, and is the harness's proof that it can report a difference: `--set _MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000` decides nothing (the second holds the patronymic rule, which decides a given-first order of its own, save where #1356 keeps the family-first base's), so every group written against its base reads 0% (all 60 such rows, at all eight sizes, on 2026-11-15). `--checks` prints, instead of the tables, the per-name checks the decisions entry quotes (the short romanized surnames' wrong votes, names ending in a bare non-ASCII letter, and, over the groups holding enough names of one patronymic rule to decide it, whether the patronymic share's denominator decides any differently without the contested names). `--base ` measures another tree in a child process and lists the cells that moved, the populations whose count of groups deciding the East Slavic rule moved, and the parliament tables' rows that moved. A source present but yielding no names, and a population or parliament list a present source holds none of, prints a note. A whole run with every source fetched took 20s with `--jobs 12` on one 12-CPU machine (2026-11-10, sizes 2 to 200; a machine-bound figure). +**Measuring a change to the group suggester.** `Parser.suggest` moves no parse either, so its check is `suggest_measure.py`: it draws groups of 2 to 200 names (`--sizes`, `--trials`, `--seed`) from populations whose order is known because each name is composed from the boxes its filer typed it into -- PatentsView inventors by country, UK company filers (`psc-individuals`) by nationality, Czech candidates, Vietnamese names, the Russian inventors whose given box holds a patronymic (`pv-RU-patronymic`, the list the East Slavic rule is decided on), ORCID's bylines (and the ones written two or three joined initials first) and the ORCID holders who typed one box wholly in capitals (and the ones from China, Korea, Vietnam and Taiwan, `orcid-famcaps-ea`, and the ones whose family box is two or three letters), all local corpora -- writes each group given-first and family-first, and prints the share of groups whose suggested `name_order` writes the family at the end the group was written with, under a given-first and a family-first base. The two rows where the group is written in its base's own order are the anti-goal (decisions/group-suggestion): a suggestion must not move a group the base already reads right, and the thresholds in `nameparser/_suggest.py` were chosen so that neither falls below 95% at any size, save `orcid-givcaps`' two, names typed with the given name 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 names, and at 200 until #1357 (bylines written `AM Hoy` and nothing else), one of two cuts added with #1355 to hold the short capitals words in view and explained in that file's 2026-11-14 #1355 entry; the other, `orcid-famcaps-short` (`Zhi LI`), left the list with #1397 (that file's 2026-11-14 #1397 entry). Under each population it prints the groups that decided the East Slavic rule and those that decided `initials_as_family` (rules/O8); under the order table, the share of groups deciding `capitals_as_family` (rules/O9), for every population where any group did, and `--base` lists those cells too. It also prints each population's votes per name (right, wrong, contested, none) and per signal, with `--wrong-words N` each signal's commonest words in a wrong vote; the opensanctions-parliaments table of the 2026-11-10 TURKIC entry; and every parliament list's own suggestion, under the two bases and `FAMILY_FIRST_GIVEN_LAST`, beside the order it was read by eye to write. Its draws run under the two bases only, so what a suggestion does under `FAMILY_FIRST_GIVEN_LAST`, and the East Slavic rule beside `capitals_as_family`, are held by tests (decisions/group-suggestion, 2026-11-15 #1356). `--set NAME=VALUE` tries another threshold without editing the module, and is the harness's proof that it can report a difference: `--set _MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000 --set _MIN_RUN_NAMES=1000000` decides nothing (the second holds the patronymic rule, which decides a given-first order of its own, save where #1356 keeps the family-first base's, and the third the letters signal's `initials_as_family`, which the two vote counts leave free to decide), so every group written against its base reads 0% (all 60 such rows, at all eight sizes, on 2026-11-15, measured with the first two). `--checks` prints, instead of the tables, the per-name checks the decisions entry quotes (the short romanized surnames' wrong votes, names ending in a bare non-ASCII letter, and, over the groups holding enough names of one patronymic rule to decide it, whether the patronymic share's denominator decides any differently without the contested names). `--base ` measures another tree in a child process and lists the cells that moved, the populations whose count of groups deciding the East Slavic rule moved, and the parliament tables' rows that moved. A source present but yielding no names, and a population or parliament list a present source holds none of, prints a note. A whole run with every source fetched took 20s with `--jobs 12` on one 12-CPU machine (2026-11-10, sizes 2 to 200; a machine-bound figure). ``` uv run python tools/differential/suggest_measure.py -uv run python tools/differential/suggest_measure.py --set _MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000 +uv run python tools/differential/suggest_measure.py --set _MIN_VOTES=1000000 --set _MIN_PATRONYMIC_VOTES=1000000 --set _MIN_RUN_NAMES=1000000 ``` For a vocabulary word whose reading acts on a name position, `tools/vocab/word_report.py` gives the per-word view before and alongside this: the word in a grid of shapes, its incidence in every fetched local corpus, and its `name_usage.py` rows (`nameparser/vocab/README.md`, "Adding a word"). @@ -511,8 +512,10 @@ behind a non-default `Policy` field is invisible here. Default *vocabulary* is a different matter: it is fully in EFFECT, never gated off the way a `Policy` field is, so a change to it can show up here. That is not the same as coverage -- only 5 of the 17 shipped -`maiden_markers` and 8 of the 15 `honorific_tails` appear anywhere in -the corpora (re-measured 2026-08-26; the marker count was 3 until +`maiden_markers` and 13 of the 28 `honorific_tails` appear anywhere in +the corpora (re-measured 2026-11-16; the tails were 8 of 15 on +2026-08-26, both counts growing with the CJK honorifics added since; +the marker count was 3 until #414's rules corpus brought in a parenthesized `Nee`, the denominator was 17 until `roz` left the vocabulary in 2.2 -- it appeared in no corpus name, so only the denominator moved -- and #434's `z domu` then @@ -541,7 +544,7 @@ uv run python - <<'PY' import glob, json from nameparser import Parser from nameparser._lexicon import _normalize -L = Parser().lexicon +L = Parser().lexicon._sets # the compiled sets are internal since 3.0 def _n(x): return x if isinstance(x, str) else x['name'] names = [_n(json.loads(l)) for f in glob.glob('tools/differential/corpus*.jsonl') for l in open(f, encoding='utf-8') if l.strip()] for s in ('maiden_markers', 'honorific_tails'): @@ -570,7 +573,7 @@ is opt-in about them is narrower than it looks (rows measured Row 1 carries no marker word, so it isolates the delimiter: the brackets alone route their content to `maiden`, and only once the policy says they do. Row 2 carries no brackets, so it isolates the -marker: `Lexicon.maiden_markers` ships 17 entries by default, `nee` +marker: the default vocabulary ships 17 maiden markers (2026-11-16), `nee` among them, and the bare form needs no configuration at all. So what is opt-in is neither the marker words nor the delimited path @@ -596,18 +599,18 @@ data can. and say why in the commit. Run it without `--record` for per-role agreement counts. Nothing is special-cased: an unnatural rendering or a modelling difference (CLDR's `さん` title is a suffix here) simply stays a recorded disagreement, which makes the record a measured worklist as well as a guard. -A second view measures the locale packs (#672). `LOCALE_FILES` in `cldr_agreement.py` maps each CLDR file to the pack for its language (`zh`, `zh_Hant`, `yue`, `yue_Hans` → `ZH`; `ja` → `JA`; `ne` → `NE`; `ru` → `RU`; `tr`, `az` → `TR_AZ`); those renderings are parsed with `parser_for(pack)`, over the same `FAMILY_FIRST` base where CLDR's order is surnameFirst, and their disagreements go to `cldr_agreement_locales.json`, ratcheted per pack by the same test. The native-script Wikidata source's strata of a pack's language are mapped by `NATIVE_LABELS` (`zh-cn`, `zh-tw` → `ZH`; `ja-jp` → `JA`; `ne-np` → `NE`), since their file is a QID that names no language, and the view parses them the same way into `wikidata_native_agreement_locales.json`. Each source's pack is read from its own rendering key (`locale_sources()`: CLDR's file, the native source's stratum), so a recorded rendering that is gone is still checked by its pack. The summary prints, per pack, how many of its renderings agree in every role under the default parser and under the pack, so a pack PR shows what it moved on its own language. A new pack adds its files to `LOCALE_FILES`, or its name to `NO_CLDR`; the test fails on a pack in neither. The modelling differences stay recorded here too: a pack is not meant to agree with CLDR where the models differ by design. +A second view measures the locale packs (#672). `LOCALE_FILES` in `cldr_agreement.py` maps each CLDR file to the pack for its language (`zh`, `zh_Hant`, `yue`, `yue_Hans` → `ZH`; `ja` → `JA`; `ne` → `NE`; `ru` → `RU`; `tr`, `az` → `TR_AZ`; `cs`, `sk`, `sl`, `hr`, `ga`, `gd`, `es`, `vi`, `mn`, `ar`, `he` → the pack of that name; `pt` → `PT_BR`; `hi`, `hi_Latn` → `HI`; `bn` → `BN`); those renderings are parsed with `parser_for(pack)`, over the same `FAMILY_FIRST` base where CLDR's order is surnameFirst, and their disagreements go to `cldr_agreement_locales.json`, ratcheted per pack by the same test. The native-script Wikidata source's strata of a pack's language are mapped by `NATIVE_LABELS` (`zh-cn`, `zh-tw` → `ZH`; `ja-jp` → `JA`; `ne-np` → `NE`; `hi-in` → `HI`; `bn-in`, `bn-bd` → `BN`), since their file is a QID that names no language, and the view parses them the same way into `wikidata_native_agreement_locales.json`. Each source's pack is read from its own rendering key (`locale_sources()`: CLDR's file, the native source's stratum), so a recorded rendering that is gone is still checked by its pack. The summary prints, per pack, how many of its renderings agree in every role under the default parser and under the pack, so a pack PR shows what it moved on its own language. A new pack adds its files to `LOCALE_FILES`, or its name to `NO_CLDR`; the test fails on a pack in neither. The modelling differences stay recorded here too: a pack is not meant to agree with CLDR where the models differ by design. **The GND source.** `build_gnd_corpus.py` writes the GND's name parts in CLDR's field vocabulary (`forename` → `given`, `prefix` → `surname-prefix` with a one-word `surname` as `surname-core`, any other family → `surname` whole, `counting` → `generation`, and a `personalName` -- a person entered under the whole name, with no surname -- as `given` alone, so the family is expected empty), so `cldr_agreement.py` compares `gnd_fields.jsonl` by the same rules and records its disagreements in `gnd_agreement.json`, ratcheted by the same test. The locale view does not read it: no pack covers its names. A composed rendering says so (`composed: true`); where a particle is glued to the surname (`d'Arenberg`, `al-Ǧaʿfarī`) the composed line states the glued word as a whole `surname`, since the comparison matches fields word by word, and the index form, where the particle is a word of its own, keeps the split. A family with no `prefix`, or with a surname of several words, is stated whole for the same kind of reason: GND does not split a particle inside a surname (`Vélez de Guevara`, `Zuylen van Nijevelt`), so what it leaves unsplit means "not stated", not "no particle", and only `family` is compared there. Raw lobid responses are cached outside the tree, in a `gnd/` directory under `$NAMEPARSER_TOOLS_CACHE` (default `~/.cache/nameparser-tools`); `--refresh` fetches them again. The build stops before writing anything when a stratum falls below its floor, a query matches nothing, or a pool pages short, so a lobid change fails it rather than shrinking the corpus; `--record` prints, per source, how many changes of each kind it accepts. **Adding a source.** Map only what the source states. The comparison reads a missing field as a statement that the role is empty, so a field the source leaves unstated must be mapped so that its role is not compared at all: #688's first build wrote a prefixless GND surname as `surname-core`, and 19 renderings recorded the parser's `de` in `Vélez de Guevara` as a disagreement no fix could clear; its fix then missed the same gap inside a several-word core after a prefix (`Zuylen van Nijevelt, Julius van`), so test each way a field can be left unstated, not the one that was reported. A field must also occur in its rendering's text, word by word (`test_every_committed_field_occurs_in_its_rendering`), or it is expected empty too. Size a stratum from the yield it has in the build, not on its own: strata that share a country take no one an earlier one took, so a yield measured alone overstates what the build gets. #862 measured its India strata one at a time, and Indian Urdu's 17 aligned names of 3,000 were 12 in build order, behind Bengali, Hindi and Marathi, exactly its quota; measure a new stratum with the strata before it filled to their quotas. A build must fail rather than shrink: give every stratum a floor, check a response's shape before caching it (an API error arrives as HTTP 200), and raise on a query that matches nothing. But tell a broken fetch from a fact about the data: #689's first fix raised on any item Wikidata reported missing, so one deleted name-part item anywhere in a pool would have stopped every rebuild, with `--refresh` advice that could not help; a missing part now only refuses the person stating it. A source sampled by script must check each text's script itself: Wikidata's `mul` labels are Latin, and the native-script build's first probe kept `Anushka Sharma` as a Hindi name. And give each refusal a test row that fails for the reason it names, not for another: that build's review found an all-Hebrew text standing for "a Hebrew point is not Arabic", which passed with the mark check deleted. A builder change has one oracle the suite cannot run, since it needs the local cache: rebuild offline from `$NAMEPARSER_TOOLS_CACHE` and diff the result against the committed fields file. The same review's mutation pass scored every surviving mutation that way, and four of them would have moved committed rows or the figures quoted from them with every test passing. The fetch (`fetch_bytes`: User-Agent, timeout, optional POST body and politeness delay), the cache (`cache_dir`, `cached_json`, which checks a response before caching it and writes atomically) and the two output files (`corpus_lines`, `fields_lines`, `write_corpus`) are shared in `corpus_build.py`, and the two Wikidata builders share their stratum loop (`build_strata` in `build_wikidata_corpus.py`: a person taken once across strata, the missing-person stop, the floor stop) as well as the pool check; a new builder imports them rather than copying another builder's, because a guard added to one copy is how #696 happened. -**The Wikidata source.** `build_wikidata_corpus.py` exists for the two fields no other open source labels, and states them in `wikidata_fields.jsonl` as `surname2` (P1950, CLDR's own field name) and `patronymic` (P5056, which CLDR has no field for), beside `given` (P735) and `surname` (P734); its disagreements are in `wikidata_agreement.json`. A person's written names are token-aligned to the parts rather than composed from them: a text is kept only where every word is claimed by exactly one part, a connective (`bin`, `i`, `y`) joining the part after it, and a woman's Russian surname may match the feminine form of its item's label. `cldr_agreement.py` lists `surname2` and `patronymic` in `PENDING_ROLES` and scores them inside `family` and `given_names` respectively -- a patronymic is not a family name, so `Vigdís Finnbogadóttir` expects the family empty -- and also scores each on its own once ParsedName has an attribute of that name: `patronymic` since 3.0's 4c (rules/R9) and `surname2` since 4d (rules/R10), the merged scoring kept. Only `two_family_names` fills `surname2`, so the record holds every stated second surname, CLDR's included, as not read (decisions/R10 measures it with the switch on). A stratum that falls below its floor, a query that matches nothing, a pool short of its size (unless the stratum is marked `whole`, which a full pool then contradicts) and a response that is not what was asked for each stop the build before anything is written; Iceland (270 of a pool of 600 on 2026-10-16, measured in the native paragraph below) and Malaysia are marked `whole`; Malaysia's floor is set below its quota because only 17 Malaysian public figures with a P5056 statement matched the query on 2026-10-16, and 9 of them aligned. Raw responses are cached outside the tree, in a `wikidata/` directory under `$NAMEPARSER_TOOLS_CACHE` (default `~/.cache/nameparser-tools`); `--refresh` fetches them again. +**The Wikidata source.** `build_wikidata_corpus.py` exists for the two fields no other open source labels, and states them in `wikidata_fields.jsonl` as `surname2` (P1950, CLDR's own field name) and `patronymic` (P5056, which CLDR has no field for), beside `given` (P735) and `surname` (P734); its disagreements are in `wikidata_agreement.json`. A person's written names are token-aligned to the parts rather than composed from them: a text is kept only where every word is claimed by exactly one part, a connective (`bin`, `i`, `y`) joining the part after it, and a woman's Russian surname may match the feminine form of its item's label. `cldr_agreement.py` lists `surname2` and `patronymic` in `PENDING_ROLES` and scores them inside `family` and `given_names` respectively -- a patronymic is not a family name, so `Vigdís Finnbogadóttir` expects the family empty -- and also scores each on its own once ParsedName has an attribute of that name: `patronymic` since 3.0's 4c (rules/R9) and `surname2` since 4d (rules/R10), the merged scoring kept. Only `two_family_names` (and, under `locales.ZH`, a Han surname pair) fills `surname2`, and the record is the default's, so it holds every stated second surname, CLDR's included, as not read (decisions/R10 measures it with the switch on). A stratum that falls below its floor, a query that matches nothing, a pool short of its size (unless the stratum is marked `whole`, which a full pool then contradicts) and a response that is not what was asked for each stop the build before anything is written; Iceland (270 of a pool of 600 on 2026-10-16, measured in the native paragraph below) and Malaysia are marked `whole`; Malaysia's floor is set below its quota because only 17 Malaysian public figures with a P5056 statement matched the query on 2026-10-16, and 9 of them aligned. Raw responses are cached outside the tree, in a `wikidata/` directory under `$NAMEPARSER_TOOLS_CACHE` (default `~/.cache/nameparser-tools`); `--refresh` fetches them again. **The native-script Wikidata source.** `build_wikidata_native_corpus.py` exists because every other real-name corpus is Latin script, apart from Wikidata's Russian patronymics, so the script-conditional readings (family-first Han, Hangul and kana; Korean surname segmentation) had been tested only against CLDR's invented names. No text holds an honorific, so the corpus does not exercise the CJK honorific peel; it shows only that the peel leaves plain names alone. It reuses `build_wikidata_corpus.py`'s fetches and token alignment and adds the following. Strata are a country and a language, not a property, and the query keeps people with a label in that language. A text is used only if every letter and combining mark is in the stratum's script (`mul` labels are Latin: `Anushka Sharma` would otherwise pass as a Hindi name). Unspaced text is aligned by character under the same exactly-one-part rule, and nothing is inferred: a Chinese item stating only its surname is left out rather than reading the rest of the text as the given name. Feminine surname forms are kept per language (Greek `Λελούδα` for `Λελούδας`, Bulgarian and Kazakh `-ова`, Ukrainian `-ська`), so the filter does not drop women. A Han, kana or Hangul text carries no shape, since the parser reads those scripts family-first by itself and that is what is being tested; pure katakana keeps the order it is written in, as the parser does. Each person gives one rendering, P1559 first, and its disagreements are in `wikidata_native_agreement.json`. On 2026-10-16 every spaced stratum agreed in every role except seven Arabic surnames of two words (`عبد العزيز`, `عز الدين`, `شكر الله`, `ذو الغنى`: the parser reads the first word as a middle name), a Persian double surname, and a Bulgarian name whose two stated family names include what is probably the father's name (`Динко Цветков Дерменджиев`); Hangul agreed on 120 of 120; on 2026-10-23 the 117 Devanagari and Urdu names then added agreed but for two Urdu surnames of two words (`رضا خان`, `اگنی ہوتری`), the Arabic surnames' class; all 85 new Devanagari names carry combining vowel signs and agreed, though none holds a period, so the gap rules/H2's Accepted clause records (a period-marked abbreviation in an abugida) is out of the corpus's reach, and the 32 Urdu names carry no combining mark at all. One Marathi name is stated with its parts swapped (`राहुल बजाज`, given `बजाज`) and so scores as family-first; Han read by default disagrees on every unspaced Chinese name and 49 of 60 Japanese ones, while the locale view reads 74/80 under `ZH` (six surnames it does not segment: `詹`, `卫`, `柯`, `茅`, `华`, `文`) and 59/60 under `JA`. Wikidata's P734 is a convention, not a fact, where the culture has none: an Arabic nisba (`البغدادي`) is entered as a family name, and the corpus scores it as one. `--lc-check` compares each name with the native-script variants of its Library of Congress record (P244), splitting by LC's comma or, in CJK, a space, and counts an LCCN LC no longer has; it runs after the build has written its files, and adds nothing to them and filters nothing from them. A pool that comes back shorter than its size stops the build unless its stratum is marked as the whole population (Thailand, Kazakhstan, Bangladesh, Hindi in India, Urdu in Pakistan, Nepal), so a query that starts matching less cannot drift the sample unseen; a stratum so marked whose pool comes back full stops it too, since the mark is then stale. The check is `pooled()` in `build_wikidata_corpus.py`, which both Wikidata builders call; re-pooled on 2026-10-16 (#696), the parent's Iceland returned 270 of a pool of 600 and Malaysia 17 of 240, so both are marked whole, and the other six filled their pools (es 900, mx 600, co 480, ru 660, su 360, ri 240). On 2026-10-16, 99 of the 910 names had an LC variant that splits them, and 96 agreed; the other three are Arabic names whose LC record names a person written the other way round (`Ibrāhīm, Ṣāliḥ` for Wikidata's `إبراهيم صالح`), so the P244 link or the order is suspect, not the split. LC writes most Han variants unspaced, so it confirms almost no Chinese or Japanese split. The first build's 907 corpus lines (904 names new to the snapshot; three Ukrainian names were already in `corpus_wikidata.jsonl`; the 2026-10-23 strata added 117 lines, all new to it) cost about 2.9 s in the corpus-reading test modules and about 0.6 s in the agreement tests, measured locally without coverage on 2026-10-16. Raw responses are cached under `$NAMEPARSER_TOOLS_CACHE`, in `wikidata/` and `lc/`. -**The conventions source.** `conventions_fields.jsonl` states the parts of the hand-written conventions corpus, from the `fields` of `conventions.py`'s rows, and its disagreements are in `conventions_agreement.json`. The names are invented, so the record is a worklist of conventions rather than a measure of real data: a patronymic read as a family name (`Hassan bin Yusof`), a title read as a given name (`U Kyaw Win`). It uses the Wikidata source's `patronymic`, written with its connective (`bin Yusof`), and adds `honorific`, a word of address written after the name (`Bey`, `ssi`, `san`), scored inside `suffix` as nameparser reads `さん` (Derek, 2026-10-16). A row no field can state honestly is left out of the fields file and stays in the corpus, which the snapshot still watches: the kunya `Abu Karim`, the `-né` married form `Szabóné Kiss Éva`, and `arap`/`ole`/`wa`, whose last word is a parent's name or a family name depending on the family. Such a row says why in its `unstated`, and the builder refuses a row with neither `fields` nor `unstated`, so this fields file states a subset of its corpus without a row's fields being lost unseen. Being hand-written, it is also held to two checks the generated sources pass anyway: its fields partition each text word for word (`test_the_fields_partition_their_rendering`), and the scorer raises on a field name no rule reads, for every source. +**The conventions source.** `conventions_fields.jsonl` states the parts of the hand-written conventions corpus, from the `fields` of `conventions.py`'s rows, and its disagreements are in `conventions_agreement.json`. The names are invented, so the record is a worklist of conventions rather than a measure of real data: a patronymic read as a family name (`Hassan bin Yusof`), a title read as a given name (`U Kyaw Win`). It uses the Wikidata source's `patronymic`, written with its connective (`bin Yusof`), and adds `honorific`, a word of address written after the name (`Bey`, `ssi`, `san`), scored inside `suffix` as nameparser reads `さん` (decided 2026-10-16). A row no field can state honestly is left out of the fields file and stays in the corpus, which the snapshot still watches: the kunya `Abu Karim`, the `-né` married form `Szabóné Kiss Éva`, and `arap`/`ole`/`wa`, whose last word is a parent's name or a family name depending on the family. Such a row says why in its `unstated`, and the builder refuses a row with neither `fields` nor `unstated`, so this fields file states a subset of its corpus without a row's fields being lost unseen. Being hand-written, it is also held to two checks the generated sources pass anyway: its fields partition each text word for word (`test_the_fields_partition_their_rendering`), and the scorer raises on a field name no rule reads, for every source. `--record` rewrites every record. `JA` needs the `ja` extra (`namedivider-python`), which only CI's `ja-extra` job installs: without it the `JA` ratchet skips, the summary says `not measured`, and `--record` keeps the recorded `JA` entries of both locale records unchanged. Re-record with the extra installed (`uv sync --group dev --extra ja`) when a change moves Japanese. -`_CORPUS_NAMES` in `tests/v2/_differential_fixtures.py` leaves the file out (2026-10-12): the tests reading it carry counts measured over the names the other corpora held. `corpus_gnd.jsonl`, `corpus_wikidata.jsonl` and `corpus_wikidata_native.jsonl` stay in it (2026-10-16): the counts those tests carry are floors and dated snapshots, which a larger corpus cannot falsify, and their invariants now walk all three files' names too. A release figure counts GND's moved names in, its composed renderings included, since the names are real; AGENTS.md's rule of counting out names only `corpus_cldr.jsonl` holds stays CLDR's alone (Derek, 2026-10-16). Wikidata's moved names, native-script ones included, count in under the same rule, which singles out CLDR alone; they are real and written, not composed. `differential_corpus()` in `tests/v2/conftest.py`, which feeds the property tests, globs `corpus*.jsonl`, so it reads CLDR (since #652), GND and both Wikidata files, and the decomposed-twin test walks all their names. +`_CORPUS_NAMES` in `tests/v2/_differential_fixtures.py` leaves the file out (2026-10-12): the tests reading it carry counts measured over the names the other corpora held. `corpus_gnd.jsonl`, `corpus_wikidata.jsonl` and `corpus_wikidata_native.jsonl` stay in it (2026-10-16): the counts those tests carry are floors and dated snapshots, which a larger corpus cannot falsify, and their invariants now walk all three files' names too. A release figure counts GND's moved names in, its composed renderings included, since the names are real; AGENTS.md's rule of counting out names only `corpus_cldr.jsonl` holds stays CLDR's alone (decided 2026-10-16). Wikidata's moved names, native-script ones included, count in under the same rule, which singles out CLDR alone; they are real and written, not composed. `differential_corpus()` in `tests/v2/conftest.py`, which feeds the property tests, globs `corpus*.jsonl`, so it reads CLDR (since #652), GND and both Wikidata files, and the decomposed-twin test walks all their names. diff --git a/tools/differential/compare.py b/tools/differential/compare.py index 5a1640600..f63d3c44c 100644 --- a/tools/differential/compare.py +++ b/tools/differential/compare.py @@ -34,7 +34,7 @@ from typing import NamedTuple HERE = Path(__file__).resolve().parent -DEFAULT_BASELINE = "3.0.0" +DEFAULT_BASELINE = "3.0.1" REPO_ROOT = HERE.parents[1] diff --git a/tools/stage_reads.py b/tools/stage_reads.py new file mode 100644 index 000000000..020ff444a --- /dev/null +++ b/tools/stage_reads.py @@ -0,0 +1,188 @@ +"""List the Lexicon and Policy fields each pipeline stage reads, by tracing. + +Each stage module's docstring declares a ``Reads:`` line, and the release +checklist (root AGENTS.md, step 0) has it checked. A grep for +``lexicon._sets.`` in a module sees only the reads written there +in that spelling: it misses a read through a ``sets = lexicon._sets`` +alias and every read a stage makes through a helper in ``_vocab`` or +``_pieces``. This tool sees those, because it watches the reads happen: +it runs every row of tests/v2/cases.py through the stages one by one, +with the parse's ``Lexicon`` and ``Policy`` wrapped in proxies that +record each attribute read, and charges each read to the stage running. + + uv run python tools/stage_reads.py # every stage + uv run python tools/stage_reads.py --stage classify # one stage + +Each line is one read and one case text that made it: ``L.`` a +vocabulary set read through ``Lexicon._sets``, ``L!`` anything +else read off the lexicon (a method, a public field), ``P.`` a +``Policy`` field. ``group/_comma.decide`` holds the reads of C1's +decision, which group calls and which has a ``Reads:`` line of its own; +``script_segment/_comma.decide`` the same decision asked by script +segmentation, which also runs classify on a trial state, so classify's +reads are charged to it too. + +What it cannot see: a read no case row reaches (a trace is as wide as the +table), and a read inside a ``Lexicon`` method, which is charged to the +method's name. Compare its list against the header by reading both. +""" +from __future__ import annotations + +import argparse +import functools +import sys +from collections import defaultdict +from collections.abc import Callable, Iterable, Iterator +from contextlib import contextmanager +from pathlib import Path +from types import ModuleType +from typing import Protocol + +ROOT = Path(__file__).resolve().parents[1] + + +class CaseLike(Protocol): + text: str + policy: object + locale: str | None + + +#: Reads, per stage: read -> the first case text that made it. +Reads = dict[str, dict[str, str]] + + +class _Recorder: + def __init__(self) -> None: + self.reads: Reads = defaultdict(dict) + self.where = "?" + self.text = "" + + def record(self, read: str) -> None: + self.reads[self.where].setdefault(read, self.text) + + +class _SetsProxy: + def __init__(self, real: object, recorder: _Recorder) -> None: + object.__setattr__(self, "_real", real) + object.__setattr__(self, "_recorder", recorder) + + def __getattr__(self, name: str) -> object: + self._recorder.record(f"L.{name}") + return getattr(self._real, name) + + +class _LexiconProxy: + def __init__(self, real: object, recorder: _Recorder) -> None: + object.__setattr__(self, "_real", real) + object.__setattr__(self, "_recorder", recorder) + object.__setattr__(self, "_proxy_sets", + _SetsProxy(getattr(real, "_sets"), recorder)) + + def __getattr__(self, name: str) -> object: + if name == "_sets": + return self._proxy_sets + if not name.startswith("__"): + self._recorder.record(f"L!{name}") + return getattr(self._real, name) + + +class _PolicyProxy: + def __init__(self, real: object, recorder: _Recorder) -> None: + object.__setattr__(self, "_real", real) + object.__setattr__(self, "_recorder", recorder) + + def __getattr__(self, name: str) -> object: + if not name.startswith("__"): + self._recorder.record(f"P.{name}") + return getattr(self._real, name) + + +@contextmanager +def _charged_apart(module: ModuleType, name: str, + recorder: _Recorder) -> Iterator[None]: + """Charge the reads made inside `module.name` to `/.name`.""" + real: Callable[..., object] = getattr(module, name) + label = f"{module.__name__.rsplit('.', 1)[-1]}.{name}" + + @functools.wraps(real) + def charged(*args: object, **kwargs: object) -> object: + outer = recorder.where + if not outer.endswith(f"/{label}"): # decide calls itself + recorder.where = f"{outer}/{label}" + try: + return real(*args, **kwargs) + finally: + recorder.where = outer + + setattr(module, name, charged) + try: + yield + finally: + setattr(module, name, real) + + +def trace(cases: Iterable[CaseLike], + assembled: Callable[[object], None] | None = None) -> Reads: + """Run each case through the stages and assemble, recording reads. + + `assembled`, where given, is handed each case's ParsedName, which is + how a test holds the traced fold to `Parser.parse`.""" + from nameparser import Parser, locales, parser_for + from nameparser._pipeline import STAGES, _comma + from nameparser._pipeline._assemble import assemble + from nameparser._pipeline._state import ParseState + + recorder = _Recorder() + with _charged_apart(_comma, "decide", recorder): + for case in cases: + if case.locale: + pack = getattr(locales, + case.locale.upper().replace("-", "_")) + parser = parser_for(pack) + else: + parser = Parser(policy=case.policy) if case.policy else Parser() + recorder.text = case.text + state = ParseState( + original=case.text, + lexicon=_LexiconProxy(parser.lexicon, recorder), # type: ignore[arg-type] + policy=_PolicyProxy(parser.policy, recorder), # type: ignore[arg-type] + segmenter=parser.segmenter) + for stage in STAGES: + recorder.where = stage.__name__ + state = stage(state) + recorder.where = "assemble" + name = assemble(state) + if assembled is not None: + assembled(name) + return {stage: dict(reads) for stage, reads in recorder.reads.items()} + + +def _cases() -> tuple[CaseLike, ...]: + sys.path.insert(0, str(ROOT)) + from tests.v2.cases import CASES + return CASES + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=__doc__.split("\n\n", 1)[0] if __doc__ else None) + parser.add_argument("--stage", help="one stage's reads only " + "(its function name, e.g. classify)") + args = parser.parse_args(argv) + reads = trace(_cases()) + stages = sorted(reads) + if args.stage: + stages = [s for s in stages + if s == args.stage or s.startswith(f"{args.stage}/")] + if not stages: + parser.error(f"no reads charged to {args.stage!r}; " + f"the stages are {sorted(reads)}") + for stage in stages: + print(f"== {stage}") + for read in sorted(reads[stage]): + print(f" {read:<40} e.g. {reads[stage][read]!r}") + return 0 + + +if __name__ == "__main__": + sys.exit(main())