BUG #19951: levenshtein_less_equal returns 0 when exact distance is 1 with a negative cost
Thread notes
1 note#bug
hackorum-bot#bug
@global #bug
The following bug has been logged on the website:
Bug reference: 19951
Logged by: Qifan Liu
Email address: imchifan@163.com
PostgreSQL version: 19.0
Operating system: Linux/amd64
Description:
Hi,
levenshtein_less_equal() can return a value that is not greater than max_d
even though the corresponding exact distance exceeds max_d. The functions
accept the negative edit cost used here, and the fuzzystrmatch documentation
does not prohibit negative costs.
Run this as a superuser.
The following can be run in a database where fuzzystrmatch is not already
installed:
\pset tuples_only on
\pset format unaligned
CREATE EXTENSION fuzzystrmatch;
WITH r AS (
SELECT levenshtein('a', 'b', -1, 2, 2) AS exact_distance,
levenshtein_less_equal('a', 'b', -1, 2, 2, 0) AS bounded_distance
)
SELECT exact_distance,
bounded_distance,
exact_distance > 0 AND bounded_distance <= 0 AS contract_violation
FROM r;
DROP EXTENSION fuzzystrmatch;
The output is:
Output format is unaligned.
CREATE EXTENSION
1|0|t
DROP EXTENSION
Since exact_distance is 1 and max_d is 0, bounded_distance should be greater
than 0, but it is 0.
Hi,
Thanks for the report.
On Wed, Nov 25, 2026 at 11:22 PM PG Bug reporting form
<noreply@postgresql.org> wrote:
WITH r AS (
SELECT levenshtein('a', 'b', -1, 2, 2) AS exact_distance,
levenshtein_less_equal('a', 'b', -1, 2, 2, 0) AS bounded_distance
)
I am not sure anyone is using negative costs here to hit this bug. So
it can probably be left as-is. I am still attaching a patch for a
couple of reasons.
1. levensthtein() does work currently with negative costs so it might
make sense to make levenshtein_less_equal() correct.
2. The change is very small where if any of the 3 costs are negative,
I just set max_d to -1 and let it take the unoptimized path. I
considered disallowing negative costs altogether but that won't be
backward compatible.
Thanks & Regards,
Nitin Motiani
Google