diff --git a/contrib/btree_gist/btree_interval.c b/contrib/btree_gist/btree_interval.c
index b51b2946367..47a4345331f 100644
--- a/contrib/btree_gist/btree_interval.c
+++ b/contrib/btree_gist/btree_interval.c
@@ -6,6 +6,7 @@
 #include "btree_gist.h"
 #include "btree_utils_num.h"
 #include "common/int.h"
+#include "common/int128.h"
 #include "utils/fmgrprotos.h"
 #include "utils/rel.h"
 #include "utils/sortsupport.h"
@@ -78,13 +79,25 @@ gbt_intvkey_cmp(const void *a, const void *b, FmgrInfo *flinfo)
 static double
 intr2num(const Interval *i)
 {
-	return INTERVAL_TO_SEC(i);
+	if (INTERVAL_IS_NOEND(i))
+		return get_float8_infinity();
+	else if (INTERVAL_IS_NOBEGIN(i))
+		return -get_float8_infinity();
+	else
+		return INTERVAL_TO_SEC(i);
 }
 
 static float8
 gbt_intv_dist(const void *a, const void *b, FmgrInfo *flinfo)
 {
-	return fabs(intr2num((const Interval *) a) - intr2num((const Interval *) b));
+	double		da = intr2num((const Interval *) a);
+	double		db = intr2num((const Interval *) b);
+
+	/* Inf - Inf would yield NaN, but we want to return zero instead */
+	if (da == db)
+		return 0.0;
+	else
+		return fabs(da - db);
 }
 
 /*
@@ -167,14 +180,86 @@ interval_dist(PG_FUNCTION_ARGS)
 	}
 
 	/*
-	 * Do what interval_mi() would do, except report interval +Infinity rather
-	 * than throwing an out-of-range error.
+	 * Do what interval_mi() would do, unless that results in a field
+	 * overflow.  We must not throw an out-of-range error here.
 	 */
 	if (pg_sub_s32_overflow(a->month, b->month, &result->month) ||
 		pg_sub_s32_overflow(a->day, b->day, &result->day) ||
 		pg_sub_s64_overflow(a->time, b->time, &result->time) ||
 		INTERVAL_NOT_FINITE(result))
-		INTERVAL_NOEND(result);
+	{
+		/*
+		 * A field overflowed, but we may be able to represent the difference
+		 * in an alternate fashion.  Compute the difference in the linear form
+		 * that interval comparison uses (a month is 30 days, a day is 24
+		 * hours).  Then try to convert back to some valid interval
+		 * representation.  Return +Infinity only if there is no valid
+		 * equivalent interval.
+		 */
+		INT128		span = int64_to_int128(a->time);
+		int32		usecs;
+		int32		secs;
+		int32		days;
+		int64		months;
+
+		int128_add_int64_mul_int64(&span,
+								   a->month * INT64CONST(30) + a->day,
+								   USECS_PER_DAY);
+		int128_sub_int64(&span, b->time);
+		int128_sub_int64_mul_int64(&span,
+								   b->month * INT64CONST(30) + b->day,
+								   USECS_PER_DAY);
+		/* span cannot be negative now, since we forced a >= b */
+		int128_div_mod_int32(&span, USECS_PER_SEC, &usecs);
+		int128_div_mod_int32(&span, SECS_PER_DAY, &secs);
+		int128_div_mod_int32(&span, DAYS_PER_MONTH, &days);
+
+		/*
+		 * span is now in months, and could be large, but days, secs, and
+		 * usecs are all bounded to typical ranges.  Fill the month field
+		 * first and let any excess spill into the day and then the time
+		 * field, so that we return +Infinity only for a span beyond every
+		 * finite interval.
+		 */
+		months = int128_to_int64(span);
+		if (months <= PG_INT32_MAX)
+		{
+			result->month = (int32) months;
+			result->day = days;
+			result->time = secs * USECS_PER_SEC + usecs;
+		}
+		else
+		{
+			int64		xdays;
+			int64		xtime;
+
+			result->month = PG_INT32_MAX;
+			xdays = (months - PG_INT32_MAX) * DAYS_PER_MONTH + days;
+			if (xdays <= PG_INT32_MAX)
+			{
+				result->day = (int32) xdays;
+				result->time = secs * USECS_PER_SEC + usecs;
+			}
+			else if (pg_mul_s64_overflow(xdays - PG_INT32_MAX, USECS_PER_DAY,
+										 &xtime) ||
+					 pg_add_s64_overflow(xtime, secs * USECS_PER_SEC + usecs,
+										 &xtime))
+			{
+				/* The difference can't fit, must report +Infinity */
+				INTERVAL_NOEND(result);
+			}
+			else
+			{
+				/*
+				 * In the edge case where xtime comes out as exactly
+				 * PG_INT64_MAX, we'll be setting result to +Infinity here,
+				 * but that's fine.  There are no larger finite intervals.
+				 */
+				result->day = PG_INT32_MAX;
+				result->time = xtime;
+			}
+		}
+	}
 
 	PG_RETURN_INTERVAL_P(result);
 }
@@ -317,7 +402,7 @@ gbt_intv_penalty(PG_FUNCTION_ARGS)
 	inew[0] = intr2num(&newentry->lower);
 	inew[1] = intr2num(&newentry->upper);
 
