pg.ddx.io pgsql-bugs@postgresql.org mailing list archive
help / color / mirror / Atom feedBUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
11+ messages / 4 participants
[nested] [flat]
Commits from this thread:
2026-11-23 492bc90572 6b90b651a7 210e6c983e f572f1a11a d4d8e1159a 15b3dc140d Fix overflow problems in btree_gist's penalty and distance functions.
* BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-10-15 14:09 PG Bug reporting form <noreply@postgresql.org>
0 siblings, 1 reply; 11+ messages in thread
From: PG Bug reporting form @ 2026-10-15 14:09 UTC (permalink / raw)
To: pgsql-bugs@lists.postgresql.org; +Cc: alpkeles99@gmail.com
The following bug has been logged on the website:
Bug reference: 19761
Logged by: Alperen Keles
Email address: alpkeles99@gmail.com
PostgreSQL version: 18.6
Operating system: macOS 26 arm64 (also Ubuntu 24.04 x86_64)
Description:
With contrib/btree_gist, a GiST index on a date column rejects the values
'infinity' and '-infinity' once the index has more than one page:
ERROR: 22008: cannot subtract infinite dates
LOCATION: date_mi, date.c:556
Inserting finite dates also fails once the index holds an infinity, and so
does a KNN search (ORDER BY d <-> ...) over such an index. The timestamp and
timestamptz opclasses handle all of these cases.
Versions tested (both behave the same):
- master at 158b6d5109f (PostgreSQL 20devel), --enable-cassert
--enable-debug
- REL_18_STABLE at a85b5523e67 (reports 18.6)
Platform: macOS 26 (Darwin 25.6.0), Apple M-series arm64, Apple clang
21.0.0.
Rechecked on 2026-10-15 (Ubuntu 24.04, x86_64, gcc 13.3, --enable-cassert
--enable-debug, server under ulimit -v 6 GB): the same five errors on
master aa7b9cf132b, 19rc1 (REL_19_STABLE 0fb192f1b02) and REL_18_STABLE
4d62ef92fda.
Fresh initdb, default configuration except fsync=off; empty ~/.psqlrc.
Script:
\set VERBOSITY verbose
CREATE EXTENSION btree_gist;
CREATE TABLE t (d date);
CREATE INDEX t_d_idx ON t USING gist (d);
-- about 410+ rows are enough for the index to grow past one page
INSERT INTO t SELECT date '2000-01-01' + i FROM generate_series(1, 500) i;
INSERT INTO t VALUES ('infinity');
INSERT INTO t VALUES ('-infinity');
-- an index built over rows that already hold infinities (sorted build)
-- succeeds, but later inserts and KNN searches fail
CREATE TABLE u (d date);
INSERT INTO u SELECT date '2000-01-01' + i FROM generate_series(1, 500) i;
INSERT INTO u VALUES ('infinity'), ('-infinity');
CREATE INDEX u_d_idx ON u USING gist (d);
INSERT INTO u VALUES ('2000-06-01');
SET enable_seqscan = off;
SELECT d FROM u ORDER BY d <-> date '2000-06-01' LIMIT 1;
-- the scalar operator rejects infinity as well
SELECT date 'infinity' <-> date '2000-01-01';
-- for comparison, timestamp handles all of this
CREATE TABLE ts (x timestamp);
CREATE INDEX ts_x_idx ON ts USING gist (x);
INSERT INTO ts SELECT timestamp '2000-01-01' + i * interval '1 day' FROM
generate_series(1, 500) i;
INSERT INTO ts VALUES ('infinity'), ('-infinity');
SELECT timestamp 'infinity' <-> timestamp '2000-01-01';
Actual output (master; 18 is identical except date.c:560):
INSERT 0 500
ERROR: 22008: cannot subtract infinite dates <- INSERT 'infinity'
ERROR: 22008: cannot subtract infinite dates <- INSERT '-infinity'
CREATE INDEX <- u_d_idx builds fine
ERROR: 22008: cannot subtract infinite dates <- INSERT '2000-06-01'
into u
ERROR: 22008: cannot subtract infinite dates <- ORDER BY d <-> ...
LIMIT 1
ERROR: 22008: cannot subtract infinite dates <- date 'infinity' <->
date
INSERT 0 2 <- timestamp infinities
OK
infinity <- timestamp <-> result
Expected output: the inserts succeed, the KNN query returns 2000-06-01, and
date <-> returns a saturated value instead of an error, as it does for
timestamp. The table accepts these values without the index, and so does a
btree index.
UPDATE ... SET d = 'infinity' and COPY fail the same way. So does
CREATE INDEX ... WITH (buffering = on) over a table that holds infinities,
since that path does not use the sorted build. Before the sorted build for
btree_gist (e4309f73f69, v18), I believe a plain CREATE INDEX over such a
table would fail as well, but I did not test older branches.
Cause: contrib/btree_gist/btree_date.c computes key differences with
DirectFunctionCall2(date_mi, ...). Since date got infinities in 8.4
(a303e4dc431), date_mi raises an error for infinite input
(src/backend/utils/adt/date.c:553-556). The calls are:
- gbt_date_penalty, lines 212, 218, 228. gistchoose calls it on every
insert once the root is an internal page, which is why a single-page
index does not show the problem. Backtrace (backtrace_functions =
'date_mi'): date_mi <- gbt_date_penalty <- gistchoose <- gistdoinsert.
- gdb_date_dist, line 95 (KNN distance, via gbt_date_distance and
gistScanPage).
- date_dist, line 123 (the date <-> date operator).
btree_ts.c avoids this. gbt_ts_penalty does its own double arithmetic on the
raw int64 values, gbt_ts_dist returns get_float8_infinity() for non-finite
input, and ts_dist/tstz_dist return a saturated interval.
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-10-16 09:15 Nitin Motiani <nitinmotiani@google.com>
parent: PG Bug reporting form <noreply@postgresql.org>
0 siblings, 1 reply; 11+ messages in thread
From: Nitin Motiani @ 2026-10-16 09:15 UTC (permalink / raw)
To: alpkeles99@gmail.com; pgsql-bugs@lists.postgresql.org
Hi,
Thanks for the analysis. I was able to reproduce the issue.
On Thu, Oct 15, 2026 at 9:03 PM PG Bug reporting form
<noreply@postgresql.org> wrote:
>
> btree_ts.c avoids this. gbt_ts_penalty does its own double arithmetic on the
> raw int64 values, gbt_ts_dist returns get_float8_infinity() for non-finite
> input, and ts_dist/tstz_dist return a saturated interval.
>
I'm attaching a patch which uses the same logic as btree_ts.c and
btree_int.c in btree_date.co to handle these issues. Please take a
look.
Thanks & Regards
Nitin Motiani,
Google
Attachments:
v1-0001-btree_gist-Fix-cannot-subtract-infinite-dates-err.patch (application/x-patch, 4.9K) download
From be83b080e4bb361c8c16c5992d3b8ad4ae1355a9 Mon Sep 17 00:00:00 2001
From: Nitin Motiani <nitinmotiani@google.com>
Date: Fri, 16 Oct 2026 07:45:01 +0000
Subject: [PATCH v1] btree_gist: Fix "cannot subtract infinite dates" errors.
The date opclass's penalty and KNN distance functions used date_mi(),
which rejects infinite dates. Once a GiST index on a date column had
internal pages, inserting 'infinity' or '-infinity' failed, as did any
later insert or KNN search on an index already containing one.
Compute the penalty with penalty_num(), as the int4 and timestamp
opclasses do, and make the distance function return infinity for
infinite inputs, as gbt_ts_dist() does.
Reported-by: Alperen Keles <alpkeles99@gmail.com>
Discussion: https://postgr.es/m/19761-b72cfc453e487610@postgresql.org
---
contrib/btree_gist/btree_date.c | 45 ++++++++++------------------
contrib/btree_gist/expected/date.out | 13 ++++++++
contrib/btree_gist/sql/date.sql | 7 +++++
3 files changed, 35 insertions(+), 30 deletions(-)
diff --git a/contrib/btree_gist/btree_date.c b/contrib/btree_gist/btree_date.c
index 1824a3d0e6e..0db640511af 100644
--- a/contrib/btree_gist/btree_date.c
+++ b/contrib/btree_gist/btree_date.c
@@ -91,12 +91,14 @@ gbt_datekey_cmp(const void *a, const void *b, FmgrInfo *flinfo)
static float8
gdb_date_dist(const void *a, const void *b, FmgrInfo *flinfo)
{
- /* we assume the difference can't overflow */
- Datum diff = DirectFunctionCall2(date_mi,
- DateADTGetDatum(*((const DateADT *) a)),
- DateADTGetDatum(*((const DateADT *) b)));
+ DateADT da = *((const DateADT *) a);
+ DateADT db = *((const DateADT *) b);
- return (float8) abs(DatumGetInt32(diff));
+ if (DATE_NOT_FINITE(da) || DATE_NOT_FINITE(db))
+ return get_float8_infinity();
+
+ /* the difference of two finite dates always fits in int32 */
+ return (float8) abs(da - db);
}
@@ -206,32 +208,15 @@ gbt_date_penalty(PG_FUNCTION_ARGS)
dateKEY *origentry = (dateKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
dateKEY *newentry = (dateKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(1))->key);
float *result = (float *) PG_GETARG_POINTER(2);
- int32 diff,
- res;
-
- diff = DatumGetInt32(DirectFunctionCall2(date_mi,
- DateADTGetDatum(newentry->upper),
- DateADTGetDatum(origentry->upper)));
-
- res = Max(diff, 0);
-
- diff = DatumGetInt32(DirectFunctionCall2(date_mi,
- DateADTGetDatum(origentry->lower),
- DateADTGetDatum(newentry->lower)));
-
- res += Max(diff, 0);
-
- *result = 0.0;
- if (res > 0)
- {
- diff = DatumGetInt32(DirectFunctionCall2(date_mi,
- DateADTGetDatum(origentry->upper),
- DateADTGetDatum(origentry->lower)));
- *result += FLT_MIN;
- *result += (float) (res / ((double) (res + diff)));
- *result *= (FLT_MAX / (((GISTENTRY *) PG_GETARG_POINTER(0))->rel->rd_att->natts + 1));
- }
+ /*
+ * Don't use date_mi here: it rejects infinite dates, and plain int32
+ * subtraction could overflow for them (DATEVAL_NOBEGIN/NOEND are
+ * INT32_MIN/INT32_MAX). penalty_num computes in double, where every
+ * int32 and every difference of two int32s is exact.
+ */
+ penalty_num(result, origentry->lower, origentry->upper,
+ newentry->lower, newentry->upper);
PG_RETURN_POINTER(result);
}
diff --git a/contrib/btree_gist/expected/date.out b/contrib/btree_gist/expected/date.out
index 5db864bb82c..7a8e36111a3 100644
--- a/contrib/btree_gist/expected/date.out
+++ b/contrib/btree_gist/expected/date.out
@@ -89,3 +89,16 @@ SELECT a, a <-> '2001-02-13' FROM datetmp ORDER BY a <-> '2001-02-13' LIMIT 3;
03-24-2001 | 39
(3 rows)
+-- infinite dates in an index with internal pages (penalty and KNN distance)
+CREATE TABLE dateinf (a date);
+CREATE INDEX dateinfidx ON dateinf USING gist ( a );
+INSERT INTO dateinf SELECT '2000-01-01'::date + i FROM generate_series(1, 1000) i;
+INSERT INTO dateinf VALUES ('infinity'), ('-infinity');
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+ a
+------------
+ 01-02-2000
+ 01-03-2000
+ 01-04-2000
+(3 rows)
+
diff --git a/contrib/btree_gist/sql/date.sql b/contrib/btree_gist/sql/date.sql
index f969ef0a08c..c371f8d9a2c 100644
--- a/contrib/btree_gist/sql/date.sql
+++ b/contrib/btree_gist/sql/date.sql
@@ -35,3 +35,10 @@ SELECT count(*) FROM datetmp WHERE a > '2001-02-13'::date;
EXPLAIN (COSTS OFF)
SELECT a, a <-> '2001-02-13' FROM datetmp ORDER BY a <-> '2001-02-13' LIMIT 3;
SELECT a, a <-> '2001-02-13' FROM datetmp ORDER BY a <-> '2001-02-13' LIMIT 3;
+
+-- infinite dates in an index with internal pages (penalty and KNN distance)
+CREATE TABLE dateinf (a date);
+CREATE INDEX dateinfidx ON dateinf USING gist ( a );
+INSERT INTO dateinf SELECT '2000-01-01'::date + i FROM generate_series(1, 1000) i;
+INSERT INTO dateinf VALUES ('infinity'), ('-infinity');
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
--
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-10-23 07:04 Dilip Kumar <dilipbalaut@gmail.com>
parent: Nitin Motiani <nitinmotiani@google.com>
0 siblings, 1 reply; 11+ messages in thread
From: Dilip Kumar @ 2026-10-23 07:04 UTC (permalink / raw)
To: Nitin Motiani <nitinmotiani@google.com>; +Cc: alpkeles99@gmail.com; pgsql-bugs@lists.postgresql.org
On Fri, Oct 16, 2026 at 2:45 PM Nitin Motiani <nitinmotiani@google.com> wrote:
>
> Hi,
>
> Thanks for the analysis. I was able to reproduce the issue.
>
> On Thu, Oct 15, 2026 at 9:03 PM PG Bug reporting form
> <noreply@postgresql.org> wrote:
> >
> > btree_ts.c avoids this. gbt_ts_penalty does its own double arithmetic on the
> > raw int64 values, gbt_ts_dist returns get_float8_infinity() for non-finite
> > input, and ts_dist/tstz_dist return a saturated interval.
> >
>
> I'm attaching a patch which uses the same logic as btree_ts.c and
> btree_int.c in btree_date.co to handle these issues. Please take a
> look.
So IIUC the issue relates to the btree date handling function and not
to gist? If so we can use a normal btree index in the new test cases
we have added instead of gist. I haven't yet reviewed the code
completely but I will do it soon.
--
Regards,
Dilip Kumar
Google
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-10-23 13:14 Nitin Motiani <nitinmotiani@google.com>
parent: Dilip Kumar <dilipbalaut@gmail.com>
0 siblings, 1 reply; 11+ messages in thread
From: Nitin Motiani @ 2026-10-23 13:14 UTC (permalink / raw)
To: Dilip Kumar <dilipbalaut@gmail.com>; +Cc: alpkeles99@gmail.com; pgsql-bugs@lists.postgresql.org
On Fri, Oct 23, 2026 at 12:34 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:
>
> So IIUC the issue relates to the btree date handling function and not
> to gist? If so we can use a normal btree index in the new test cases
> we have added instead of gist. I haven't yet reviewed the code
> completely but I will do it soon.
>
Thanks for taking a look, Dilip. The issue is specific to GiST.
contrib/btree_gist/btree_date.c is the GiST operator class for date in
the btree_gist extension, not btree code[1]. The failing functions are
its GiST penalty and distance support functions (gbt_date_penalty and
gdb_date_dist). GiST calls them when routing inserts through internal
pages and for KNN searches. A regular btree index on date never calls
these functions. I tested the standard btree date functions with
infinity, -infinity and they pass without the fix.
That's why the test uses a GiST index with enough rows to have
internal pages. On unpatched code, the INSERT of infinite dates fails
in the penalty function, and the KNN query fails in the distance
function. With the patch, both pass.
One question which I'm unclear on : the bug report also noted that the
SQL operator date <-> date (date_dist in btree_date.c) fails on
+/-infinity. In v1, I left date_dist unchanged because its return type
is int4, which has no infinity representation (similar to int4_dist
raising an error when the distance cannot fit in int4). The
alternative is to make date_dist return PG_INT32_MAX for infinite
inputs, similar to how ts_dist saturates for timestamp. Do you think
we should saturate date_dist to PG_INT32_MAX as well, or keep the
error for the SQL operator?
Regards,
Nitin Motiani
Google
[1] https://www.postgresql.org/docs/current/btree-gist.html
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-10-25 06:20 Dilip Kumar <dilipbalaut@gmail.com>
parent: Nitin Motiani <nitinmotiani@google.com>
0 siblings, 1 reply; 11+ messages in thread
From: Dilip Kumar @ 2026-10-25 06:20 UTC (permalink / raw)
To: Nitin Motiani <nitinmotiani@google.com>; +Cc: alpkeles99@gmail.com; pgsql-bugs@lists.postgresql.org
On Fri, Oct 23, 2026 at 6:44 PM Nitin Motiani <nitinmotiani@google.com> wrote:
>
> On Fri, Oct 23, 2026 at 12:34 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:
> >
> > So IIUC the issue relates to the btree date handling function and not
> > to gist? If so we can use a normal btree index in the new test cases
> > we have added instead of gist. I haven't yet reviewed the code
> > completely but I will do it soon.
> >
>
> Thanks for taking a look, Dilip. The issue is specific to GiST.
> contrib/btree_gist/btree_date.c is the GiST operator class for date in
> the btree_gist extension, not btree code[1]. The failing functions are
> its GiST penalty and distance support functions (gbt_date_penalty and
> gdb_date_dist). GiST calls them when routing inserts through internal
> pages and for KNN searches. A regular btree index on date never calls
> these functions. I tested the standard btree date functions with
> infinity, -infinity and they pass without the fix.
>
> That's why the test uses a GiST index with enough rows to have
> internal pages. On unpatched code, the INSERT of infinite dates fails
> in the penalty function, and the KNN query fails in the distance
> function. With the patch, both pass.
Okay that make sense.
> One question which I'm unclear on : the bug report also noted that the
> SQL operator date <-> date (date_dist in btree_date.c) fails on
> +/-infinity. In v1, I left date_dist unchanged because its return type
> is int4, which has no infinity representation (similar to int4_dist
> raising an error when the distance cannot fit in int4). The
> alternative is to make date_dist return PG_INT32_MAX for infinite
> inputs, similar to how ts_dist saturates for timestamp. Do you think
> we should saturate date_dist to PG_INT32_MAX as well, or keep the
> error for the SQL operator?
I think we must fix date_dist as well otherwise it may cause
inconsistent behavior between index scan and sequence scan, see below
example
CREATE TABLE t (d date);
CREATE INDEX t_d_idx ON t USING gist (d);
INSERT INTO t SELECT date '2000-01-01' + i FROM generate_series(1, 500) i;
INSERT INTO t VALUES ('infinity');
INSERT INTO t VALUES ('-infinity');
postgres[3265593]=# SELECT d FROM t ORDER BY d <-> '2000-06-01' LIMIT 1;
d
------------
2000-06-01
(1 row)
-- Now test by turning off the index scan
postgres[3265593]=# set enable_indexscan =off;
postgres[3265593]=# SELECT d FROM t ORDER BY d <-> '2000-06-01' LIMIT 1;
2026-10-25 06:15:58.591 UTC [3265593] ERROR: cannot subtract infinite dates
2026-10-25 06:15:58.591 UTC [3265593] STATEMENT: SELECT d FROM t
ORDER BY d <-> '2000-06-01' LIMIT 1;
ERROR: 22008: cannot subtract infinite dates
LOCATION: date_mi, date.c:554
--
Regards,
Dilip Kumar
Google
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-10-25 11:35 Nitin Motiani <nitinmotiani@google.com>
parent: Dilip Kumar <dilipbalaut@gmail.com>
0 siblings, 2 replies; 11+ messages in thread
From: Nitin Motiani @ 2026-10-25 11:35 UTC (permalink / raw)
To: Dilip Kumar <dilipbalaut@gmail.com>; +Cc: alpkeles99@gmail.com; pgsql-bugs@lists.postgresql.org
On Sun, Oct 25, 2026 at 11:51 AM Dilip Kumar <dilipbalaut@gmail.com> wrote:
>
> I think we must fix date_dist as well otherwise it may cause
> inconsistent behavior between index scan and sequence scan, see below
> example
>
> CREATE TABLE t (d date);
> CREATE INDEX t_d_idx ON t USING gist (d);
> INSERT INTO t SELECT date '2000-01-01' + i FROM generate_series(1, 500) i;
> INSERT INTO t VALUES ('infinity');
> INSERT INTO t VALUES ('-infinity');
>
> postgres[3265593]=# SELECT d FROM t ORDER BY d <-> '2000-06-01' LIMIT 1;
> d
> ------------
> 2000-06-01
> (1 row)
>
> -- Now test by turning off the index scan
>
> postgres[3265593]=# set enable_indexscan =off;
> postgres[3265593]=# SELECT d FROM t ORDER BY d <-> '2000-06-01' LIMIT 1;
> 2026-10-25 06:15:58.591 UTC [3265593] ERROR: cannot subtract infinite dates
> 2026-10-25 06:15:58.591 UTC [3265593] STATEMENT: SELECT d FROM t
> ORDER BY d <-> '2000-06-01' LIMIT 1;
> ERROR: 22008: cannot subtract infinite dates
> LOCATION: date_mi, date.c:554
>
> --
Thanks for the review, Dilip. I'm attaching the v2 patch which makes
the change in date_dist also.
Regards,
Nitin Motiani
Google
Attachments:
v2-0001-btree_gist-Fix-cannot-subtract-infinite-dates-err.patch (application/x-patch, 7.2K) download
From c090b789114a424ff2672f59b6d0cbb8acfaa4b2 Mon Sep 17 00:00:00 2001
From: Nitin Motiani <nitinmotiani@google.com>
Date: Fri, 16 Oct 2026 07:45:01 +0000
Subject: [PATCH v2] btree_gist: Fix "cannot subtract infinite dates" errors.
The date opclass's penalty and distance functions used date_mi(),
which rejects infinite dates. Once a GiST index on a date column had
internal pages, inserting 'infinity' or '-infinity' failed, as did any
later insert or KNN search on an index already containing one. The
date <-> date operator failed the same way, so ORDER BY d <-> x could
succeed with a KNN index scan but fail with a sort.
Compute the penalty with penalty_num(), as the int4 and timestamp
opclasses do. Make the KNN distance function return infinity for
infinite inputs, as gbt_ts_dist() does, and make the <-> operator
return INT_MAX for them, as ts_dist() does. No difference of two
finite dates reaches INT_MAX, so both plans order rows the same way.
Reported-by: Alperen Keles <alpkeles99@gmail.com>
Discussion: https://postgr.es/m/19761-b72cfc453e487610@postgresql.org
---
contrib/btree_gist/btree_date.c | 65 +++++++++++++---------------
contrib/btree_gist/expected/date.out | 43 ++++++++++++++++++
contrib/btree_gist/sql/date.sql | 17 ++++++++
3 files changed, 89 insertions(+), 36 deletions(-)
diff --git a/contrib/btree_gist/btree_date.c b/contrib/btree_gist/btree_date.c
index 1824a3d0e6e..f1f3cba65b0 100644
--- a/contrib/btree_gist/btree_date.c
+++ b/contrib/btree_gist/btree_date.c
@@ -91,12 +91,14 @@ gbt_datekey_cmp(const void *a, const void *b, FmgrInfo *flinfo)
static float8
gdb_date_dist(const void *a, const void *b, FmgrInfo *flinfo)
{
- /* we assume the difference can't overflow */
- Datum diff = DirectFunctionCall2(date_mi,
- DateADTGetDatum(*((const DateADT *) a)),
- DateADTGetDatum(*((const DateADT *) b)));
+ DateADT da = *((const DateADT *) a);
+ DateADT db = *((const DateADT *) b);
- return (float8) abs(DatumGetInt32(diff));
+ if (DATE_NOT_FINITE(da) || DATE_NOT_FINITE(db))
+ return get_float8_infinity();
+
+ /* the difference of two finite dates always fits in int32 */
+ return (float8) abs(da - db);
}
@@ -119,12 +121,20 @@ PG_FUNCTION_INFO_V1(date_dist);
Datum
date_dist(PG_FUNCTION_ARGS)
{
- /* we assume the difference can't overflow */
- Datum diff = DirectFunctionCall2(date_mi,
- PG_GETARG_DATUM(0),
- PG_GETARG_DATUM(1));
-
- PG_RETURN_INT32(abs(DatumGetInt32(diff)));
+ DateADT a = PG_GETARG_DATEADT(0);
+ DateADT b = PG_GETARG_DATEADT(1);
+
+ /*
+ * int4 has no infinity, so saturate for infinite inputs, as ts_dist does
+ * for timestamps. This is consistent with the ordering produced by
+ * gdb_date_dist, since no difference of two finite dates reaches
+ * PG_INT32_MAX.
+ */
+ if (DATE_NOT_FINITE(a) || DATE_NOT_FINITE(b))
+ PG_RETURN_INT32(PG_INT32_MAX);
+
+ /* the difference of two finite dates always fits in int32 */
+ PG_RETURN_INT32(abs(a - b));
}
@@ -206,32 +216,15 @@ gbt_date_penalty(PG_FUNCTION_ARGS)
dateKEY *origentry = (dateKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
dateKEY *newentry = (dateKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(1))->key);
float *result = (float *) PG_GETARG_POINTER(2);
- int32 diff,
- res;
-
- diff = DatumGetInt32(DirectFunctionCall2(date_mi,
- DateADTGetDatum(newentry->upper),
- DateADTGetDatum(origentry->upper)));
-
- res = Max(diff, 0);
-
- diff = DatumGetInt32(DirectFunctionCall2(date_mi,
- DateADTGetDatum(origentry->lower),
- DateADTGetDatum(newentry->lower)));
-
- res += Max(diff, 0);
-
- *result = 0.0;
- if (res > 0)
- {
- diff = DatumGetInt32(DirectFunctionCall2(date_mi,
- DateADTGetDatum(origentry->upper),
- DateADTGetDatum(origentry->lower)));
- *result += FLT_MIN;
- *result += (float) (res / ((double) (res + diff)));
- *result *= (FLT_MAX / (((GISTENTRY *) PG_GETARG_POINTER(0))->rel->rd_att->natts + 1));
- }
+ /*
+ * Don't use date_mi here: it rejects infinite dates, and plain int32
+ * subtraction could overflow for them (DATEVAL_NOBEGIN/NOEND are
+ * INT32_MIN/INT32_MAX). penalty_num computes in double, where every
+ * int32 and every difference of two int32s is exact.
+ */
+ penalty_num(result, origentry->lower, origentry->upper,
+ newentry->lower, newentry->upper);
PG_RETURN_POINTER(result);
}
diff --git a/contrib/btree_gist/expected/date.out b/contrib/btree_gist/expected/date.out
index 5db864bb82c..f32d0f84e93 100644
--- a/contrib/btree_gist/expected/date.out
+++ b/contrib/btree_gist/expected/date.out
@@ -89,3 +89,46 @@ SELECT a, a <-> '2001-02-13' FROM datetmp ORDER BY a <-> '2001-02-13' LIMIT 3;
03-24-2001 | 39
(3 rows)
+-- infinite dates in an index with internal pages (penalty and KNN distance)
+CREATE TABLE dateinf (a date);
+CREATE INDEX dateinfidx ON dateinf USING gist ( a );
+INSERT INTO dateinf SELECT '2000-01-01'::date + i FROM generate_series(1, 1000) i;
+INSERT INTO dateinf VALUES ('infinity'), ('-infinity');
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+ a
+------------
+ 01-02-2000
+ 01-03-2000
+ 01-04-2000
+(3 rows)
+
+-- same ordering via sort, which evaluates the <-> operator on every row
+SET enable_seqscan = on;
+SET enable_indexscan = off;
+SET enable_indexonlyscan = off;
+EXPLAIN (COSTS OFF)
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+ QUERY PLAN
+------------------------------------------------
+ Limit
+ -> Sort
+ Sort Key: ((a <-> '01-01-2000'::date))
+ -> Seq Scan on dateinf
+(4 rows)
+
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+ a
+------------
+ 01-02-2000
+ 01-03-2000
+ 01-04-2000
+(3 rows)
+
+RESET enable_indexscan;
+RESET enable_indexonlyscan;
+SELECT 'infinity'::date <-> '2000-01-01'::date, '-infinity'::date <-> '2000-01-01'::date;
+ ?column? | ?column?
+------------+------------
+ 2147483647 | 2147483647
+(1 row)
+
diff --git a/contrib/btree_gist/sql/date.sql b/contrib/btree_gist/sql/date.sql
index f969ef0a08c..f071740ca0c 100644
--- a/contrib/btree_gist/sql/date.sql
+++ b/contrib/btree_gist/sql/date.sql
@@ -35,3 +35,20 @@ SELECT count(*) FROM datetmp WHERE a > '2001-02-13'::date;
EXPLAIN (COSTS OFF)
SELECT a, a <-> '2001-02-13' FROM datetmp ORDER BY a <-> '2001-02-13' LIMIT 3;
SELECT a, a <-> '2001-02-13' FROM datetmp ORDER BY a <-> '2001-02-13' LIMIT 3;
+
+-- infinite dates in an index with internal pages (penalty and KNN distance)
+CREATE TABLE dateinf (a date);
+CREATE INDEX dateinfidx ON dateinf USING gist ( a );
+INSERT INTO dateinf SELECT '2000-01-01'::date + i FROM generate_series(1, 1000) i;
+INSERT INTO dateinf VALUES ('infinity'), ('-infinity');
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+-- same ordering via sort, which evaluates the <-> operator on every row
+SET enable_seqscan = on;
+SET enable_indexscan = off;
+SET enable_indexonlyscan = off;
+EXPLAIN (COSTS OFF)
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+RESET enable_indexscan;
+RESET enable_indexonlyscan;
+SELECT 'infinity'::date <-> '2000-01-01'::date, '-infinity'::date <-> '2000-01-01'::date;
--
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-10-26 11:21 Nitin Motiani <nitinmotiani@google.com>
parent: Nitin Motiani <nitinmotiani@google.com>
1 sibling, 0 replies; 11+ messages in thread
From: Nitin Motiani @ 2026-10-26 11:21 UTC (permalink / raw)
To: Dilip Kumar <dilipbalaut@gmail.com>; +Cc: alpkeles99@gmail.com; pgsql-bugs@lists.postgresql.org
On Sun, Oct 25, 2026 at 5:05 PM Nitin Motiani <nitinmotiani@google.com> wrote:
>
> Thanks for the review, Dilip. I'm attaching the v2 patch which makes
> the change in date_dist also.
>
Hi Dilip,
I have created a commitfest entry for this at
https://commitfest.postgresql.org/patch/7517/.
Thanks & Regards,
Nitin Motiani
Google
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-10-26 16:10 Tom Lane <tgl@sss.pgh.pa.us>
parent: Nitin Motiani <nitinmotiani@google.com>
1 sibling, 1 reply; 11+ messages in thread
From: Tom Lane @ 2026-10-26 16:10 UTC (permalink / raw)
To: Nitin Motiani <nitinmotiani@google.com>; +Cc: Dilip Kumar <dilipbalaut@gmail.com>; alpkeles99@gmail.com; pgsql-bugs@lists.postgresql.org
Nitin Motiani <nitinmotiani@google.com> writes:
> Thanks for the review, Dilip. I'm attaching the v2 patch which makes
> the change in date_dist also.
I think this is not there yet. An important behavior of the
corresponding code for float8 (float_penalty_num_impl()) is that
it makes the distance between two same-sign infinity values be zero,
not infinity. This is mathematically wrong but we must do it for
indexing purposes, else inserting multiple infinities will end up
splitting each infinity onto its own index page when we want all
identical infinities to pack onto as few index pages as possible.
BTW, while checking this I happened to notice that
gbt_float8_dist has a variant of the same problem:
r = arg1 - arg2;
if (unlikely(isinf(r)) && !isinf(arg1) && !isinf(arg2))
float_overflow_error();
I don't think we want an error thrown there either;
returning the infinite distance (or DBL_MAX?) seems better.
regards, tom lane
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-10-27 03:59 Nitin Motiani <nitinmotiani@google.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 11+ messages in thread
From: Nitin Motiani @ 2026-10-27 03:59 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Dilip Kumar <dilipbalaut@gmail.com>; alpkeles99@gmail.com; pgsql-bugs@lists.postgresql.org
On Mon, Oct 26, 2026 at 9:40 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> I think this is not there yet. An important behavior of the
> corresponding code for float8 (float_penalty_num_impl()) is that
> it makes the distance between two same-sign infinity values be zero,
> not infinity. This is mathematically wrong but we must do it for
> indexing purposes, else inserting multiple infinities will end up
> splitting each infinity onto its own index page when we want all
> identical infinities to pack onto as few index pages as possible.
>
> BTW, while checking this I happened to notice that
> gbt_float8_dist has a variant of the same problem:
>
> r = arg1 - arg2;
> if (unlikely(isinf(r)) && !isinf(arg1) && !isinf(arg2))
> float_overflow_error();
>
> I don't think we want an error thrown there either;
> returning the infinite distance (or DBL_MAX?) seems better.
>
Thanks a lot for the review, Tom. I'll be able to work on this in a
couple of weeks. Will look into it in detail and send the updated
patch at that time.
Regards,
Nitin Motiani
Google
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-11-22 17:31 Nitin Motiani <nitinmotiani@google.com>
parent: Nitin Motiani <nitinmotiani@google.com>
0 siblings, 1 reply; 11+ messages in thread
From: Nitin Motiani @ 2026-11-22 17:31 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Dilip Kumar <dilipbalaut@gmail.com>; alpkeles99@gmail.com; pgsql-bugs@lists.postgresql.org
Hi Tom,
Apologies for the delay on this. I am attaching the new patches. I'm
attaching multiple patch files which can be squashed together if
needed.
On Mon, Oct 26, 2026 at 9:40 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> I think this is not there yet. An important behavior of the
> corresponding code for float8 (float_penalty_num_impl()) is that
> it makes the distance between two same-sign infinity values be zero,
> not infinity. This is mathematically wrong but we must do it for
> indexing purposes, else inserting multiple infinities will end up
> splitting each infinity onto its own index page when we want all
> identical infinities to pack onto as few index pages as possible.
>
Made the changes for the same signed infinity distances to be 0. The
penalty function was already fine so I just updated the distance
functions we were changing to handle the infinity. These are in the
0001 patch file.
> BTW, while checking this I happened to notice that
> gbt_float8_dist has a variant of the same problem:
>
> r = arg1 - arg2;
> if (unlikely(isinf(r)) && !isinf(arg1) && !isinf(arg2))
> float_overflow_error();
>
> I don't think we want an error thrown there either;
> returning the infinite distance (or DBL_MAX?) seems better.
>
Created the patch 0002 to handle this in gbt_float8_dist. I went with
returning infinity instead of DBL_MAX as that might collide with a
case where the actual distance is DBL_MAX. I considered changing
float8_dist also but its behaviour is the same as int and float4 so I
didn't change that.
I also noticed that the timestamp type has the same issue. So I added
the following to handle the overflow case.
return fabs(((float8) *aa - (float8) *bb) / USECS_PER_SEC);
I am not sure if we should just change the existing logic to use the
above in all the cases. Let me know what you think of that.
Like the date type, the distance functions for the timestamp also
return infinity for two same-signed infinities. I changed that also
but since it alters existing results, I'm unsure if it is safe to
merge. Therefore I'm sending it as a separate patch 0003. Please take
a look.
Thanks & Regards,
Nitin Motiani
Google
Attachments: download all (3 files, .tar.gz)
v3-0001-btree_gist-Fix-cannot-subtract-infinite-dates-err.patch (application/octet-stream, 9.2K) download
From 830f954e145e126f6388df95324720fcb8656045 Mon Sep 17 00:00:00 2001
From: Nitin Motiani <nitinmotiani@google.com>
Date: Fri, 16 Oct 2026 07:45:01 +0000
Subject: [PATCH v3 1/3] btree_gist: Fix "cannot subtract infinite dates"
errors.
The date opclass's penalty and distance functions used date_mi(),
which rejects infinite dates. Once a GiST index on a date column had
internal pages, inserting 'infinity' or '-infinity' failed, as did any
later insert or KNN search on an index already containing one. The
date <-> date operator failed the same way, so ORDER BY d <-> x could
succeed with a KNN index scan but fail with a sort.
Compute the penalty with penalty_num(), as the int4 and timestamp
opclasses do. In the KNN distance function and the <-> operator,
treat same-sign infinities as equal, as the float8 opclass does, and
any other infinite input as infinitely far away: return infinity from
the former and INT_MAX from the latter. No difference of two finite
dates reaches INT_MAX, so both plans order rows the same way.
Reported-by: Alperen Keles <alpkeles99@gmail.com>
Reviewed-by: Dilip Kumar <dilipbalaut@gmail.com>
Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19761-b72cfc453e487610@postgresql.org
---
contrib/btree_gist/btree_date.c | 72 +++++++++++------------
contrib/btree_gist/expected/date.out | 86 ++++++++++++++++++++++++++++
contrib/btree_gist/sql/date.sql | 25 ++++++++
3 files changed, 146 insertions(+), 37 deletions(-)
diff --git a/contrib/btree_gist/btree_date.c b/contrib/btree_gist/btree_date.c
index 1824a3d0e6e..d0b60c7a0bf 100644
--- a/contrib/btree_gist/btree_date.c
+++ b/contrib/btree_gist/btree_date.c
@@ -91,12 +91,18 @@ gbt_datekey_cmp(const void *a, const void *b, FmgrInfo *flinfo)
static float8
gdb_date_dist(const void *a, const void *b, FmgrInfo *flinfo)
{
- /* we assume the difference can't overflow */
- Datum diff = DirectFunctionCall2(date_mi,
- DateADTGetDatum(*((const DateADT *) a)),
- DateADTGetDatum(*((const DateADT *) b)));
-
- return (float8) abs(DatumGetInt32(diff));
+ DateADT da = *((const DateADT *) a);
+ DateADT db = *((const DateADT *) b);
+
+ /*
+ * Treat same-sign infinities as equal, as the float8 opclass does, and
+ * any other infinite input as infinitely far away.
+ */
+ if (DATE_NOT_FINITE(da) || DATE_NOT_FINITE(db))
+ return (da == db) ? 0.0 : get_float8_infinity();
+
+ /* the difference of two finite dates always fits in int32 */
+ return (float8) abs(da - db);
}
@@ -119,12 +125,21 @@ PG_FUNCTION_INFO_V1(date_dist);
Datum
date_dist(PG_FUNCTION_ARGS)
{
- /* we assume the difference can't overflow */
- Datum diff = DirectFunctionCall2(date_mi,
- PG_GETARG_DATUM(0),
- PG_GETARG_DATUM(1));
-
- PG_RETURN_INT32(abs(DatumGetInt32(diff)));
+ DateADT a = PG_GETARG_DATEADT(0);
+ DateADT b = PG_GETARG_DATEADT(1);
+
+ /*
+ * As in gdb_date_dist, same-sign infinities are equal. For other
+ * infinite inputs, int4 has no infinity, so saturate, as ts_dist does for
+ * timestamps. This is consistent with the ordering produced by
+ * gdb_date_dist, since no difference of two finite dates reaches
+ * PG_INT32_MAX.
+ */
+ if (DATE_NOT_FINITE(a) || DATE_NOT_FINITE(b))
+ PG_RETURN_INT32((a == b) ? 0 : PG_INT32_MAX);
+
+ /* the difference of two finite dates always fits in int32 */
+ PG_RETURN_INT32(abs(a - b));
}
@@ -206,32 +221,15 @@ gbt_date_penalty(PG_FUNCTION_ARGS)
dateKEY *origentry = (dateKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(0))->key);
dateKEY *newentry = (dateKEY *) DatumGetPointer(((GISTENTRY *) PG_GETARG_POINTER(1))->key);
float *result = (float *) PG_GETARG_POINTER(2);
- int32 diff,
- res;
-
- diff = DatumGetInt32(DirectFunctionCall2(date_mi,
- DateADTGetDatum(newentry->upper),
- DateADTGetDatum(origentry->upper)));
-
- res = Max(diff, 0);
-
- diff = DatumGetInt32(DirectFunctionCall2(date_mi,
- DateADTGetDatum(origentry->lower),
- DateADTGetDatum(newentry->lower)));
-
- res += Max(diff, 0);
-
- *result = 0.0;
- if (res > 0)
- {
- diff = DatumGetInt32(DirectFunctionCall2(date_mi,
- DateADTGetDatum(origentry->upper),
- DateADTGetDatum(origentry->lower)));
- *result += FLT_MIN;
- *result += (float) (res / ((double) (res + diff)));
- *result *= (FLT_MAX / (((GISTENTRY *) PG_GETARG_POINTER(0))->rel->rd_att->natts + 1));
- }
+ /*
+ * Don't use date_mi here: it rejects infinite dates, and plain int32
+ * subtraction could overflow for them (DATEVAL_NOBEGIN/NOEND are
+ * INT32_MIN/INT32_MAX). penalty_num computes in double, where every
+ * int32 and every difference of two int32s is exact.
+ */
+ penalty_num(result, origentry->lower, origentry->upper,
+ newentry->lower, newentry->upper);
PG_RETURN_POINTER(result);
}
diff --git a/contrib/btree_gist/expected/date.out b/contrib/btree_gist/expected/date.out
index 5db864bb82c..ed634829478 100644
--- a/contrib/btree_gist/expected/date.out
+++ b/contrib/btree_gist/expected/date.out
@@ -89,3 +89,89 @@ SELECT a, a <-> '2001-02-13' FROM datetmp ORDER BY a <-> '2001-02-13' LIMIT 3;
03-24-2001 | 39
(3 rows)
+-- infinite dates in an index with internal pages (penalty and KNN distance)
+CREATE TABLE dateinf (a date);
+CREATE INDEX dateinfidx ON dateinf USING gist ( a );
+INSERT INTO dateinf SELECT '2000-01-01'::date + i FROM generate_series(1, 1000) i;
+INSERT INTO dateinf SELECT 'infinity' FROM generate_series(1, 3);
+INSERT INTO dateinf SELECT '-infinity' FROM generate_series(1, 3);
+EXPLAIN (COSTS OFF)
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+ QUERY PLAN
+---------------------------------------------------
+ Limit
+ -> Index Only Scan using dateinfidx on dateinf
+ Order By: (a <-> '01-01-2000'::date)
+(3 rows)
+
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+ a
+------------
+ 01-02-2000
+ 01-03-2000
+ 01-04-2000
+(3 rows)
+
+SELECT a FROM dateinf ORDER BY a <-> 'infinity'::date LIMIT 3;
+ a
+----------
+ infinity
+ infinity
+ infinity
+(3 rows)
+
+SELECT a FROM dateinf ORDER BY a <-> '-infinity'::date LIMIT 3;
+ a
+-----------
+ -infinity
+ -infinity
+ -infinity
+(3 rows)
+
+-- same orderings via sort, which evaluates the <-> operator on every row
+SET enable_seqscan = on;
+SET enable_indexscan = off;
+SET enable_indexonlyscan = off;
+EXPLAIN (COSTS OFF)
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+ QUERY PLAN
+------------------------------------------------
+ Limit
+ -> Sort
+ Sort Key: ((a <-> '01-01-2000'::date))
+ -> Seq Scan on dateinf
+(4 rows)
+
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+ a
+------------
+ 01-02-2000
+ 01-03-2000
+ 01-04-2000
+(3 rows)
+
+SELECT a FROM dateinf ORDER BY a <-> 'infinity'::date LIMIT 3;
+ a
+----------
+ infinity
+ infinity
+ infinity
+(3 rows)
+
+SELECT a FROM dateinf ORDER BY a <-> '-infinity'::date LIMIT 3;
+ a
+-----------
+ -infinity
+ -infinity
+ -infinity
+(3 rows)
+
+RESET enable_indexscan;
+RESET enable_indexonlyscan;
+SELECT 'infinity'::date <-> 'infinity'::date, '-infinity'::date <-> '-infinity'::date,
+ 'infinity'::date <-> '-infinity'::date, 'infinity'::date <-> '2000-01-01'::date;
+ ?column? | ?column? | ?column? | ?column?
+----------+----------+------------+------------
+ 0 | 0 | 2147483647 | 2147483647
+(1 row)
+
diff --git a/contrib/btree_gist/sql/date.sql b/contrib/btree_gist/sql/date.sql
index f969ef0a08c..64cc588b3f6 100644
--- a/contrib/btree_gist/sql/date.sql
+++ b/contrib/btree_gist/sql/date.sql
@@ -35,3 +35,28 @@ SELECT count(*) FROM datetmp WHERE a > '2001-02-13'::date;
EXPLAIN (COSTS OFF)
SELECT a, a <-> '2001-02-13' FROM datetmp ORDER BY a <-> '2001-02-13' LIMIT 3;
SELECT a, a <-> '2001-02-13' FROM datetmp ORDER BY a <-> '2001-02-13' LIMIT 3;
+
+-- infinite dates in an index with internal pages (penalty and KNN distance)
+CREATE TABLE dateinf (a date);
+CREATE INDEX dateinfidx ON dateinf USING gist ( a );
+INSERT INTO dateinf SELECT '2000-01-01'::date + i FROM generate_series(1, 1000) i;
+INSERT INTO dateinf SELECT 'infinity' FROM generate_series(1, 3);
+INSERT INTO dateinf SELECT '-infinity' FROM generate_series(1, 3);
+EXPLAIN (COSTS OFF)
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+SELECT a FROM dateinf ORDER BY a <-> 'infinity'::date LIMIT 3;
+SELECT a FROM dateinf ORDER BY a <-> '-infinity'::date LIMIT 3;
+-- same orderings via sort, which evaluates the <-> operator on every row
+SET enable_seqscan = on;
+SET enable_indexscan = off;
+SET enable_indexonlyscan = off;
+EXPLAIN (COSTS OFF)
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+SELECT a FROM dateinf ORDER BY a <-> '2000-01-01'::date LIMIT 3;
+SELECT a FROM dateinf ORDER BY a <-> 'infinity'::date LIMIT 3;
+SELECT a FROM dateinf ORDER BY a <-> '-infinity'::date LIMIT 3;
+RESET enable_indexscan;
+RESET enable_indexonlyscan;
+SELECT 'infinity'::date <-> 'infinity'::date, '-infinity'::date <-> '-infinity'::date,
+ 'infinity'::date <-> '-infinity'::date, 'infinity'::date <-> '2000-01-01'::date;
--
v3-0003-btree_gist-Treat-same-sign-infinite-timestamps-as.patch (application/octet-stream, 5.6K) download
From 732767f95a1c177c08f4a22f75dbbc89fb6ac4be Mon Sep 17 00:00:00 2001
From: Nitin Motiani <nitinmotiani@google.com>
Date: Sat, 21 Nov 2026 13:56:53 +0000
Subject: [PATCH v3 3/3] btree_gist: Treat same-sign infinite timestamps as
zero distance apart.
gbt_ts_dist(), ts_dist() and tstz_dist() treated two equal infinities
as infinitely far apart. Treat them as equal instead, as the float8
and date opclasses do.
This changes the result of 'infinity'::timestamp <-> 'infinity'::timestamp
(and likewise for -infinity and timestamptz) from infinity to zero.
Discussion: https://postgr.es/m/19761-b72cfc453e487610@postgresql.org
---
contrib/btree_gist/btree_ts.c | 34 ++++++++++++++-------
contrib/btree_gist/expected/timestamp.out | 17 +++++++++++
contrib/btree_gist/expected/timestamptz.out | 17 +++++++++++
contrib/btree_gist/sql/timestamp.sql | 4 +++
contrib/btree_gist/sql/timestamptz.sql | 4 +++
5 files changed, 65 insertions(+), 11 deletions(-)
diff --git a/contrib/btree_gist/btree_ts.c b/contrib/btree_gist/btree_ts.c
index ad285ae4fc4..21490961862 100644
--- a/contrib/btree_gist/btree_ts.c
+++ b/contrib/btree_gist/btree_ts.c
@@ -114,8 +114,12 @@ gbt_ts_dist(const void *a, const void *b, FmgrInfo *flinfo)
Interval *i;
int64 diff;
+ /*
+ * Treat same-sign infinities as equal, as the float8 opclass does, and
+ * any other infinite input as infinitely far away.
+ */
if (TIMESTAMP_NOT_FINITE(*aa) || TIMESTAMP_NOT_FINITE(*bb))
- return get_float8_infinity();
+ return (*aa == *bb) ? 0.0 : get_float8_infinity();
/*
* Some valid timestamps are too far apart for their difference to fit in
@@ -157,11 +161,15 @@ ts_dist(PG_FUNCTION_ARGS)
if (TIMESTAMP_NOT_FINITE(a) || TIMESTAMP_NOT_FINITE(b))
{
- Interval *p = palloc_object(Interval);
-
- p->day = INT_MAX;
- p->month = INT_MAX;
- p->time = PG_INT64_MAX;
+ Interval *p = palloc0_object(Interval);
+
+ /* same-sign infinities are equal, as in gbt_ts_dist */
+ if (a != b)
+ {
+ p->day = INT_MAX;
+ p->month = INT_MAX;
+ p->time = PG_INT64_MAX;
+ }
PG_RETURN_INTERVAL_P(p);
}
else
@@ -181,11 +189,15 @@ tstz_dist(PG_FUNCTION_ARGS)
if (TIMESTAMP_NOT_FINITE(a) || TIMESTAMP_NOT_FINITE(b))
{
- Interval *p = palloc_object(Interval);
-
- p->day = INT_MAX;
- p->month = INT_MAX;
- p->time = PG_INT64_MAX;
+ Interval *p = palloc0_object(Interval);
+
+ /* same-sign infinities are equal, as in gbt_ts_dist */
+ if (a != b)
+ {
+ p->day = INT_MAX;
+ p->month = INT_MAX;
+ p->time = PG_INT64_MAX;
+ }
PG_RETURN_INTERVAL_P(p);
}
diff --git a/contrib/btree_gist/expected/timestamp.out b/contrib/btree_gist/expected/timestamp.out
index d24062ea9d0..833e4e54bee 100644
--- a/contrib/btree_gist/expected/timestamp.out
+++ b/contrib/btree_gist/expected/timestamp.out
@@ -108,3 +108,20 @@ SELECT a FROM timestampfar ORDER BY a <-> '294276-12-31 23:59:59' LIMIT 1;
Sun Dec 31 23:59:59 294276
(1 row)
+-- same-sign infinities are zero distance apart
+SELECT a, a <-> 'infinity' FROM timestamptmp ORDER BY a <-> 'infinity' LIMIT 3;
+ a | ?column?
+----------+----------
+ infinity | @ 0
+ infinity | @ 0
+ infinity | @ 0
+(3 rows)
+
+SELECT a, a <-> '-infinity' FROM timestamptmp ORDER BY a <-> '-infinity' LIMIT 3;
+ a | ?column?
+-----------+----------
+ -infinity | @ 0
+ -infinity | @ 0
+ -infinity | @ 0
+(3 rows)
+
diff --git a/contrib/btree_gist/expected/timestamptz.out b/contrib/btree_gist/expected/timestamptz.out
index 75a15a42568..5ade8c70fbf 100644
--- a/contrib/btree_gist/expected/timestamptz.out
+++ b/contrib/btree_gist/expected/timestamptz.out
@@ -209,3 +209,20 @@ SELECT a, a <-> '2018-12-18 10:59:54 GMT+2' FROM timestamptztmp ORDER BY a <-> '
Thu Jan 24 12:28:12 2019 PST | @ 37 days 7 hours 28 mins 18 secs
(3 rows)
+-- same-sign infinities are zero distance apart
+SELECT a, a <-> 'infinity' FROM timestamptztmp ORDER BY a <-> 'infinity' LIMIT 3;
+ a | ?column?
+----------+----------
+ infinity | @ 0
+ infinity | @ 0
+ infinity | @ 0
+(3 rows)
+
+SELECT a, a <-> '-infinity' FROM timestamptztmp ORDER BY a <-> '-infinity' LIMIT 3;
+ a | ?column?
+-----------+----------
+ -infinity | @ 0
+ -infinity | @ 0
+ -infinity | @ 0
+(3 rows)
+
diff --git a/contrib/btree_gist/sql/timestamp.sql b/contrib/btree_gist/sql/timestamp.sql
index f0ffd2531fc..09c60a066ed 100644
--- a/contrib/btree_gist/sql/timestamp.sql
+++ b/contrib/btree_gist/sql/timestamp.sql
@@ -43,3 +43,7 @@ INSERT INTO timestampfar VALUES ('4714-11-24 00:00:00 BC'), ('294276-12-31 23:59
EXPLAIN (COSTS OFF)
SELECT a FROM timestampfar ORDER BY a <-> '294276-12-31 23:59:59' LIMIT 1;
SELECT a FROM timestampfar ORDER BY a <-> '294276-12-31 23:59:59' LIMIT 1;
+
+-- same-sign infinities are zero distance apart
+SELECT a, a <-> 'infinity' FROM timestamptmp ORDER BY a <-> 'infinity' LIMIT 3;
+SELECT a, a <-> '-infinity' FROM timestamptmp ORDER BY a <-> '-infinity' LIMIT 3;
diff --git a/contrib/btree_gist/sql/timestamptz.sql b/contrib/btree_gist/sql/timestamptz.sql
index f70caa4a649..9af0cd23261 100644
--- a/contrib/btree_gist/sql/timestamptz.sql
+++ b/contrib/btree_gist/sql/timestamptz.sql
@@ -78,3 +78,7 @@ SELECT count(*) FROM timestamptztmp WHERE a > '2018-12-18 10:59:54 GMT+4'::time
EXPLAIN (COSTS OFF)
SELECT a, a <-> '2018-12-18 10:59:54 GMT+2' FROM timestamptztmp ORDER BY a <-> '2018-12-18 10:59:54 GMT+2' LIMIT 3;
SELECT a, a <-> '2018-12-18 10:59:54 GMT+2' FROM timestamptztmp ORDER BY a <-> '2018-12-18 10:59:54 GMT+2' LIMIT 3;
+
+-- same-sign infinities are zero distance apart
+SELECT a, a <-> 'infinity' FROM timestamptztmp ORDER BY a <-> 'infinity' LIMIT 3;
+SELECT a, a <-> '-infinity' FROM timestamptztmp ORDER BY a <-> '-infinity' LIMIT 3;
--
v3-0002-btree_gist-Don-t-throw-overflow-errors-from-KNN-d.patch (application/octet-stream, 7.3K) download
From cc2198b01d3f5df85828290c87a58069491f5edb Mon Sep 17 00:00:00 2001
From: Nitin Motiani <nitinmotiani@google.com>
Date: Sat, 21 Nov 2026 13:54:37 +0000
Subject: [PATCH v3 2/3] btree_gist: Don't throw overflow errors from KNN
distance functions.
gbt_float8_dist() raised an error when the difference of two finite
values overflowed, and gbt_ts_dist() did the same via timestamp_mi()
for valid timestamps too far apart for their difference to fit in an
interval. A KNN search computes these distances for every index entry
it visits, not just the ones it returns, so a single extreme value in
the index could make such searches fail.
In gbt_float8_dist(), return the infinite distance that the IEEE
subtraction already produces. In gbt_ts_dist(), compute the distance
in double when the int64 difference overflows. The <-> operators
themselves still report overflow, as they do for the integer and
float4 opclasses.
Reported-by: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/19761-b72cfc453e487610@postgresql.org
---
contrib/btree_gist/btree_float8.c | 7 +++++--
contrib/btree_gist/btree_ts.c | 11 +++++++++++
contrib/btree_gist/expected/float8.out | 21 +++++++++++++++++++++
contrib/btree_gist/expected/timestamp.out | 19 +++++++++++++++++++
contrib/btree_gist/sql/float8.sql | 10 ++++++++++
contrib/btree_gist/sql/timestamp.sql | 8 ++++++++
6 files changed, 74 insertions(+), 2 deletions(-)
diff --git a/contrib/btree_gist/btree_float8.c b/contrib/btree_gist/btree_float8.c
index 478324ce4f3..d5c2395e15b 100644
--- a/contrib/btree_gist/btree_float8.c
+++ b/contrib/btree_gist/btree_float8.c
@@ -79,9 +79,12 @@ gbt_float8_dist(const void *a, const void *b, FmgrInfo *flinfo)
float8 arg2 = *(const float8 *) b;
float8 r;
+ /*
+ * If the difference of two finite values overflows, this yields an
+ * infinite distance. Don't throw an error: KNN searches compute
+ * distances for index entries they merely visit.
+ */
r = arg1 - arg2;
- if (unlikely(isinf(r)) && !isinf(arg1) && !isinf(arg2))
- float_overflow_error();
if (unlikely(isnan(r)))
{
if (isnan(arg1) && isnan(arg2))
diff --git a/contrib/btree_gist/btree_ts.c b/contrib/btree_gist/btree_ts.c
index 53d63e5c852..ad285ae4fc4 100644
--- a/contrib/btree_gist/btree_ts.c
+++ b/contrib/btree_gist/btree_ts.c
@@ -7,6 +7,7 @@
#include "btree_gist.h"
#include "btree_utils_num.h"
+#include "common/int.h"
#include "utils/fmgrprotos.h"
#include "utils/timestamp.h"
#include "utils/float.h"
@@ -111,10 +112,20 @@ gbt_ts_dist(const void *a, const void *b, FmgrInfo *flinfo)
const Timestamp *aa = (const Timestamp *) a;
const Timestamp *bb = (const Timestamp *) b;
Interval *i;
+ int64 diff;
if (TIMESTAMP_NOT_FINITE(*aa) || TIMESTAMP_NOT_FINITE(*bb))
return get_float8_infinity();
+ /*
+ * Some valid timestamps are too far apart for their difference to fit in
+ * an interval. Don't throw an error for those, since KNN searches
+ * compute distances for index entries they merely visit; compute the
+ * distance in double instead.
+ */
+ if (pg_sub_s64_overflow(*aa, *bb, &diff))
+ return fabs(((float8) *aa - (float8) *bb) / USECS_PER_SEC);
+
i = DatumGetIntervalP(DirectFunctionCall2(timestamp_mi,
TimestampGetDatum(*aa),
TimestampGetDatum(*bb)));
diff --git a/contrib/btree_gist/expected/float8.out b/contrib/btree_gist/expected/float8.out
index 194bd210ac6..3ad6c594132 100644
--- a/contrib/btree_gist/expected/float8.out
+++ b/contrib/btree_gist/expected/float8.out
@@ -124,3 +124,24 @@ SELECT count(*) FROM float8tmp WHERE abs(a) = 1890.0::float8;
RESET enable_seqscan;
RESET enable_indexscan;
RESET enable_bitmapscan;
+-- finite values whose difference overflows float8 (KNN distance must not error)
+CREATE TABLE float8far (a float8);
+CREATE INDEX float8faridx ON float8far USING gist ( a );
+INSERT INTO float8far VALUES (1e308), (-1e308);
+SET enable_seqscan = off;
+EXPLAIN (COSTS OFF)
+SELECT a FROM float8far ORDER BY a <-> 1e308::float8 LIMIT 1;
+ QUERY PLAN
+-------------------------------------------------------
+ Limit
+ -> Index Only Scan using float8faridx on float8far
+ Order By: (a <-> '1e+308'::double precision)
+(3 rows)
+
+SELECT a FROM float8far ORDER BY a <-> 1e308::float8 LIMIT 1;
+ a
+--------
+ 1e+308
+(1 row)
+
+RESET enable_seqscan;
diff --git a/contrib/btree_gist/expected/timestamp.out b/contrib/btree_gist/expected/timestamp.out
index 0d94f2f245c..d24062ea9d0 100644
--- a/contrib/btree_gist/expected/timestamp.out
+++ b/contrib/btree_gist/expected/timestamp.out
@@ -89,3 +89,22 @@ SELECT a, a <-> '2004-10-26 08:55:08' FROM timestamptmp ORDER BY a <-> '2004-10-
Mon Nov 29 20:12:43 2004 | @ 34 days 11 hours 17 mins 35 secs
(3 rows)
+-- finite timestamps too far apart to subtract (KNN distance must not error)
+CREATE TABLE timestampfar (a timestamp);
+CREATE INDEX timestampfaridx ON timestampfar USING gist ( a );
+INSERT INTO timestampfar VALUES ('4714-11-24 00:00:00 BC'), ('294276-12-31 23:59:59');
+EXPLAIN (COSTS OFF)
+SELECT a FROM timestampfar ORDER BY a <-> '294276-12-31 23:59:59' LIMIT 1;
+ QUERY PLAN
+-------------------------------------------------------------------------------------
+ Limit
+ -> Index Only Scan using timestampfaridx on timestampfar
+ Order By: (a <-> 'Sun Dec 31 23:59:59 294276'::timestamp without time zone)
+(3 rows)
+
+SELECT a FROM timestampfar ORDER BY a <-> '294276-12-31 23:59:59' LIMIT 1;
+ a
+----------------------------
+ Sun Dec 31 23:59:59 294276
+(1 row)
+
diff --git a/contrib/btree_gist/sql/float8.sql b/contrib/btree_gist/sql/float8.sql
index a0fc84f94bb..1b30a1c5904 100644
--- a/contrib/btree_gist/sql/float8.sql
+++ b/contrib/btree_gist/sql/float8.sql
@@ -52,3 +52,13 @@ SELECT count(*) FROM float8tmp WHERE abs(a) = 1890.0::float8;
RESET enable_seqscan;
RESET enable_indexscan;
RESET enable_bitmapscan;
+
+-- finite values whose difference overflows float8 (KNN distance must not error)
+CREATE TABLE float8far (a float8);
+CREATE INDEX float8faridx ON float8far USING gist ( a );
+INSERT INTO float8far VALUES (1e308), (-1e308);
+SET enable_seqscan = off;
+EXPLAIN (COSTS OFF)
+SELECT a FROM float8far ORDER BY a <-> 1e308::float8 LIMIT 1;
+SELECT a FROM float8far ORDER BY a <-> 1e308::float8 LIMIT 1;
+RESET enable_seqscan;
diff --git a/contrib/btree_gist/sql/timestamp.sql b/contrib/btree_gist/sql/timestamp.sql
index 95effebfc47..f0ffd2531fc 100644
--- a/contrib/btree_gist/sql/timestamp.sql
+++ b/contrib/btree_gist/sql/timestamp.sql
@@ -35,3 +35,11 @@ SELECT count(*) FROM timestamptmp WHERE a > '2004-10-26 08:55:08'::timestamp;
EXPLAIN (COSTS OFF)
SELECT a, a <-> '2004-10-26 08:55:08' FROM timestamptmp ORDER BY a <-> '2004-10-26 08:55:08' LIMIT 3;
SELECT a, a <-> '2004-10-26 08:55:08' FROM timestamptmp ORDER BY a <-> '2004-10-26 08:55:08' LIMIT 3;
+
+-- finite timestamps too far apart to subtract (KNN distance must not error)
+CREATE TABLE timestampfar (a timestamp);
+CREATE INDEX timestampfaridx ON timestampfar USING gist ( a );
+INSERT INTO timestampfar VALUES ('4714-11-24 00:00:00 BC'), ('294276-12-31 23:59:59');
+EXPLAIN (COSTS OFF)
+SELECT a FROM timestampfar ORDER BY a <-> '294276-12-31 23:59:59' LIMIT 1;
+SELECT a FROM timestampfar ORDER BY a <-> '294276-12-31 23:59:59' LIMIT 1;
--
^ permalink raw reply [nested|flat] 11+ messages in thread
* Re: BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date
@ 2026-11-23 22:56 Tom Lane <tgl@sss.pgh.pa.us>
parent: Nitin Motiani <nitinmotiani@google.com>
0 siblings, 0 replies; 11+ messages in thread
From: Tom Lane @ 2026-11-23 22:56 UTC (permalink / raw)
To: Nitin Motiani <nitinmotiani@google.com>; +Cc: Dilip Kumar <dilipbalaut@gmail.com>; alpkeles99@gmail.com; pgsql-bugs@lists.postgresql.org
Nitin Motiani <nitinmotiani@google.com> writes:
> Apologies for the delay on this. I am attaching the new patches. I'm
> attaching multiple patch files which can be squashed together if
> needed.
Pushed with minor cosmetic adjustments.
> Like the date type, the distance functions for the timestamp also
> return infinity for two same-signed infinities. I changed that also
> but since it alters existing results, I'm unsure if it is safe to
> merge. Therefore I'm sending it as a separate patch 0003. Please take
> a look.
Yeah, I included this. It seems a trifle unlikely that anyone is
storing infinities in btree_gist indexes today, else we'd have heard
complaints before. So keeping the behavior for different datatypes'
infinities in sync seems like a more attractive choice.
regards, tom lane
^ permalink raw reply [nested|flat] 11+ messages in thread
end of thread, other threads:[~2026-11-23 22:56 UTC | newest]
Thread overview: 11+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-10-15 14:09 BUG #19761: btree_gist: "cannot subtract infinite dates" when inserting 'infinity' into a GiST index on date PG Bug reporting form <noreply@postgresql.org>
2026-10-16 09:15 ` Nitin Motiani <nitinmotiani@google.com>
2026-10-23 07:04 ` Dilip Kumar <dilipbalaut@gmail.com>
2026-10-23 13:14 ` Nitin Motiani <nitinmotiani@google.com>
2026-10-25 06:20 ` Dilip Kumar <dilipbalaut@gmail.com>
2026-10-25 11:35 ` Nitin Motiani <nitinmotiani@google.com>
2026-10-26 11:21 ` Nitin Motiani <nitinmotiani@google.com>
2026-10-26 16:10 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-10-27 03:59 ` Nitin Motiani <nitinmotiani@google.com>
2026-11-22 17:31 ` Nitin Motiani <nitinmotiani@google.com>
2026-11-23 22:56 ` Tom Lane <tgl@sss.pgh.pa.us>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox