Skip to content

Prune fuzzy candidates using Jaro similarity bounds - #451

Open
oliver-kriska wants to merge 3 commits into
elixir-gettext:mainfrom
oliver-kriska:prune-fuzzy-candidates
Open

oliver-kriska wants to merge 3 commits into
elixir-gettext:mainfrom
oliver-kriska:prune-fuzzy-candidates

Conversation

@oliver-kriska

@oliver-kriska oliver-kriska commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Faster fuzzy merging without changing match selection

Related to #440. The expensive part of fuzzy merging is scoring every old message for each unmatched message, not constructing the matcher closure. This PR skips candidates whose maximum possible Jaro similarity is below the threshold or the best score already found. Surviving candidates still use String.jaro_distance/2; this does not substitute an approximate matcher or change the fuzzy threshold.

Lengths and grapheme frequencies are prepared once per PO merge by Gettext.Fuzzy.candidates/1, only when fuzzy matching is on and some new message has no exact match. Gettext.Fuzzy.find_match/3 does the search. The bounds assume no transpositions and at most as many matching graphemes as the strings have in common. They use graphemes rather than bytes or codepoints, count repeated graphemes, and preserve the scorer's floating-point addition order. Candidate traversal order and the first winner on equal scores are retained. Exact matches and --no-fuzzy do not build the index. All old messages remain eligible, including ones already used by another match.

A msgid that is empty or not valid UTF-8 is never skipped, on either side, so String.jaro_distance/2 still decides what happens with it, including the exceptions it raises for malformed input. Equality and empty-string fast paths remain the scorer's responsibility.

Measurements

Baseline: upstream b2c62ff. Apple M4 Pro, Elixir 1.20.4 / OTP 29.0.5, MIX_ENV=prod, four schedulers. These are medians of seven alternating baseline/candidate pairs after an untimed warmup, using fresh input files for every invocation. Timings include the complete merge task: parsing, preparing candidates, merging, pruning references, composing and writing PO files. They exclude VM startup, compilation and copying the fixtures.

Workload Before After
Real application change: 16 locales, 176 PO files, 11 unmatched source keys 7.41 s 1.94 s
25,900 messages, one locale, 100 edits 25.81 s 2.98 s
Real application change, --no-fuzzy control 1.30 s 1.33 s
25,900 messages, all exact matches 1.36 s 1.32 s

On Elixir 1.19.5 / OTP 28.4.1 (the same major versions as the issue reporter), with the same methodology:

Workload Before After
10,000 messages, one locale, 10 edits 0.950 s 0.675 s
10,000 messages, one locale, 100 edits 14.07 s 0.964 s

The large fixtures expand a private application's real catalog using unique msgid suffixes, retaining its translations, plurals, contexts and references. The real-change row replays an actual before/after catalog snapshot without generating strings. This is not the reporter's catalog, and the locale count and number of changed messages in that report are unknown. The machine had other work running, so these are indicative paired measurements, not guaranteed timings or a reproduction of the reported six-minute merge. The control results do not establish a speedup.

Separately traced Jaro-call counts fell from 779,328 to 6,096 for the real change, and from 2,590,000 to 3,128 for the 25,900-message/100-edit case. Allocated heap words inside merge/5 for the latter fell from 6.63 billion to 98.7 million; these are cumulative allocations, not peak memory. Profiling the 25,900-message/10-edit search shows the remaining work is mostly preparing grapheme counts and checking bounds rather than running Jaro comparisons.

Equivalence and limits

  • Every measured task invocation checks merge statistics and SHA-256 hashes of every output PO against the baseline.
  • Differential validation compares complete message structs, statistics and composed bytes for 2,022 seeded multi-message cases and 4,800 exhaustive short-string threshold-boundary cases on each of OTP 27, 28 and 29. Another 120 malformed/empty-input cases compare full results or exception type and message. Cases cover Unicode combining characters/emoji, repeated graphemes, contexts, singular/plural conversion, exact/fuzzy matches, obsolete messages and previous-message metadata.
  • The Elixir 1.16 scoring implementation was also exercised on the installed runtime; this is not a replacement for running CI on Elixir 1.16 / OTP 24.
  • The isolated branch passes mix test --warnings-as-errors (199 passed: 5 doctests, 194 tests), formatting and whitespace checks. Kept tests target inclusive thresholds, repeated/Unicode graphemes, best-match/tie behavior, zero thresholds and platform handling of malformed UTF-8.

