On Thu, Dec 3, 2026 at 5:32 PM Greg Burd <[email protected]> wrote: Hi all,
v2 attached. v1 had a bug in the index support functions, and fixing it properly needed a change in design. An ordering GiST or SP-GiST scan uses the distance in two ways. For a key that is the indexed value, such as a box_ops leaf, the distance is the row's, and it must equal the operator's result, or the index and a seq scan disagree. For a key that only bounds the values below it, an internal key or a polygon's bounding box, the distance needs to be a lower bound, nothing more; the scan visits keys in that order, so a bound that is too high returns rows late. NaN is never a lower bound: it sorts after every number. Master breaks both rules. The operator's edge projection returns whatever the NaN comparisons happen to produce, and GiST's computeDistance() raises "inconsistent point values" (or fails an assertion) on a key that holds a NaN, which one NaN row anywhere in the subtree is enough to cause; that is bug #19937 [1]. v1 used one function for both roles, returning NaN for any NaN coordinate. That fixed the operator but broke the bound: with one '(1,NaN)' inserted after building a GiST index on a 45x45 grid of points, the scan for the nearest point to (0.5,0.5) returned (0,8) at 7.52 first, and (0,0) at 0.71 only 1930th. The query is in info.txt. v2 gives each role its own function. point_box_distance() is the operator, and box_ops leaves use it, so the index returns exactly the operator's number, NaN included. point_box_distance_bound() is for keys that bound other values: the same distance, or 0 when the key or the point has a NaN. 0 is always a lower bound, and a key with a NaN says nothing tighter about the rows below it. No row is ever reported with that 0, so the operator and the index cannot disagree. CF 7370 uses the same 0 for GiST's NaN keys [2]; v2 applies it to SP-GiST too, and I'll reply on that thread about how the two fit together. One user-visible change: <-> between a point and a box with a NaN is now NaN, as <-> between points already is. Master gives 0.5 for (0.5,0.5) and ((0,0),(1,NaN)). I compared index scans with seq scans for every GiST and SP-GiST opclass that orders by distance to a point, with NaN and infinite rows in several positions. Master has 141 failures, 38 of them crashes, v1 162, v2 4; the 4 come from point_inside() and fail the same way on master. Details are in the attached info.txt. > SP-GiST's version now errors on overflow, as GiST's and the operator > always did, and returns NaN when any coordinate is NaN. With v2, the second half holds for box_ops leaves only; internal keys get the 0 bound. v2 is rebased onto 76ac7f718d8. best. -greg [1] https://postgr.es/m/[email protected] [2] https://postgr.es/m/[email protected]
v2-0001-Compute-the-distance-between-a-point-and-a-box-ex.patch
Description: Binary data
info.txt
Description: Binary data