-	penalty_num(result, iorg[0], iorg[1], inew[0], inew[1]);
+	float_penalty_num(result, iorg[0], iorg[1], inew[0], inew[1]);
 
 	PG_RETURN_POINTER(result);
 }
diff --git a/contrib/btree_gist/btree_utils_num.h b/contrib/btree_gist/btree_utils_num.h
index 52f531f70e4..c427f2bf68d 100644
--- a/contrib/btree_gist/btree_utils_num.h
+++ b/contrib/btree_gist/btree_utils_num.h
@@ -184,6 +184,7 @@ float_penalty_num_impl(double olower, double oupper,
  * Convert an Interval to an approximate equivalent number of seconds
  * (as a double).  Here because we need it for time/timetz as well as
  * interval.  See interval_cmp_internal for comparison.
+ * Caution: don't use this if the interval could be +-Infinity.
  */
 #define INTERVAL_TO_SEC(ivp) \
 	(((double) (ivp)->time) / ((double) USECS_PER_SEC) + \
diff --git a/contrib/btree_gist/expected/interval.out b/contrib/btree_gist/expected/interval.out
index bb105abf239..b7fc338bda3 100644
--- a/contrib/btree_gist/expected/interval.out
+++ b/contrib/btree_gist/expected/interval.out
@@ -124,8 +124,48 @@ SELECT '178000000 years'::interval <-> '-178000000 years'::interval AS sub_overf
 (1 row)
 
 SELECT '-178956970 years -7 months'::interval <-> '1 mon'::interval AS negate_overflow;
- negate_overflow 
------------------
- infinity
+         negate_overflow          
+----------------------------------
+ @ 178956970 years 7 mons 30 days
+(1 row)
+
+SELECT make_interval(days => 178956971, hours => -2147483647) <-> make_interval(hours => 2147483647) AS fields_cancel;
+ fields_cancel 
+---------------
+ @ 10 hours
 (1 row)
 
+SELECT make_interval(hours => -2147483647) <-> make_interval(hours => 2147483647) AS time_overflow;
+             time_overflow              
+----------------------------------------
+ @ 497102 years 8 mons 10 days 14 hours
+(1 row)
+
+SELECT (make_interval(months => -2147483648) <-> '0') <
+       (make_interval(months => -2147483647, days => -2147483647) <-> '0') AS monotonic;
+ monotonic 
+-----------
+ t
+(1 row)
+
+-- KNN order must agree with the <-> operator
+CREATE TABLE intervalknn (a interval);
+INSERT INTO intervalknn VALUES ('-infinity'), ('0'),
+  (make_interval(days => 178956971, hours => -2147483647));
+CREATE INDEX intervalknnidx ON intervalknn USING gist (a);
+SELECT a, a <-> '-178000000 years' FROM intervalknn ORDER BY a <-> '-178000000 years';
+                 a                  |                      ?column?                      
+------------------------------------+----------------------------------------------------
+ @ 0                                | @ 178000000 years
+ @ 178956971 days -2147483647 hours | @ 178000000 years 178956971 days -2147483647 hours
+ -infinity                          | infinity
+(3 rows)
+
+SELECT a, a <-> make_interval(hours => 2147483647) FROM intervalknn ORDER BY a <-> make_interval(hours => 2147483647);
+                 a                  |      ?column?      
+------------------------------------+--------------------
+ @ 178956971 days -2147483647 hours | @ 10 hours
+ @ 0                                | @ 2147483647 hours
+ -infinity                          | infinity
+(3 rows)
+
diff --git a/contrib/btree_gist/sql/interval.sql b/contrib/btree_gist/sql/interval.sql
index 5ceedd2ee1c..19991f9ab95 100644
--- a/contrib/btree_gist/sql/interval.sql
+++ b/contrib/btree_gist/sql/interval.sql
@@ -49,3 +49,15 @@ SELECT 'infinity'::interval <-> 'infinity'::interval AS same_pos,
        '1 day'::interval <-> 'infinity'::interval AS finite_inf;
 SELECT '178000000 years'::interval <-> '-178000000 years'::interval AS sub_overflow;
 SELECT '-178956970 years -7 months'::interval <-> '1 mon'::interval AS negate_overflow;
+SELECT make_interval(days => 178956971, hours => -2147483647) <-> make_interval(hours => 2147483647) AS fields_cancel;
+SELECT make_interval(hours => -2147483647) <-> make_interval(hours => 2147483647) AS time_overflow;
+SELECT (make_interval(months => -2147483648) <-> '0') <
+       (make_interval(months => -2147483647, days => -2147483647) <-> '0') AS monotonic;
+
+-- KNN order must agree with the <-> operator
+CREATE TABLE intervalknn (a interval);
+INSERT INTO intervalknn VALUES ('-infinity'), ('0'),
+  (make_interval(days => 178956971, hours => -2147483647));
+CREATE INDEX intervalknnidx ON intervalknn USING gist (a);
+SELECT a, a <-> '-178000000 years' FROM intervalknn ORDER BY a <-> '-178000000 years';
+SELECT a, a <-> make_interval(hours => 2147483647) FROM intervalknn ORDER BY a <-> make_interval(hours => 2147483647);
