Skip to content

Commit b26d8fd

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 e73bd1e commit b26d8fd

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
@@ -374,6 +374,8 @@ my_decompress(PG_FUNCTION_ARGS)
374374
Returns a value indicating the <quote>cost</quote> of inserting the new
375375
entry into a particular branch of the tree. Items will be inserted
376376
down the path of least <function>penalty</function> in the tree.
377+
Values returned by <function>penalty</function> should be non-negative.
378+
If a negative value is returned, it will be treated as zero.
377379
</para>
378380

379381
<para>

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/reloptions.h"
1820
#include "storage/freespace.h"
@@ -532,16 +534,22 @@ gistpenalty(GISTSTATE *giststate, int attno,
532534
{
533535
float penalty = 0.0;
534536

535-
if (giststate->penaltyFn[attno].fn_strict == FALSE || (isNullOrig == FALSE && isNullAdd == FALSE))
537+
if (giststate->penaltyFn[attno].fn_strict == FALSE ||
538+
(isNullOrig == FALSE && isNullAdd == FALSE))
539+
{
536540
FunctionCall3(&giststate->penaltyFn[attno],
537541
PointerGetDatum(orig),
538542
PointerGetDatum(add),
539543
PointerGetDatum(&penalty));
544+
/* disallow negative or NaN penalty */
545+
if (isnan(penalty) || penalty < 0.0)
546+
penalty = 0.0;
547+
}
540548
else if (isNullOrig && isNullAdd)
541549
penalty = 0.0;
542550
else
543-
penalty = 1e10; /* try to prevent to mix null and non-null
544-
* value */
551+
penalty = 1e10; /* try to prevent mixing null and non-null
552+
* values */
545553

546554
return penalty;
547555
}

0 commit comments

Comments
 (0)