hnsw icon indicating copy to clipboard operation
hnsw copied to clipboard

Panic will appear when running this demo.

Open jpc901 opened this issue 5 months ago • 2 comments

Panic will appear when running this demo.

package main

import (
	"math/rand"
	"sync"
	"time"

	"github.com/coder/hnsw"
)

var (
	idToEmb = map[int64][]float32{
		8832462: {0.16308737, -0.015082314, -0.13542788, 0.0050275815},
		8836285: {0.12513474, -0.01645081, -0.18823123, 0.0038108851},
		8833448: {0.12430125, -0.028154016, -0.16484132, -0.013979792},
		8835979: {0.11317906, -0.015129599, -0.081378885, 0.14409661},
		8833623: {0.047779884, -0.01809181, -0.11893867, -0.042758342},
		8836020: {0.16370028, -0.018596498, -0.13393748, -0.025386846},
		8833095: {0.13081397, -0.011383214, -0.043572865, 0.007917681},
		105126:  {0.087190986, -0.013881853, -0.16933066, 0.09613177},
	}
)

func test2() {
	g := &hnsw.Graph[int64]{
		Distance: hnsw.CosineDistance,
		Rng:      rand.New(rand.NewSource(time.Now().UnixNano())),
		M:        32,
		Ml:       0.28,
		EfSearch: 300,
	}
	wg := sync.WaitGroup{}
	mtx := sync.Mutex{}
	for id, emb := range idToEmb {
		wg.Add(1)
		go func(id int64, emb []float32) {
			mtx.Lock()
			g.Add(hnsw.MakeNode(id, emb))
			mtx.Unlock()
			wg.Done()
		}(id, emb)
	}
	wg.Wait()

	for id, emb := range idToEmb {
		g.Add(hnsw.MakeNode(id, emb))
	}

}

func main() {
	test2()
}

There should be something wrong here.

if elevator != nil {
	searchPoint = layer.nodes[*elevator]
}

jpc901 avatar Aug 27 '25 06:08 jpc901

The elevator has not been cleaned up. Adding a duplicate key will probably cause this problem.

jpc901 avatar Aug 27 '25 06:08 jpc901

Thanks for identifying. I don't have time to fix the issue but welcome a tested PR.

ammario avatar Sep 03 '25 16:09 ammario