From: upenderbh (@upenderbh) <noreply+upenderbh@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] PR #1010: Fix duplicate neighbors race between HNSW INSERT and VACUUM
Date: Tue, 04 Aug 2026 10:40:56 +0000
Message-ID: <gh-pgvector-pgvector-1010@github.com> (raw)
## Summary
Under high concurrent `INSERT` and `VACUUM` workloads, HNSW indexes can become physically corrupted on disk by accumulating duplicate neighbor connections in node adjacency lists.
The corruption happens when a concurrent `INSERT` publishes its initial bridge edge (`i=0`) on disk, making the new element immediately discoverable to a concurrent `VACUUM` Phase 2 process (`RepairGraph`). `VACUUM` discovers the new element while repairing adjacent nodes and inserts it into their neighbor arrays, checking for existing connections. When `INSERT` resumes to update its remaining candidate connections (`i=1`), it executes blind writes without checking, unaware that `VACUUM` has already added the element. This writes the new element a second time into the same neighbor arrays.
While PostgreSQL's query executor deduplicates final SQL query results via a visited hash set (`tidhash_insert` in `HnswSearchLayer`), duplicate neighbors cause permanent structural graph corruption by:
* Wasting fixed node out-degree capacity (`M` or `2M`)
* Blocking valid navigation paths
* Degrading ANN search recall accuracy
## Reproduction
This race condition can be reliably and deterministically reproduced using a dual-GDB lockstep script that pauses the `INSERT` worker immediately after writing its first bridge edge while allowing `VACUUM` Phase 2 to run.
* [Reproduction Script](https://gist.github.com/upenderbh/ae58353cd0c2debb38c169c913aae3b9)
It can also be reproduced organically under heavy concurrent `INSERT` and `VACUUM` workloads.
## Root Cause
The corruption occurs in three steps:
1. **`INSERT` Bridge Edge Publication (`i=0`)**: `INSERT` begins adding a new element `E` (`id=1001`) and calls `HnswUpdateNeighborsOnDisk`, skipping the check for existing connections. It writes its first bridge edge (`i=0`) to a neighboring node on disk. At this moment, element `E` becomes globally reachable via graph traversal.
2. **`VACUUM` Discovery & Insertion**: `VACUUM` Phase 2 (`RepairGraphElement`) scans the graph around a deleted tuple, discovers element `E` via the newly published bridge edge, and inserts `E` into adjacent nodes' neighbor arrays while actively checking for existing connections. `VACUUM` finishes Phase 2.
3. **`INSERT` Blind Write Overwrite (`i=1`)**: `INSERT` resumes updating its remaining neighbor candidates (`i=1`). Because `INSERT` continues to skip the existence check (blind write), it inserts element `E` a second time into those exact same neighboring nodes, creating duplicate neighbor entries on disk.
## Fix
To prevent `INSERT` from blindly overwriting neighbor connections that a concurrent `VACUUM` might have already added, the `checkExisting` flag has been removed entirely so that the existence check is always enforced.
By making the `ConnectionExists` check unconditional in `UpdateNeighborOnDisk`, the concurrency bug is cleanly eliminated. This ensures that `INSERT` always verifies whether a connection already exists before writing it to the neighbor array, closing the algorithmic asymmetry with `VACUUM`.
### Performance Impact
The performance impact on `INSERT` workloads is negligible. The added check introduces zero extra disk I/O because the target neighbor page is already loaded and locked in memory before the update occurs. The only overhead is purely CPU-bound scan of the neighbor array, which takes negligible time since its size is strictly bounded by the index parameter `m` (typically 16 to 100).
## Verification
* **Before Fix:** Running the reproduction script with page inspect gives `duplicate_neighbors > 0`.
* **After Fix:** Removing the `checkExisting` bypass eliminates the race condition, causing the script to complete with `duplicate_neighbors = 0`.
inline patch 1: src/hnsw.h, src/hnswinsert.c, src/hnswvacuum.c (+7/-7 lines) download inline-1.patchdiff --git a/src/hnsw.h b/src/hnsw.hindex 1f25cc297..a587fd1f8 100644--- a/src/hnsw.h+++ b/src/hnsw.h@@ -476,7 +476,7 @@ void HnswAddHeapTid(HnswElement element, ItemPointer heaptid);
HnswNeighborArray *HnswInitNeighborArray(int lm, HnswAllocator * allocator);
void HnswInitNeighbors(char *base, HnswElement element, int m, HnswAllocator * alloc);
bool HnswInsertTupleOnDisk(Relation index, HnswSupport * support, Datum value, ItemPointer heaptid, bool building);
-void HnswUpdateNeighborsOnDisk(Relation index, HnswSupport * support, HnswElement e, int m, bool checkExisting, bool building);+void HnswUpdateNeighborsOnDisk(Relation index, HnswSupport * support, HnswElement e, int m, bool building);
void HnswLoadElementFromTuple(HnswElement element, HnswElementTuple etup, bool loadHeaptids, bool loadVec);
void HnswLoadElement(HnswElement element, double *distance, HnswQuery * q, Relation index, HnswSupport * support, bool loadVec, double *maxDistance);
bool HnswFormIndexValue(Datum *out, Datum *values, bool *isnull, const HnswTypeInfo * typeInfo, HnswSupport * support);
diff --git a/src/hnswinsert.c b/src/hnswinsert.cindex 08ff27e42..616de35c6 100644--- a/src/hnswinsert.c+++ b/src/hnswinsert.c@@ -471,7 +471,7 @@ ConnectionExists(HnswElement e, HnswNeighborTuple ntup, int startIdx, int lm)
* Update neighbor
*/
static void
-UpdateNeighborOnDisk(HnswElement element, HnswElement newElement, int idx, int m, int lm, int lc, Relation index, bool checkExisting, bool building)+UpdateNeighborOnDisk(HnswElement element, HnswElement newElement, int idx, int m, int lm, int lc, Relation index, bool building)
{
Buffer buf;
Page page;
@@ -501,7 +501,7 @@ UpdateNeighborOnDisk(HnswElement element, HnswElement newElement, int idx, int m
startIdx = (element->level - lc) * m;
/* Check for existing connection */
- if (checkExisting && ConnectionExists(newElement, ntup, startIdx, lm))+ if (ConnectionExists(newElement, ntup, startIdx, lm))
idx = -1;
else if (idx == -2)
{
@@ -543,7 +543,7 @@ UpdateNeighborOnDisk(HnswElement element, HnswElement newElement, int idx, int m
* Update neighbors
*/
void
-HnswUpdateNeighborsOnDisk(Relation index, HnswSupport * support, HnswElement e, int m, bool checkExisting, bool building)+HnswUpdateNeighborsOnDisk(Relation index, HnswSupport * support, HnswElement e, int m, bool building)
{
char *base = NULL;
@@ -572,7 +572,7 @@ HnswUpdateNeighborsOnDisk(Relation index, HnswSupport * support, HnswElement e,
if (idx == -1)
continue;
- UpdateNeighborOnDisk(neighborElement, e, idx, m, lm, lc, index, checkExisting, building);+ UpdateNeighborOnDisk(neighborElement, e, idx, m, lm, lc, index, building);
}
}
@@ -682,7 +682,7 @@ UpdateGraphOnDisk(Relation index, HnswSupport * support, HnswElement element, in
HnswUpdateMetaPage(index, 0, NULL, newInsertPage, MAIN_FORKNUM, building);
/* Update neighbors */
- HnswUpdateNeighborsOnDisk(index, support, element, m, false, building);+ HnswUpdateNeighborsOnDisk(index, support, element, m, building);
/* Update entry point if needed */
if (entryPoint == NULL || element->level > entryPoint->level)
diff --git a/src/hnswvacuum.c b/src/hnswvacuum.cindex 88905db4a..ad44364a0 100644--- a/src/hnswvacuum.c+++ b/src/hnswvacuum.c@@ -270,7 +270,7 @@ RepairGraphElement(HnswVacuumState * vacuumstate, HnswElement element, HnswEleme
UnlockReleaseBuffer(buf);
/* Update neighbors */
- HnswUpdateNeighborsOnDisk(index, support, element, m, true, false);+ HnswUpdateNeighborsOnDisk(index, support, element, m, false);
}
/*