Skip to content

About

manyfold - find, prove and repair plural defects in ICU MessageFormat translation catalogues (offline, pure stdlib CLDR plural engine)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Development Experiment 047 — manyfold

Find, prove and repair plural defects in ICU MessageFormat translation catalogues.

Offline, dependency-free (pure stdlib), no LLM, no network.


Thesis

English has two plural forms. Polish has four, Arabic six, Japanese one. When a catalogue ships English's one/other shape to a Polish audience, nothing breaks: ICU silently falls back to other, and the product reads as broken grammar to every native speaker. Nothing crashes, nothing warns, and no English-speaking QA pass can see it — the bug is invisible in the only language the team tests in. Two 2026 signals sharpened this into today's idea: localization tooling reports that "missing plural forms cause silent fallbacks that are invisible in English testing," and that "AI coding tools rarely emit correct ICU in the first place, tending to handle counts naively in a way that is correct for English but wrong for most other languages" — so the defect is now being mass produced by code generators. manyfold is the smallest thing that proves the idea: a real CLDR plural-rule engine plus an ICU parser, used not to lint but to render — for every message, in every locale, it finds a concrete number that reaches each plural category and shows the sentence a user will actually read, then rewrites the catalogue into the shape the locale requires.

Lane: developer tooling for i18n/localization — the data/web-productivity lane. Experiments 001–044 were static auditors of the agent/MCP plane and 045–046 were a CI runner and a spreadsheet diff; this is the series' first entry on internationalization, and its first whose primary output is rendered natural language rather than a verdict.


Why this is not another linter

Existing tools check whether a plural declaration looks right. eslint-plugin-formatjs enforces a category list, editor plugins highlight missing keys, and TMS platforms validate ICU syntax on upload. All of them stop at the structure.

manyfold goes one step further, and that step is the whole product:

typical linter manyfold
knows the locale's categories yes yes
proves a category is reachable no yes — by search over a number domain
shows the wrong string users will see no yes — proof renders it
detects a branch shadowed by =N no yes
compares target against source shape no yes — ENGLISH_SHAPED
fixes the catalogue no yes — repair writes correct skeletons

A developer who cannot read Polish still cannot judge a Polish string. But a Polish reviewer handed this table can, in ten seconds:

| key        | arg     | selector | n   | renders as             | status       |
| cart.items | `count` | `=0`     | 0   | Twój koszyk jest pusty | exact        |
| cart.items | `count` | `one`    | 1   | 1 produkt              | ok           |
| cart.items | `count` | `few`    | 2   | 2 produktów            | **FALLBACK** |
| cart.items | `count` | `many`   | 5   | 5 produktów            | **FALLBACK** |
| cart.items | `count` | `other`  | 0.1 | 0.1 produktów          | ok           |

2 produktów is wrong — Polish wants 2 produkty. That row is the entire value proposition.


Install & run

Requires Python 3.11+. No dependencies.

python -m manyfold check examples/locales     # or: make run

Optionally install the console script:

pip install -e .
manyfold check ./locales

The four commands

manyfold check  ./locales                 # report defects; exit 1 on errors (CI gate)
manyfold proof  ./locales -o proof.md     # render every branch with a witness number
manyfold repair ./locales --write         # rewrite catalogues into the correct shape
manyfold rules  --locale pl               # what plural forms does Polish need?

Useful flags: --source <locale> (default en), --format json, --fail-on {error,warning,info,never}, --rules <cldr plurals.json>, --prune, --marker '<<{category}>> '.

Catalogue layouts understood

  • locales/en.json, locales/pl.json — one file per locale
  • locales/en/common.json, locales/pl/common.json — locale directories
  • flat keys, nested objects, and FormatJS {"id": {"defaultMessage": "..."}}
  • i18next suffix plurals (items_one / items_few / items_other), analysed and repaired as groups

Sample run

$ python -m manyfold check examples/locales --no-missing-keys

== ar ==
ERROR   ENGLISH_SHAPED           cart.items
         'count' copies the source locale's plural shape 'one', 'other'
         ar also needs zero (e.g. n=0), two (e.g. n=2), few (e.g. n=3), many (e.g. n=11).
         Those counts fall back to 'other' and read as broken grammar.
ERROR   MISSING_CATEGORY         inbox.unread
         'count' is missing 'zero', 'few', 'many'
         ar selects zero (e.g. n=0), few (e.g. n=3), many (e.g. n=11); these fall back to 'other'.
warn    LOST_NUMBER              cart.items
         'one' branch no longer shows the count
         The source 'one' branch renders 'count', this one does not.

== de ==
warn    SHADOWED_CATEGORY        cart.items
         'count' branch 'one' can never fire
         Every number that would select it is already captured by an exact selector ('=0', '=1').
warn    SPURIOUS_CATEGORY        inbox.unread
         'count' declares 'few', which 'de' never selects
         de uses 'one', 'other'. These branches are dead text -- paid for, never shown.

== fr ==
ERROR   ENGLISH_SHAPED           cart.items
         'count' copies the source locale's plural shape 'one', 'other'
         fr also needs many (e.g. n=1000000). Those counts fall back to 'other' and read as broken grammar.

== pl ==
ERROR   ENGLISH_SHAPED           cart.items
         'count' copies the source locale's plural shape 'one', 'other'
         pl also needs few (e.g. n=2), many (e.g. n=5). Those counts fall back to 'other' and read as broken grammar.
ERROR   NOT_PLURALIZED           upload.progress
         'total' is pluralised in source but not here
         The translation uses a single fixed form, so it will be wrong for at least one count.

manyfold: 14 error(s), 5 warning(s), 0 info -- rules: embedded CLDR 46
         run `manyfold repair` to seed the missing branches

Note what is not in that output: the Japanese catalogue, whose plain カートに{count}点 strings contain no plural at all. Japanese has one category, so a fixed form is correct, and flagging it would be noise. Zero findings for ja, zero for the en source.

And the repair, which is what makes this a tool rather than a report:

$ python -m manyfold repair examples/locales

== pl ==
  cart.items  (count: added few, many)
    - {count, plural, =0 {Twój koszyk jest pusty} one {# produkt} other {# produktów}}
    + {count, plural, =0 {Twój koszyk jest pusty} one {# produkt} few {[TODO:few] # produktów}
      many {[TODO:many] # produktów} other {# produktów}}
  upload.progress  (total: wrapped a plain translation in a plural)
    - Wysyłanie {done} z {total} plików
    + {total, plural, one {[TODO:one] Wysyłanie {done} z {total} plików}
      few {[TODO:few] Wysyłanie {done} z {total} plików}
      many {[TODO:many] Wysyłanie {done} z {total} plików}
      other {Wysyłanie {done} z {total} plików}}

manyfold: 14 repair(s) proposed; re-run with --write to apply

The translator receives a file with the right branches already in place, seeded from the existing text and marked [TODO:few]. Their job becomes "fix the grammar in three short strings" instead of "learn ICU MessageFormat".


Architecture

catalogue dir ──► catalog.py ──► flattened entries (key → message, per locale)
                                        │
                  rules_data.py         ▼
                  (CLDR snapshot) ─► analyze.py ─► Report(findings)
                        │                 ▲             │
                        ▼                 │             ├─► proof.py   ─► Markdown proof sheet
                  cldr.py (engine)   icu.py (parser)    └─► repair.py  ─► rewritten catalogues
                        │                 │
                        └──► witness.py ◄─┘
  • cldr.py — a recursive-descent parser and evaluator for the CLDR plural-rule grammar (and/or, the n i v w f t c e operands, mod, ranges, and the legacy in/within/is operators), plus operand extraction from a number's visible representation. "1" and "1.0" are different numbers here, which is why v, w, f and t exist.
  • rules_data.py — the embedded CLDR 46 snapshot: 44 locales, cardinal and ordinal, each with a sample table. --rules swaps in upstream CLDR JSON.
  • icu.py — ICU MessageFormat parser, unparser and renderer: nested plural/selectordinal/select, offset:, #, =N selectors, and ICU's DOUBLE_OPTIONAL apostrophe quoting.
  • witness.py — exhaustive search over a fixed candidate domain for the simplest number reaching a category.
  • analyze.py — 15 defect codes across structural and differential checks.
  • proof.py, repair.py, cli.py — the three outputs.

Correctness: the snapshot checks itself

Transcribing 44 locales of plural rules by hand is exactly the kind of task that produces a silent typo — and a wrong rule here would mis-pluralise someone's product while reporting success. So every locale carries a table of sample numbers with their expected categories, and the test suite re-derives each one through the real engine:

$ python -m manyfold rules --self-check
manyfold: every embedded sample agrees with the rules (embedded CLDR 46)

A further test asserts that every declared category of every locale has a reachable witness, so a rule that can never fire fails CI rather than shipping. This does not make the snapshot authoritative — CLDR upstream is — but it makes a transcription error loud instead of silent, and --rules exists for anyone who needs the real thing.

Two approaches considered

A: symbolic analysis of the rule conditions. Translate each CLDR condition into constraints and solve for satisfiability to decide reachability. Exact and fast, but it needs a second implementation of the rule semantics — one for solving, one for rendering — and the two can disagree. A disagreement would be invisible and would produce exactly the class of bug this tool exists to catch.

B (chosen): exhaustive search over a bounded candidate domain. ~330 candidate numbers, classified by the same engine that renders at runtime. It cannot disagree with itself, the witnesses are real numbers a human can paste into a test, and the whole sweep is cached per locale (the full 44-locale reachability test runs in well under a second). The cost is that a category reachable only outside the domain would be reported unreachable — so the domain is chosen to cover every construct CLDR actually uses (millions for Romance many, n % 100 in 11..19 for Latvian zero, visible fractions for Czech many, compact exponents for c/e), and a test asserts the coverage holds for every embedded locale.

Memory/CPU: the whole tool is O(messages × locales); the example run analyses 6 locales and 26 messages in ~0.1 s. Rule evaluation is cached per locale, not per message.


Defect codes

code severity meaning
ENGLISH_SHAPED error target copies the source locale's category set, but its own locale needs more
MISSING_CATEGORY error a category the locale selects has no branch; falls back to other
NOT_PLURALIZED error source pluralises this argument, target uses one fixed form
MISSING_OTHER error plural with no other — ICU fails at render time
SELECT_MISSING_OTHER error select with no other
ARG_MISSING error a placeholder present in the source is gone
UNKNOWN_SELECTOR error selector is neither a CLDR category nor =N
PARSE_ERROR error message is not valid ICU MessageFormat
SPURIOUS_CATEGORY warning branch for a category the locale never selects — dead text
SHADOWED_CATEGORY warning branch unreachable because =N selectors already cover it
LOST_NUMBER warning a branch that showed the count in the source no longer does
ARG_EXTRA warning placeholder not present in the source
UNKNOWN_LOCALE warning no plural rules on file; checks skipped for that locale
SUFFIX_MISSING_CATEGORY / SUFFIX_SPURIOUS_CATEGORY error / warning same, for i18next suffix keys
MISSING_KEY info key untranslated in this locale
ORDINAL_RULES_UNKNOWN info selectordinal in a locale with no ordinal data

Use in CI

- run: python -m manyfold check ./locales --fail-on error

check exits 0 clean, 1 when findings reach the --fail-on threshold, and 2 on a usage or I/O error. --format json emits the full finding list for downstream tooling.


Assumptions & limitations

  • JSON catalogues only. gettext .po, XLIFF, .arb, .strings and Android plurals.xml are not read. The analysis layer is format-independent — only catalog.py would need extending.
  • The embedded snapshot covers 44 locales (CLDR 46, the release current as of 2026-09) for cardinals and 25 for ordinals. Anything else reports UNKNOWN_LOCALE and is skipped rather than guessed at. --rules loads upstream plurals.json/ordinals.json for full coverage.
  • The snapshot is hand-transcribed, not vendored. It is verified against its own samples, not against upstream. Treat --rules as authoritative if it matters to you.
  • Number formatting is not locale-aware. The renderer prints argument values as given, so a proof sheet shows 1000000, not 1 000 000. Plural selection is exactly correct; the decorative formatting is not. number/date/time styles are parsed and preserved but rendered as the raw value.
  • Repair seeds from other, and cannot translate. The output is a correct skeleton with [TODO:category] markers, not a finished translation. That is the point: the structure is mechanical, the grammar is not.
  • repair --write overwrites catalogue files in place, reserialising JSON with 2-space indent and ensure_ascii=False. Key order is preserved; formatting is not. Run it on a clean git tree; the default is a dry-run diff.
  • LOST_NUMBER has expected false positives. Many languages idiomatically omit the numeral in the one form (Arabic ملف واحد), so it is a warning, not an error.
  • Compact-decimal selection is supported in the rules (c/e operands, used by Romance many) but a catalogue cannot express a compact argument, so those categories are reachable in theory and rare in practice. They are still required by CLDR, and still reported.
  • --prune deletes translated text. It is opt-in for that reason.

Tests

make test      # python -m unittest discover -s tests -t .   (no dependencies)
make pytest    # python -m pytest -q

104 tests, 192 subtests. Coverage includes: CLDR operand extraction and the full rule grammar; snapshot self-verification across every embedded locale; witness reachability for every category of every locale; ICU parsing, unparsing round-trips and rendering (offsets, =N precedence, apostrophe modes, nesting); catalogue discovery across three layouts and three shapes; every defect code; repair idempotency, error-clearing and JSON/ICU validity of the output; and the CLI's exit codes, JSON output and external-CLDR loading.

Licence

MIT — see LICENSE.

About

manyfold - find, prove and repair plural defects in ICU MessageFormat translation catalogues (offline, pure stdlib CLDR plural engine)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages