Skip to content

Commit ca76a39

Browse files
committed
Protect GIST logic that assumes penalty values can't be negative.
Apparently sane-looking penalty code might return small negative values, for example because of roundoff error. This will confuse places like gistchoose(). Prevent problems by clamping negative penalty values to zero. (Just to be really sure, I also made it force NaNs to zero.) Back-patch to all supported branches. Alexander Korotkov
1 parent 1d6dd87 commit ca76a39

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

doc/src/sgml/gist.sgml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,8 @@
147147
Returns a value indicating the <quote>cost</quote> of inserting the new
148148
entry into a particular branch of the tree. items will be inserted
149149
down the path of least <function>penalty</function> in the tree.
150+
Values returned by <function>penalty</function> should be non-negative.
151+
If a negative value is returned, it will be treated as zero.
150152
</para>
151153
</listitem>
152154
</varlistentry>

src/backend/access/gist/gistutil.c

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
*/
1414
#include "postgres.h"
1515

16+
#include <math.h>
17+
1618
#include "access/gist_private.h"
1719
#include "access/heapam.h"
1820
#include "access/reloptions.h"
@@ -530,16 +532,22 @@ gistpenalty(GISTSTATE *giststate, int attno,
530532
{
531533
float penalty = 0.0;
532534

533-
if (giststate->penaltyFn[attno].fn_strict == FALSE || (isNullOrig == FALSE && isNullAdd == FALSE))
535+
if (giststate->penaltyFn[attno].fn_strict == FALSE ||
536+
(isNullOrig == FALSE && isNullAdd == FALSE))
537+
{
534538
FunctionCall3(&giststate->penaltyFn[attno],
535539
PointerGetDatum(orig),
536540
PointerGetDatum(add),
537541
PointerGetDatum(&penalty));
542+
/* disallow negative or NaN penalty */
543+
if (isnan(penalty) || penalty < 0.0)
544+
penalty = 0.0;
545+
}
538546
else if (isNullOrig && isNullAdd)
539547
penalty = 0.0;
540548
else
541-
penalty = 1e10; /* try to prevent to mix null and non-null
542-
* value */
549+
penalty = 1e10; /* try to prevent mixing null and non-null
550+
* values */
543551

544552
return penalty;
545553
}

0 commit comments

Comments
 (0)