Skip to content

Check catalogue format placeholders when pulling translations - #14784

Open
shashb27 wants to merge 8 commits into
sphinx-doc:masterfrom
shashb27:check-catalog-placeholders
Open

shashb27 wants to merge 8 commits into
sphinx-doc:masterfrom
shashb27:check-catalog-placeholders

Conversation

@shashb27

@shashb27 shashb27 commented Oct 26, 2026 •

Copy link
Copy Markdown

Following the discussion on #14664 and #14666 (closed): this adds a placeholder check to the Transifex sync so damaged catalogues can no longer land in the automated update PR.

This is the placement the earlier attempt converged on: #12394 was closed because a CI check on ordinary pull requests mostly guards against direct .po edits, which is not how translations are submitted, while the same check at the Transifex sync catches every catalogue it pulls in (see also sphinx-doc/sphinx-doc-translations#36, which proposed a babel_runner.py check command with no gettext dependency).

I've corrected two claims in this description. The catalogues do carry format flags - the POT and every catalogue mark all 11 brace-format messages python-brace-format and all 423 printf-style messages python-format, so m-aciek's Transifex pull finding no missing flags matches what's checked in; my "11 of ~870 entries carry almost no flags" line was me misreading my own measurement, since those 11 flagged entries are all the brace-format messages there are. The actual reason the #14664 damage slipped through is that babel's Catalog.check() has no checker for python-brace-format messages at all (python-babel/babel#333) - it reports zero errors on the damaged el and fa catalogues even though those entries carry the flag. And on msgfmt, --check-format has validated python-brace-format since gettext 0.21, not 0.23; 0.23 added f-string recognition to xgettext. The check is still needed in the sync, since msgfmt isn't part of it and babel won't catch this until #333 lands, but it's now scoped like babel itself: brace validation for flagged messages only, percent validation delegated to babel's own Message.check().

In the sync workflow the check runs between the pull and the compile with --exclude-failing: a failing catalogue is reverted so the automated PR excludes it, and the locale is listed in the PR body alongside the existing "Babel catalogue errors" section. Without the flag the check exits non-zero, so it can gate other CI paths later.

Measured against all 71 catalogues on current master, the check reports exactly the four damaged messages from #14664 (three in el, one in fa) and nothing else.

AI Disclosure

Per the PR template: the opencode coding agent (GLM) was used in preparing this pull request ΓÇö to survey the catalogue damage from #14664, implement the placeholder check, and write the tests. I reviewed the change and validated it locally (the new tests and tests/test_intl/test_locale.py green; ruff check and ruff format --check clean; the check flags exactly the four damaged messages across all 71 catalogues and nothing else).

The dropped-placeholder warning extension was contributed by katerynaKhar in the PR discussion; per her note there, her patch and tests were prepared with Claude Code. I reviewed the extension and re-verified it locally (same battery as above).

@shashb27
shashb27 force-pushed the check-catalog-placeholders branch from 87e1b13 to 3035fe1 Compare October 26, 2026 05:34
@katerynaKhar

Copy link
Copy Markdown

Thanks for this — the sync is the right place for the check, and it catches all four cases from #14664.

One gap I'd like to suggest closing while the check is being added: placeholders that a translation drops are explicitly allowed (test_missing_placeholder_is_not_an_error), since _placeholder_errors only looks at used - allowed. That is right for the build — a dropped placeholder never raises — but it is exactly the kind of damage that gets through unnoticed: the warning still renders, just without the config name or path it was meant to show.

To be upfront: Sphinx has none of these today. I ran the check below against all 71 catalogues on this branch and it reports zero dropped placeholders — only the four known el/fa errors. So this is not a fix for existing data, it is about what the next Transifex sync can bring in. In the other projects I scanned for #14664 dropped placeholders were by far the most common kind (1352 of 1439 findings in Laravel-Lang), so I'd expect them to show up here sooner or later too, and with this PR as it stands nothing would point at them.

The suggestion, as a patch on top of this branch (diff below):

  • _missing_placeholders() reports msgid placeholders ({name} and %(name)s) that the translation lacks, as warnings: they do not count towards failures, do not change the exit code and do not get the catalogue excluded — one dropped {name} shouldn't hold back a whole locale's update;
  • with --exclude-failing they are listed in the sync PR body under a separate "Translations missing placeholders" heading, so whoever reviews the sync PR sees them and can fix them on Transifex;
  • plural messages: a placeholder only has to appear in one translated form, since msgstr[0] legitimately omits the count in many languages;
  • positional {} fields are not compared;
  • messages that already have an error are not also reported as missing — a renamed placeholder ({current__name__} in el) would otherwise show up twice.

_placeholder_errors() is unchanged, so the existing tests pass as they are. 8 new tests plus one extra assertion in test_run_check_reports_and_excludes; tests/test_babel_runner_check.py and tests/test_intl/test_locale.py pass (22 passed), ruff check and ruff format --check are clean.

Feel free to take it into this PR as is, adjust it, or tell me if you'd rather keep this PR minimal — then I can open it as a follow-up after this one lands.

(The patch and tests were prepared with Claude Code and run locally on Python 3.13.)

Patch on top of 3035fe1
diff --git a/CHANGES.rst b/CHANGES.rst
index fbc9ae2..b1205c4 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -21,7 +21,8 @@ Testing
 
 * #14664: Check that the format placeholders of every translation match
   its msgid when pulling catalogues from Transifex, and exclude failing
-  catalogues from the automated update pull request.
+  catalogues from the automated update pull request. Placeholders that a
+  translation drops are reported as warnings.
   Patch by Shash Bhaskar
 
 * #14690: Fix test isolation issues caused by shared test directories and
diff --git a/tests/test_babel_runner_check.py b/tests/test_babel_runner_check.py
index 09d248e..0a79d64 100644
--- a/tests/test_babel_runner_check.py
+++ b/tests/test_babel_runner_check.py
@@ -105,6 +105,48 @@ def test_each_plural_form_is_checked() -> None:
     ]
 
 
