Skip to content

Simplify _tokenize.py with no reading moved - #1527

Merged
derek73 merged 5 commits into
masterfrom
refactor/simplify-tokenize
Nov 22, 2026
Merged

derek73 merged 5 commits into
masterfrom
refactor/simplify-tokenize

Conversation

@derek73

@derek73 derek73 commented Nov 22, 2026 •

Copy link
Copy Markdown
Owner

Release checklist step 0: a /simplify pass over nameparser/_pipeline/_tokenize.py, which changed 185 lines since v3.1.0 (#1436's scan rewrite). This is quality only, with no reading moved. The diff touches no other library file: no _vocab.py, _pieces.py, _state.py, _group.py, _classify.py or _suggest.py, and no pattern shared with render.

Changes

  • _BIDI deleted. No library code has read it since Parse cost could fall by about 18% with no reading moved #1436 moved the scan onto the classes built from _BIDI_CHARS.
    • Its only readers were a test, which sliced the + off _BIDI.pattern to rebuild the class, and the class's row in test_regex_sync.py's roster.
    • The test now builds the class from _BIDI_CHARS, and the row goes with the pattern, which test_every_declared_pattern_still_exists requires.
  • Each offset is recorded in the branch that decided it. A comma's offset is appended in the comma branch, and a transcription dot's after both flank checks pass. The tail no longer asks the character's class a second time.
  • The ambiguity tuple is tested before any(). The generator was entered on every parse, even with no ambiguity. The change is one frame fewer on such a parse, inside the band. A new test pins it (below).
  • Comments in the three-part form.
    • The T2 and T3 citations now say which clause the code implements and point at their decisions entries.
    • The bisect comment's measurement moves to decisions/parse-cost, re-measured (below). The comment keeps its code-local reason and points at the scaling row that guards it.
    • The \s/isspace() claim names the test that holds it over every code point.
  • Stale prose corrected. Two docstrings said only the 间隔号 marks a transcription; the fullwidth full stop has too since Should the fullwidth full stop between Han names separate a transcription, as the 间隔号 does? (台邦.撒沙勒 gives one given name) #1312. _flank's "stripped invisibles" read as if it covered _INVISIBLE_SEPARATORS, which are not stripped. The extracted-region note said a dot there is "a mere separator"; it still divides only between classified flanks. The emoji note claimed the bidi marks were integers too.
  • New tests:
    • test_tokenize_asks_no_ambiguity_origin_of_a_parse_without_one (test_benchmark.py) pins the saved generator frame at no call on three names without a report. Its recorded control is one call each on af58ca0, checked by running the test against master's tokenize.
    • test_a_stray_delimiters_report_points_at_the_token_holding_it (test_tokenize.py) puts a stray character at each end of a token and of the name. The test review mutated the bisect (bisect_left, a missing or doubled - 1) and the resolution's gate. test_tokenize.py and the case table passed every one of those mutants; only test_extract.py and test_script_segment.py held them. Each mutant fails three or four of the new rows.
  • decisions/parse-cost gains a 2026-11-22 Simplify _tokenize.py with no reading moved #1527 entry: no row moves, the bisect's re-taken measurement, the frame, and the comparison below with its recipe and control.

No test expectation was edited.

Proof that nothing moved

  • Snapshot and suite:

    • tools/differential/snapshot.jsonl is byte-identical, and nothing was re-recorded.
    • The full suite passes on 3.11 and 3.15 (57,930 passed, 47 skipped, 3 xfailed, taken before the two new tests were added; the new tests then pass on both interpreters).
    • mypy and ruff check are clean.
  • Tokens and spans, compared across both trees. The inputs were every distinct text of the committed tools/differential/*.jsonl files, plus a grid of one to five pieces. The pieces were Han, Hangul (composed and in conjoining jamo), Mongolian and Latin words, both transcription dots, U+202F, the bidi marks, an emoji, the commas, the name dots, the invisible separators and the delimiters.

    • That is 90,889 texts, each under all four strip_bidi/strip_emoji settings.
    • Each line held tokenize's own tokens (text, span, role), its comma and interpunct offsets and its ambiguity indices, then the whole parse's repr and tokens.
    • Result: 0 of 363,556 lines differ. A planted control (master recording a dot's offset only at odd indices) moves 1,775.
    • The grid's pieces and composition are written out in the decisions entry.
  • Local corpora. measure.py --base against an export of af58ca0 ran 30 steps, and every one reports no moves. The steps were the committed snapshot, CLDR and GND agreement, 18 local snapshots (ctgov ×2, cz, dof, fec, govuk, jrc, my, nepal, parliaments, orcid, patentsview, psc, tse, tw, uit, ukec, vn), six field-agreement scores and four cross-script "alike" checks. It ran through a scratch NAMEPARSER_TOOLS_CACHE of links to the corpus files, so nothing shared was written or re-recorded.

  • Reads line. uv run python tools/stage_reads.py --stage tokenize reports Policy.strip_bidi and Policy.strip_emoji, which is what the Reads: line says.

  • Serial and timed rows. uv run pytest -n0 -m serial passes 39 of 39 on both trees (py3.11, at a load average of 200–340 from parallel sessions; the timed rows read CPU time). The scaling rows tokenize's work reaches, read with the tests' own _ratio at _BASE 800 → 3,200, twice on each tree, give ratios for 4x the input against _MAX_RATIO 6.0, with no side consistently higher:

    | row | master af58ca0 | this PR |
    |---|---|---|
    | plain_tokens | 4.75, 4.43 | 4.56, 4.04 |
    | commas | 4.45, 3.99 | 4.70, 4.67 |
    | unmatched_closes | 4.24, 4.17 | 4.71, 4.48 |
    | unmatched_opens | 4.74, 4.45 | 4.47, 4.78 |
    | delimiter_pairs | 4.15, 4.41 | 4.79, 4.48 |
    | quote_pairs | 4.42, 4.80 | 4.74, 4.30 |

    The new tests also pass on 3.15.

Frames per parse

These are sys.setprofile "call" events from tools/perf/call_count.py, with each tree loaded by path and its __file__ checked.

master af58ca0 this PR _CALL_BASELINE
py3.11 reference row 196.72 195.72 197 ±2%
py3.15 reference row 187.72 186.72 188 ±2%

Per name, on py3.11 (default order / FAMILY_FIRST):

name master af58ca0 this PR
John Smith 90 / 91 89 / 90
Smith, John 98 / 97 97 / 96
John (Jack) Smith 144 / 145 143 / 144
王·小明 107 / 108 106 / 107

A name holding a report, such as John "Jack ) Smith, is unchanged. Every row stays inside the band, so there is no release-log bullet.

Behavior-changing candidates

None was raised. Each reviewer was asked for them, and every finding was behaviour-preserving.

Considered and left alone

  • Span built with tuple.__new__ (efficiency). This would save one frame per token, about −6 on the reference row, outside the band. It is a hand copy of NamedTuple's generated constructor at two sites, and it would need _CALL_BASELINE re-taken on every interpreter.
  • WorkToken built with object.__new__ (efficiency). One frame per token. It would hand-copy the dataclass init, silently bypassing any later __post_init__. The right place would be a constructor helper in _state, which is outside this pass.
  • One NamedTuple instead of the three per-switch dicts _STRIPPED, _IGNORABLE and _BOUNDARY (altitude). The patterns would be byte-identical, and so would the readers' cost. It is a reshuffle with no reader simplified.
  • Inline _stripped into _flank (altitude). It saves a frame per flank character, on dot input only. _stripped is the reader the class test asserts on directly.
  • Extract's word-end loop as one C search over a class tokenize would export (altitude). This is _extract._opens_a_listed_particle, a loop over the characters that calls _ignorable for each one. It belongs in a pass over _extract.py, outside this one.
  • Build _EMOJI_CHARS with _policy._ranges_pattern (reuse). The match set is identical, but it needs a body-only helper split out of _policy, a shared helper outside this pass.
  • Smaller tidies: inlining _INTERPUNCT, an arithmetic form of _mongolian_letter, and skipping the sorts of offsets and tokens that are already sorted. These are untouched code or cheap defensive guarantees.
  • Origin resolution's end check (offset < tokens[i].span.end). The test review found no input that reaches it: a 60,000-string fuzz and hand probes of masked, extracted and custom-delimiter shapes. Extract never reports a delimiter inside a masked region. It stays as a free defensive guard. A test would need a hand-built ParseState.

Follow-ups for other passes

  • _extract._overlaps' docstring still carries an inline measurement ("400 pairs spent 5.4ms here, against 2.5ms before the sweep existed"), the class of figure this pass moved out of tokenize. It is worth taking to decisions/parse-cost in an extract pass.
  • _vocab.py:107-112 still cites "the _EMOJI_RANGES precedent in _tokenize.py". It is accurate, but it is history about tokenize living in another module, and _vocab.py belongs to another worker this cycle.

Reviews

  1. /simplify, four reviewers (reuse, simplification, efficiency, altitude). The findings applied are listed under Changes, and the rest under Considered.
  2. PR review toolkit on the first push (2cfe3a8, 06b36b0):
    • code-reviewer: no defects. Each change was argued equivalent on every input. One long docstring line was fixed.
    • comment-analyzer: no errors. It sent the improvements listed under Changes, plus the T2/T3 clause lines and the bisect's "per stray closer". It also found the _extract._overlaps follow-up above.
    • pr-test-analyzer: mutated eleven sites in scratch copies. Every behavioural mutant fails the full suite. The bisect and gate mutants passed test_tokenize.py and the case table, hence the new rows. The end-check mutants survive everything (see Considered).
    • design-docs-reviewer on the parse-cost entry found six problems, all fixed in 5eec819:
      • the old 180ms covered two quadratics fixed together in 81ea9c1, not this scan alone;
      • "each the same under FAMILY_FIRST" was false;
      • two per-name figures did not reproduce;
      • the grid was not enumerated;
      • the clock and the loop were not stated;
      • the row's own control was missing. Now recorded: unmatched_closes at its own 800 → 3,200, 4.21x and 4.35x on the change against 12.53x and 11.95x with a linear scan planted, against _MAX_RATIO 6.0.
    • Not run, as not applicable: type-design-analyzer (no type changed), silent-failure-hunter (no error path touched) and code-simplifier (the /simplify pass is this PR).
  3. Fix commits reviewed on their own:
    • code-reviewer on 5eec819 and dacacc9: no findings. An AST comparison with docstrings blanked shows the two commits change only comments and docstrings in _tokenize.py. The new frame pin fails on master's tokenize and cannot pass vacuously.
    • design-docs-reviewer, second round: all six fixes confirmed, and every figure re-taken. It found three new details, fixed in e402171:
      • the grid's jamo piece is 가, not the syllable before it in the list;
      • the two orders' counts went through different entry points, one frame apart;
      • the comparator sentence lacked its verb.

🤖 Generated with Claude Code

derek73 and others added 2 commits November 22, 2026 00:26
Release checklist step 0's pass over tokenize, quality only:

- Delete `_BIDI`, which no library code has read since the scan moved
  to the classes built from `_BIDI_CHARS` (#1436); its test builds the
  class from `_BIDI_CHARS` and its regex-sync roster row goes with it.
- Record a comma's or a transcription dot's offset in the branch that
  decided it, rather than asking the character's class a second time.
- Skip the ambiguity-origin generator when there is no ambiguity: one
  frame fewer on every parse without one (195.72 against 196.72 on
  py3.11, inside the band).
- Point the bisect comment at its scaling row and decisions entry
  instead of carrying its measurement, and the `\s` claim at the test
  that holds it.
- Correct two docstrings still saying only the interpunct marks a
  transcription: the fullwidth full stop does too since #1312.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…sions/parse-cost

The bisect comment's figures move here, re-measured, with the scaling
row that guards the resolution, the one frame the pass saves, and the
token comparison that shows nothing moved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@derek73 derek73 added this to the 3.2 milestone Nov 22, 2026
@derek73 derek73 added the internals Refactors and parse cost with no behavior change label Nov 22, 2026
@derek73 derek73 self-assigned this Nov 22, 2026
derek73 and others added 3 commits November 22, 2026 00:38
- Comments: the T2 and T3 citations say which clause the code
  implements; the emoji note no longer claims the bidi marks are
  integers; _stripped and _flank say which characters are transparent
  and name the reader; the extracted-region note says a transcription
  dot still divides there; the bisect note counts stray closers, not
  delimiter characters; a 115-column docstring line is rewrapped.
- Pin the saved generator frame: the ±2% band cannot see it return, so
  test_tokenize_asks_no_ambiguity_origin_of_a_parse_without_one holds
  it at no call on three names without a report, with a recorded
  control of one call each on af58ca0 (checked by running the test
  against master's tokenize).
- decisions/parse-cost: the entry carries #1527; the old 180ms is
  attributed to the two quadratics 81ea9c1 fixed together; the clock
  and the linear loop are written out; the unmatched_closes row's own
  ratio with the loop planted is recorded (12.53x and 11.95x against
  6.0); per-name counts are re-taken by a stated recipe under both
  orders, with 3.15's reference row; the comparison grid's pieces and
  composition are listed so it can be rebuilt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test review mutated the bisect (bisect_left, a missing or doubled
`- 1`) and the resolution's gate, and test_tokenize.py and the case
table passed each mutant: only test_extract.py and
test_script_segment.py held them. Four rows put the stray character at
each end of a token and at each end of the name; each mutant fails
three or four of them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The grid's jamo piece is ga, not the syllable before it; the two orders'
counts went through different entry points, one frame apart; the
comparator sentence now says what it runs over.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@derek73
derek73 merged commit 9c06606 into master Nov 22, 2026
14 checks passed
@derek73
derek73 deleted the refactor/simplify-tokenize branch November 22, 2026 10:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

internals Refactors and parse cost with no behavior change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant