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

Started by PG Bug reporting form4 days ago1 messagesbugs

Thread notes

1 note#bug
hackorum-bot#bug
hackorum-bot
2 days ago

@global #bug

#bug
Jump to latest
#1PG Bug reporting form
noreply@postgresql.org

The following bug has been logged on the website:

Bug reference: 19937
Logged by: Chi Zhang
Email address: 798604270@qq.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.