This trades temporary per-catalog indexing memory for fewer expensive comparisons. Histograms remain live until the merge finishes; peak memory was not measured. Worst-case scanning remains quadratic in old messages × unmatched new messages. Candidates with identical grapheme histograms can all survive the bounds, making the extra checks slower than the baseline. It also does not change extraction's timeout or compilation behavior, and does not claim to resolve every cause of the timeout in issue 440.

Prepare grapheme counts lazily and skip candidates that cannot reach the
threshold or improve on the best match. Keep platform Jaro scoring for
survivors, the original traversal order and first-winner tie behavior.

Retain the full scan for empty or malformed input so pruning cannot hide
scorer exceptions. Cover inclusive thresholds, repeated Unicode graphemes,
ties, zero scores and malformed input through the merge API.
Comment thread lib/gettext/merger.ex Outdated
defp find_best_candidate(candidates, msgid, threshold) do
graphemes = String.graphemes(msgid)
size = length(graphemes)
counts = graphemes |> Enum.frequencies() |> Enum.sort_by(fn {_, count} -> -count end)

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.

Do you want

counts = graphemes |> Enum.frequencies() |> Enum.sort_by(fn {_, count} -> count end, :desc)

instead for clarity?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in fae25e4, it reads better. The line moved to Gettext.Fuzzy.find_match/3.

Comment thread lib/gettext/merger.ex Outdated
Comment on lines +234 to +259
# Matching graphemes cannot outnumber either string or their shared grapheme
# counts. Assuming no transpositions gives an upper bound on Jaro similarity.
# Keep the scorer's arithmetic order so inclusive thresholds stay inclusive.
defp jaro_upper_bound(_matches, 0, 0), do: 1.0
defp jaro_upper_bound(_matches, 0, _size), do: 0.0
defp jaro_upper_bound(_matches, _size, 0), do: 0.0

defp jaro_upper_bound(matches, size, old_size),
do: (matches / size + matches / old_size + 1.0) / 3

defp enough_common_graphemes?([], _old, _size, _old_size, _remaining, _target), do: true

defp enough_common_graphemes?(
[{grapheme, count} | rest],
old,
size,
old_size,
remaining,
target
) do
missing = max(count - Map.get(old, grapheme, 0), 0)
remaining = remaining - missing

(missing == 0 or jaro_upper_bound(min(remaining, old_size), size, old_size) >= target) and
enough_common_graphemes?(rest, old, size, old_size, remaining, target)
end

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.

I think most of the logic in this block belongs in Gettext.Fuzzy, not here. Thoughts?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, moved in fae25e4. Gettext.Fuzzy.candidates/1 counts the graphemes of the old msgids once and Gettext.Fuzzy.find_match/3 does the search. Fuzzy.matcher/1 had no caller left, so I removed it, and the tests moved to fuzzy_test.exs.

Comment thread lib/gettext/merger.ex Outdated

:error when fuzzy? ->
case maybe_merge_fuzzy(message, old, key, fuzzy_threshold) do
candidates = candidates || prepare_fuzzy_candidates(old, key)

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.

I find it really hard to follow that candidates can be nil or a map or a list of indexed messages. Can we pass the original map of messages around and the prepared index separately?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, that was hard to follow. The merger now builds the candidates once before the loop, only when fuzzy is on and some new message has no exact match, and they are always a list. The map of old messages is not involved any more. The map variant was a fallback for msgids with invalid UTF-8; now such a msgid is just never skipped, so String.jaro_distance/2 still does with it what it does on main.

Gettext.Fuzzy.candidates/1 counts the graphemes of the old msgids once
and Gettext.Fuzzy.find_match/3 searches them. The merger builds the
candidates before it goes over the new messages, only when one of them
has no exact match, so they are always a list.

A msgid that is not valid UTF-8 is never ruled out, which keeps what
String.jaro_distance/2 does with it. Fuzzy.matcher/1 had no other caller
and is removed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Comment thread lib/gettext/fuzzy.ex
the first of them is returned.
"""
@spec find_match(candidates, key, float) :: Message.t() | nil
def find_match(candidates, {_msgctxt, msgid} = key, threshold) do

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.

For a header-only PO file with no translations, we should be able to skip all this right? Something like:

def find_match(candidates, key, threshold)

def find_match([], _key, _threshold) do
  nil
end

def find_match(candidates, {_msgctxt, msgid} = key, threshold) do
  # ...what we have today
end

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, done in 8e2244f with your clauses. The merger calls find_match/3 for every new message without an exact match, so a header-only PO now returns right away. The existing empty-list test in fuzzy_test.exs covers the new clause.

A PO file with only a header has no messages to match against, so the
graphemes of the new msgid don't need to be counted.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
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.

2 participants