Repository navigation
fix: cost-weight Levenshtein DP border base cases (InsertCost/DeleteCost silently ignored) - #69
binggao1230 wants to merge 1 commit into
Conversation
The Wagner-Fischer border base cases in metrics/levenshtein.go used the bare
row index instead of the cost-weighted value:
- prevCol init: prevCol[i] = i -> i * m.InsertCost
- col[0] per row: col[0] = i + 1 -> (i + 1) * m.DeleteCost
The first column represents transforming the empty prefix of a into the first
i+1 characters of b (i+1 insertions), and col[0] represents transforming the
first i+1 characters of a into the empty prefix of b (i+1 deletions), so both
borders must be weighted by the corresponding public InsertCost / DeleteCost
fields. The recurrence body already used m.InsertCost / m.DeleteCost
correctly; only the borders were wrong.
Because the bare index equals the cost-weighted value when the cost is 1
(1*c == c), the bug is silent under the default unit costs (InsertCost=1,
DeleteCost=1, ReplaceCost=1) and only fires when a non-unit insert/delete cost
is configured. This makes the documented public InsertCost and DeleteCost
fields actually take effect.
Example: Levenshtein{InsertCost: 10}.Distance("x", "abcx") previously
returned 3 (less than the cost of a single insert, which is impossible since
3 insertions are required); it now returns 30.
Adds metrics/levenshtein_cost_test.go: custom-cost weight cases (the 9
previously-wrong results), unit-cost regression guards, empty-string
fast-paths and an explicit cost-bound smoking-gun assertion. Default unit-cost
results are unchanged.
bardrop
left a comment
There was a problem hiding this comment.
The Distance fix looks right to me. I checked this branch against rapidfuzz's weighted Levenshtein (weights=(ins, del, sub)) on 20k random pairs (costs 1–6 / 1–12, with some non-ASCII) and got 0 mismatches.
One problem: the new tests lock in negative Compare results ("-6.50", "-4.25", …). But the doc comment on Compare says the result is "a number between 0 and 1". With non-unit costs, 1 - distance/maxLen drops below 0 in most cases. In the same 20k pairs, 17,268 Compare results were negative. For example:
l := metrics.NewLevenshtein()
l.InsertCost, l.DeleteCost, l.ReplaceCost = 4, 3, 9
l.Compare("bcé", "a") // -3.33The cause is that maxLen is the upper bound on the distance only when all costs are 1. If Compare divided by the largest distance possible under the configured costs, it would stay in [0, 1] and still give the same results as today for unit costs. That bound is the same one rapidfuzz's normalized_distance uses:
// replace the shorter string's chars, then insert/delete the rest; or delete all of a and insert all of b
maxDist := lenA*m.DeleteCost + lenB*m.InsertCost
if lenA >= lenB {
maxDist = mathutil.Min(maxDist, lenB*m.ReplaceCost+(lenA-lenB)*m.DeleteCost)
} else {
maxDist = mathutil.Min(maxDist, lenA*m.ReplaceCost+(lenB-lenA)*m.InsertCost)
}
return 1 - float64(distance)/float64(maxDist)With that, Compare("x", "abcx") at InsertCost=10 is 1 - 30/31 ≈ 0.03 instead of -6.50. Over the same 20k pairs it matches 1 - rapidfuzz.normalized_distance and never goes below 0. Whether that belongs in this PR or a follow-up is up to you. Either way, I don't think the tests should assert the negative values.
Summary
Levenshteinexposes public, documentedInsertCost,DeleteCostandReplaceCostfields (defaults1/1/1), and the Wagner–Fischer recurrence body honours them correctly. However the two DP border base cases use the bare row index instead of the cost-weighted value, soInsertCostandDeleteCostare silently ignored at the borders.Distance(and thereforeCompare) undercount whenever a non-unit insert/delete cost is configured.Smoking gun (cost-bound impossibility)
Transforming
"x"into"abcx"requires 3 insertions, so the true minimum is3 * 10 = 30. The returned3is less than the cost of a single insert (10) — logically impossible under cost-weighted semantics, and a clear signal thatInsertCostis not being honoured at the border.Root cause
metrics/levenshtein.go,distance():The recurrence body (
delCost := prevCol[j+1] + m.DeleteCost,insCost := col[j] + m.InsertCost) is already correct — only the two borders were wrong.Because the bare index equals the cost-weighted value when the cost is
1(1*c == c), the bug is silent under the default unit costs and only fires when a non-unitInsertCostorDeleteCostis set — exactly the scenario the public fields exist to support.Dual-oracle confirmation
Two independent cost-weighted Wagner–Fischer implementations agree with each other and contradict
adrg/strutilon exactly the buggy cases:xrash/smetrics.WagnerFischer"x"→"abcx""abcx"→"x"kitten/sittingsitting/kittenflaw/lawn"a"→"abcde""abcde"→"a"intention/executionGGACT/GAGCG9 / 16 custom-cost cases wrong; all 7 unit-cost + empty-string cases correct. (Implementations that only handle unit-cost Levenshtein were deliberately not used as oracles — they would beg the question.)
The fix
Two-line, minimal, style-matching change in
metrics/levenshtein.go:Because
1*c == c, every default unit-cost result is unchanged — this PR makes the documented publicInsertCost/DeleteCostfields actually take effect, with zero impact on default-cost users.Tests
Adds
metrics/levenshtein_cost_test.go(table-driven, follows the existingmetrics_test.gostyle):TestLevenshteinCustomCostWeights— the 9 previously-wrong cases + mirrors + pure-insert/pure-delete paths, asserting bothDistanceandCompare.TestLevenshteinUnitCostUnchanged— unit-cost regression guards (kitten/sitting=3,flaw/lawn=2,intention/execution=5, …) proving defaults are unaffected.TestLevenshteinEmptyStringFastPaths— the early-return paths (which already multiplied by the cost) for both unit and non-unit costs.TestLevenshteinCostBoundSmokingGun— the explicit cost-bound assertion: 3 inserts @InsertCost=10⇒ distance30, anddistance >= InsertCost.Verification
go test ./metrics/ -run 'TestLevenshtein|ExampleLevenshtein' -v→ 6/6 PASS (4 new +TestLevenshtein+ExampleLevenshtein).go vet ./...→ clean.gofmt -l metrics/levenshtein.go metrics/levenshtein_cost_test.go→ clean.TestJaroWinkler/ExampleJaroWinklerfailures are unrelated to this change (Jaro–Winkler floating-point rounding0.80vs0.81, reproduces on pristinee955441without this patch; this PR does not touchjaro.go/jaro_winkler.go).Files
metrics/levenshtein.go(+12/-2)metrics/levenshtein_cost_test.go(+149, new)