+def _missing(msgid: str | tuple[str, str], msgstr: str | tuple[str, ...]) -> list[str]:
+    return babel_runner._missing_placeholders(Message(msgid, msgstr))
+
+
+def test_missing_placeholder_is_a_warning() -> None:
+    assert _missing('bad value {name!r}', 'valeur incorrecte') == [
+        "placeholder 'name' from the msgid is missing in translation"
+    ]
+
+
+def test_missing_percent_placeholder_is_a_warning() -> None:
+    assert _missing('bad value %(name)r', 'valeur incorrecte') == [
+        "placeholder 'name' from the msgid is missing in translation"
+    ]
+
+
+def test_complete_translation_has_no_missing_placeholders() -> None:
+    assert _missing('bad value {name!r}', 'mauvaise valeur {name!r}') == []
+
+
+def test_reordered_placeholders_are_not_missing() -> None:
+    assert _missing('{name} in {path}', 'dans {path}: {name}') == []
+
+
+def test_plural_placeholder_needs_only_one_form() -> None:
+    # the singular form may legitimately omit the count
+    msgid = 'one file in {path}', '{n} files in {path}'
+    msgstr = 'un fichier dans {path}', '{n} fichiers dans {path}'
+    assert _missing(msgid, msgstr) == []
+    assert _missing(msgid, ('un fichier', '{n} fichiers')) == [
+        "placeholder 'path' from the msgid is missing in translation"
+    ]
+
+
+def test_positional_placeholders_are_not_compared() -> None:
+    assert _missing('bad value {}', 'valeur incorrecte') == []
+
+
+def test_damaged_syntax_is_not_also_reported_missing() -> None:
+    assert _missing('bad value {name}', 'valeur incorrecte {name]') == []
+
+
 def test_run_check_reports_and_excludes(
     tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
 ) -> None:
@@ -140,13 +182,49 @@ def fake_git(*args: Any, **kwargs: Any) -> int:
     monkeypatch.setattr(babel_runner, '_write_pr_body_line', lambda m: None)
 
     # plain mode: reports the damaged catalogue and exits non-zero
-    with caplog.at_level('ERROR', logger='babel'), pytest.raises(SystemExit) as exc:
+    with caplog.at_level('WARNING', logger='babel'), pytest.raises(SystemExit) as exc:
         babel_runner.run_check()
     assert exc.value.code == 1
     assert any('el' in record.getMessage() for record in caplog.records)
+    # the renamed placeholder is an error only, not also a missing one
+    assert not [r for r in caplog.records if r.levelname == 'WARNING']
 
     # exclusion mode: reverts the damaged catalogue and exits cleanly
     babel_runner.run_check(exclude_failing=True)
     assert len(reverted) == 1
     assert Path(reverted[0]).name == 'sphinx.po'
     assert Path(reverted[0]).parent.parent.name == 'el'
+
+
+def test_run_check_warns_without_excluding(
+    tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+    d = tmp_path / 'sphinx' / 'locale' / 'el' / 'LC_MESSAGES'
+    d.mkdir(parents=True)
+    (d / 'sphinx.po').write_text(
+        dedent(
+            """\
+            msgid "value '{name}'"
+            msgstr "valeur"
+            """
+        ),
+        encoding='utf-8',
+    )
+
+    def fake_git(*_args: Any, **_kwargs: Any) -> int:
+        pytest.fail('a catalogue with only missing placeholders was reverted')
+
+    body: list[str] = []
+    monkeypatch.setattr(babel_runner, 'ROOT', tmp_path)
+    monkeypatch.setattr(babel_runner.subprocess, 'run', fake_git)
+    monkeypatch.setattr(babel_runner, '_write_pr_body_line', body.append)
+
+    # neither mode fails or excludes the catalogue
+    with caplog.at_level('WARNING', logger='babel'):
+        babel_runner.run_check()
+        babel_runner.run_check(exclude_failing=True)
+    warnings = [r for r in caplog.records if r.levelname == 'WARNING']
+    assert len(warnings) == 2
+    assert "'name'" in warnings[0].getMessage()
+    assert '* el: 1 placeholder' in body
+    assert '## Catalogues excluded from this update' not in body
diff --git a/utils/babel_runner.py b/utils/babel_runner.py
index 25d0c82..ac4885f 100644
--- a/utils/babel_runner.py
+++ b/utils/babel_runner.py
@@ -19,7 +19,8 @@
     Transifex largely do not, so damaged placeholders slip through it
     (#14664). With "--exclude-failing" (used by the Transifex sync),
     failing catalogues are reverted so that the automated pull request
-    excludes them, and they are listed in its body.
+    excludes them, and they are listed in its body. Placeholders that a
+    translation drops are reported as warnings and do not fail the check.
 """
 
 from __future__ import annotations
@@ -353,17 +354,72 @@ def _placeholder_errors(message: Message) -> list[str]:
     return errors
 
 
+def _missing_placeholders(message: Message) -> list[str]:
+    """Return placeholders of the msgid that the translation drops.
+
+    A dropped placeholder does not break formatting, so it is reported
+    as a warning rather than an error: the message still renders, but
+    loses the information the placeholder carried (a name, a path, ...).
+
+    For plural messages a placeholder only has to appear in one of the
+    translated forms, since a singular form may legitimately omit the
+    count. Positional ``{}`` fields are not compared.
+    """
+    msgid = message.id
+    if isinstance(msgid, (list, tuple)):
+        msgid_forms = [msgid[0], msgid[1]]
+    else:
+        msgid_forms = [msgid]
+
+    required: set[str] = set()
+    for form in msgid_forms:
+        try:
+            required |= _brace_format_fields(form)
+        except ValueError:
+            return []
+    required |= _percent_format_fields(''.join(msgid_forms))
+    required.discard('')
+
+    msgstr = message.string
+    if msgstr is None:
+        return []
+    if isinstance(msgstr, (list, tuple)):
+        msgstr_forms = [form for form in msgstr if form]
+    else:
+        msgstr_forms = [msgstr]
+    if not msgstr_forms:
+        return []
+
+    used: set[str] = set()
+    for form in msgstr_forms:
+        try:
+            used |= _brace_format_fields(form)
+        except ValueError:
+            # invalid syntax is already reported by _placeholder_errors()
+            return []
+        used |= _percent_format_fields(form)
+
+    return [
+        f'placeholder {name!r} from the msgid is missing in translation'
+        for name in sorted(required - used)
+    ]
+
+
 def run_check(exclude_failing: bool = False) -> None:
     """Check catalogue placeholder consistency.
 
     With *exclude_failing*, revert catalogues that fail the check so the
     Transifex sync excludes them from the automated pull request, and
     record them in its body.
+
+    Placeholders that a translation drops are reported as warnings: they
+    neither fail the check nor exclude the catalogue.
     """
     log = _get_logger()
 
     directory = ROOT / 'sphinx' / 'locale'
     excluded: list[str] = []
+    missing: dict[str, int] = {}
     failures = 0
 
     for locale in sorted(directory.iterdir()):
@@ -378,7 +434,8 @@ def run_check(exclude_failing: bool = False) -> None:
         for message in catalogue:
             if not message.id or not message.string or message.fuzzy:
                 continue
-            for error in _placeholder_errors(message):
+            errors = _placeholder_errors(message)
+            for error in errors:
                 locale_errors += 1
                 log.error(
                     'error: %s:%d: %s\nerror:     in message string: %r',
@@ -387,6 +444,19 @@ def run_check(exclude_failing: bool = False) -> None:
                     error,
                     message.string,
                 )
+            if errors:
+                # a renamed placeholder is already an error; do not also
+                # report the original name as missing
+                continue
+            for warning in _missing_placeholders(message):
+                missing[locale.name] = missing.get(locale.name, 0) + 1
+                log.warning(
+                    'warning: %s:%d: %s\nwarning:     in message string: %r',
+                    po_file.relative_to(ROOT),
+                    message.lineno,
+                    warning,
+                    message.string,
+                )
 
         if not locale_errors:
             continue
@@ -409,6 +479,13 @@ def run_check(exclude_failing: bool = False) -> None:
         for locale_name in excluded:
             _write_pr_body_line(f'* {locale_name}')
 
+    if missing:
+        _write_pr_body_line('## Translations missing placeholders')
+        _write_pr_body_line('')
+        for locale_name, count in missing.items():
+            s = 's' if count != 1 else ''
+            _write_pr_body_line(f'* {locale_name}: {count} placeholder{s}')
+
     if failures and not exclude_failing:
         raise SystemExit(1)
 

Extension contributed by katerynaKhar in the PR discussion: report msgid placeholders that a translation drops as warnings, without failing or excluding the catalogue, so the sync PR body surfaces them for a Transifex-side fix.

Co-authored-by: katerynaKhar <[email protected]>
@shashb27

Copy link
Copy Markdown
Author

Taking this into the PR - thanks for writing it out. The error path is untouched, so the existing tests carry over as they are, and I re-ran the full battery on the patch: 22 tests pass, the type checkers and ruff are clean, and the check over all 71 catalogues reports exactly the four known errors and zero dropped placeholders, matching your numbers. The plural one-form rule and not double-reporting renamed placeholders were exactly the details I would have got wrong. Commit pushed with you as co-author.

@m-aciek m-aciek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One correction to the PR description: msgfmt --check-format does not require gettext ≥ 0.23 to validate python-brace-format messages. Gettext 0.21 already includes that validator; 0.23 added f-string recognition to xgettext, which is separate from PO validation.

I also pulled the source POT and all 68 translation catalogues from Transifex and found no missing format flags relative to the POT. Could you update the description to reflect this?

Keeping validation in Python is still reasonable, but we could reuse Catalog.check() for percent formatting and limit the custom checker to brace formatting. Once Babel #333 is addressed, we could remove that custom checker too.

Comment thread utils/babel_runner.py
for message in catalogue:
if not message.id or not message.string or message.fuzzy:
continue
errors = _placeholder_errors(message)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we limit the brace-format check to messages flagged python-brace-format and leave percent-format validation to the existing Catalog.check() call? I pulled the source POT and all 68 translation catalogues from Transifex: none were missing the format flags present in the POT. The claim that downloaded catalogues largely lack these flags therefore seems inaccurate.

This would also keep our custom check limited to the functionality Babel currently lacks. Once Babel supports brace-format validation (python-babel/babel#333), we could rely on Catalog.check() for both formats and remove it.

Comment thread utils/babel_runner.py Outdated
Raises ``ValueError`` for invalid brace-format syntax.
"""
fields: set[str] = set()
for _literal, field_name, _spec, _conversion in string.Formatter().parse(text):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Formatter.parse() alone does not validate conversions or collect nested fields. For example, translating {name} as either {name!x} or {name:{unknown}} passes this check but fails at runtime. Could we validate conversion characters and recursively check fields inside format specifications?

Comment thread utils/babel_runner.py Outdated
locale_errors,
)
subprocess.run(
('git', 'checkout', '--', str(po_file)), # ruff: ignore[start-process-with-partial-path]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If an invalid catalogue belongs to a newly downloaded language, its PO file is untracked. git checkout -- <path> then fails and aborts synchronization, including valid updates to other languages. Could we remove invalid new catalogues and restore existing ones?

@shashb27

shashb27 commented Nov 4, 2026

Copy link
Copy Markdown
Author

Thanks for the really thorough review, and especially for pulling the source POT and all 68 catalogues - that settled the design question. You were right about the flags: every brace-format message carries python-brace-format in the POT and the catalogues, so I've reworked the check to gate the brace validation on that flag and delegate percent validation to babel's own Message.check(), leaving only the brace code custom until python-babel/babel#333 lands. Your other two points caught real gaps, both fixed: the brace parser now rejects unknown conversions like {name!x} and compares placeholders nested inside format specifications against the msgid's, and --exclude-failing now deletes a newly pulled language's invalid catalogue instead of letting git checkout fail on the untracked file and abort the whole sync. Rerunning the check over all 71 checked-in catalogues still flags exactly the four #14664 messages and nothing else, so the new rules add no noise. The description is corrected too - the flags claim was me misreading my own numbers, and the gettext version is 0.21 as you said. Happy to keep adjusting if anything still looks off.

Comment thread utils/babel_runner.py

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

run_check() locates catalogues through ROOT, but _is_tracked() and the git checkout call run Git from the caller's current directory. If someone runs python /path/to/sphinx/utils/babel_runner.py check --exclude-failing from outside the checkout, git ls-files exits 128; _is_tracked() treats its empty stdout as “untracked”, and this branch unlinks a tracked .po file. Please run both Git commands with cwd=ROOT and check the ls-files exit status before deciding to delete a catalogue. An outside-cwd test would cover this case.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update. I rechecked the current patch: both Git calls now run with cwd=ROOT, ls-files failures stop the check, and the outside-checkout regression test covers the tracked-catalogue case. This addresses my concern.

@shashb27

shashb27 commented Nov 5, 2026

Copy link
Copy Markdown
Author

Confirmed — I reproduced exactly this: run from outside the checkout, git ls-files exits 128 and the empty output was read as untracked, so --exclude-failing unlinked a tracked catalogue instead of reverting it. Both git commands now run with cwd=ROOT, and _is_tracked() raises on a non-zero ls-files exit rather than treating empty output as untracked, so nothing is deleted when git can't answer. I've added a test that drives the check from outside the checkout root and one for the failing ls-files case.

@m-aciek m-aciek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this and addressing the earlier feedback. I found two more cases worth covering, particularly positional argument reordering, which translators may need.

Comment thread utils/babel_runner.py Outdated
fields: set[str] = set()
for _literal, field_name, spec, conversion in string.Formatter().parse(text):
if field_name is not None:
fields.add(field_name)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we support explicit positional indices for automatically numbered fields? Translators may need them to reorder arguments. For example, "File {} was created by user {}." can naturally become "Użytkownik {1} utworzył plik {0}.". Both work with the same arguments, but the checker currently rejects the translation. With --exclude-failing, this would discard an otherwise valid catalogue update.

Comment thread utils/babel_runner.py Outdated
Comment on lines +313 to +314
if spec:
fields |= _brace_format_fields(spec)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The recursive parsing accepts {name:{name:{name}}}, so run_check() succeeds without warnings, but str.format() raises ValueError: Max string recursion exceeded. Could we enforce the runtime nesting limit here?

@shashb27

shashb27 commented Nov 9, 2026

Copy link
Copy Markdown
Author

Thanks for catching both of these. The checker now works out the argument list the msgid implies and accepts anything str.format() can render with it, so your Polish example passes, and it also rejects specifications nested deeper than str.format() allows, matching what CPython does at runtime. Both cases are covered by tests, including your example verbatim. Pushed as 2e03c7e.

…limit

str.format() expands a format specification only when it holds a
replacement field - CPython's formatter decrements its recursion depth
(from an initial 2) only for a specification marked as needing
expansion.  A literal specification inside a specification therefore
still formats ("{a:{b:>5}}"), and only a second field-bearing level,
as in "{a:{b:{c}}}", raises "ValueError: Max string recursion
exceeded" at runtime; the check now rejects exactly that.  Also drop
the _brace_format_fields helper, which _brace_format_info replaced.
@shashb27

Copy link
Copy Markdown
Author

Small correction to my earlier reply: re-testing the recursion boundary against CPython I found the nesting check was still one case too strict. str.format() recurses into a format specification only when it holds a replacement field — CPython counts the recursion down from 2 and a literal specification never decrements it — so "{a:{b:>5}}" still formats at runtime while my check rejected it; only a second field-bearing level like "{a:{b:{c}}}" raises ValueError: Max string recursion exceeded. 51086a0 now rejects exactly that, with tests on both sides of the boundary. The positional-reordering half needed no change: your Polish example passes, and a translation referencing an index the msgid does not pass (say {2} against a two-field msgid) is still an error.

@m-aciek

m-aciek commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Preferable solution would be to bring the check for python-brace-format into babel itself. python-babel/babel#333 This PR is a workaround for the upstream issue.

@shashb27

Copy link
Copy Markdown
Author

Fair — and for what it's worth there's been movement on the Babel side already: Message.python_brace_format merged as #1169, with an open lint-command PR (#1168) building on it. Would it be useful if I looked into what's still missing upstream, or do you see this checker as worth merging in sphinx regardless, as the stopgap until Babel's linting is usable from the Transifex sync? Happy to pursue the upstream side if that's the preferred path.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants