From: cuishuang (@cuishuang) <noreply+cuishuang@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] PR #1023: Fix zero random value when choosing HNSW level
Date: Mon, 07 Sep 2026 12:10:49 +0000
Message-ID: <gh-pgvector-pgvector-1023@github.com> (raw)
`HnswInitElement()` currently chooses the HNSW level with:
```c
int level = (int) (-log(RandomDouble()) * ml);
```
`RandomDouble()` can return zero on supported PostgreSQL versions:
- PostgreSQL 15+: `pg_prng_double(&pg_global_prng_state)` returns values in `[0, 1)`.
- PostgreSQL 13/14: `random() / MAX_RANDOM_VALUE` can produce zero.
When this happens, the calculation becomes:
```text
log(0) -> -Infinity
-log(0) -> +Infinity
(int) +Inf -> implementation-defined / non-portable result
```
The resulting level may then be converted to `uint8`, so this is a correctness and portability issue.
Retry the random-number generation when it returns exactly zero before calling `log()`:
```c
do
uniform = RandomDouble();
while (uniform == 0.0);
```
This preserves the existing distribution and PostgreSQL 13/14 endpoint behavior. In particular, it avoids using `1.0 - RandomDouble()`, which would change the distribution and endpoint semantics.
inline patch 1: src/hnswutils.c (+9/-1 lines) download inline-1.patchdiff --git a/src/hnswutils.c b/src/hnswutils.cindex c4372b143..929465cc6 100644--- a/src/hnswutils.c+++ b/src/hnswutils.c@@ -246,7 +246,15 @@ HnswInitElement(char *base, ItemPointer heaptid, int m, double ml, int maxLevel,
{
HnswElement element = HnswAlloc(allocator, sizeof(HnswElementData));
- int level = (int) (-log(RandomDouble()) * ml);+ double uniform;+ int level;++ /* RandomDouble() can return zero on supported PostgreSQL versions. */+ do+ uniform = RandomDouble();+ while (uniform == 0.0);++ level = (int) (-log(uniform) * ml);
/* Cap level */
if (level > maxLevel)