BUG #19937: Assertion failure (SIGABRT) in GiST KNN scan (computeDistance) on box with NaN coordinate

From: PG Bug reporting form <noreply(at)postgresql(dot)org>
To: pgsql-bugs(at)lists(dot)postgresql(dot)org
Cc: 798604270(at)qq(dot)com
Subject: BUG #19937: Assertion failure (SIGABRT) in GiST KNN scan (computeDistance) on box with NaN coordinate
Date: 2026-11-25 06:14:51
Message-ID: 19937-59d2a563ceecb0ab@postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

The following bug has been logged on the website:

Bug reference: 19937
Logged by: Chi Zhang
Email address: 798604270(at)qq(dot)com
PostgreSQL version: 19.0
Operating system: Ubuntu 24.04
Description:

Hi,

I found that a GiST KNN index scan (ORDER BY b <-> point(...)) on a box
column containing a NaN coordinate crashes assertion-enabled
(--enable-cassert) builds with SIGABRT in computeDistance()
(src/backend/access/gist/gistproc.c:1253), and fails with ERROR:
inconsistent point values on release builds, whereas a sequential scan
executes the same query cleanly.

This is the test case:
```
CREATE TEMP TABLE tb_knn (id int, b box);
INSERT INTO tb_knn VALUES (1, box(point('NaN', 0), point(1, 1))), (2,
box(point(0, 0), point(2, 2)));
CREATE INDEX tb_knn_gist ON tb_knn USING gist (b);

SET enable_seqscan = off; SET enable_indexscan = on; SET enable_bitmapscan =
off;
SELECT id FROM tb_knn ORDER BY b <-> point(1.5, 0.5);
```

The observed behavior on PostgreSQL 20devel (master, commit b4cc5e924b7a):
1) --enable-cassert build: Backend crashes with SIGABRT:
```
TRAP: failed Assert("box->low.x <= box->high.x"), File: "gistproc.c", Line:
1253
LOG: client backend was terminated by signal 6: Aborted
```
2) Release build (without cassert): Query aborts with:
```
ERROR: inconsistent point values
```

I analyzed the code and found the root cause might be that in
computeDistance() (postgres/src/backend/access/gist/gistproc.c:1239-1260),
raw C floating-point comparisons (<=, >=, <, >) are used without checking
for NaN:
1) For box(point('NaN', 0), point(1, 1)) (low=(1,0), high=(NaN,1)) and query
point(1.5, 0.5), point->y lies in [0, 1], entering the branch at line 1250.
2) Assert(box->low.x <= box->high.x) (line 1253) evaluates to false on NaN,
crashing debug builds.
3) Without assertions, both point->x > box->high.x (line 1254) and point->x
< box->low.x (line 1256) evaluate to false, falling through to elog(ERROR,
"inconsistent point values") (line 1259).
4) The symmetric y-coordinate branch at lines 1239–1249 has the same NaN
flaw when box->low.y or box->high.y is NaN.

Browse pgsql-bugs by date

  From Date Subject
Next Message PG Bug reporting form 2026-11-25 06:40:19 BUG #19938: BRIN index on box silently drops ordinary matching rows when a NaN box shares the same page range
Previous Message Michael Paquier 2026-11-25 06:01:23 Re: BUG #19890: pg_receivewal advances past a truncated LZ4 WAL segment