BUG #19031: pg_trgm infinite loop on certain cases

PG Bug reporting form <noreply@postgresql.org>

From: PG Bug reporting form <noreply@postgresql.org>
To: pgsql-bugs@lists.postgresql.org
Cc: washwithcare@gmail.com
Date: 2025-08-25T21:27:04Z
Lists: pgsql-bugs

Commits

Same data as JSON: GET /api/v1/messages/:b64id/commits the thread's linked commits as JSON, with link sources. API reference →
  1. Put "excludeOnly" GIN scan keys at the end of the scankey array.

  2. Do CHECK_FOR_INTERRUPTS inside, not before, scanGetItem.

The following bug has been logged on the website:

Bug reference:      19031
Logged by:          Tim Wood
Email address:      washwithcare@gmail.com
PostgreSQL version: 17.6
Operating system:   MacOS
Description:        

When querying against a column with a gin_trgm_ops index, using <% with a
string without any trigrams followed by a string with trigrams causes what
appears to be an infinite loop, and the query cannot be canceled, and the
process must be restarted in order to kill the long running query.

Simplified use case:

```
create extension if not exists pg_trgm with schema public;
create temp table simple_case (name text);
create index simple_case_name_index on simple_case using gin (name
gin_trgm_ops);

-- generate enough records for the optimizer to choose the index
insert into simple_case (name) select 'two and' || i::text from
generate_series(1, 1000000) as t(i);

select * from simple_case; -- returns normally

explain select * from simple_case where (',' <% name);
select * from simple_case where (',' <% name); -- returns normally

explain select * from simple_case where ('a' <% name) and (',' <% name);
select * from simple_case where ('a' <% name) and (',' <% name); -- returns
normally

explain select * from simple_case where ('a' <% name) and (',' <% name) and
('a' <% name);
select * from simple_case where ('a' <% name) and (',' <% name) and ('a' <%
name); -- returns normally

explain select * from simple_case where (',' <% name) and ('a' <% name);
select * from simple_case where (',' <% name) and ('a' <% name); -- infinite
loop
select * from simple_case where ('' <% name) and ('a' <% name); -- infinite
loop
```