Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions les/utils/weighted_select.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,13 @@ func (w *WeightedRandomSelect) Choose() WrsItem {
if w.root.sumWeight == 0 {
return nil
}
val := uint64(rand.Int63n(int64(w.root.sumWeight)))
val := rand.Uint64() % w.root.sumWeight
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please check the L92, it has the same issue.

The suggested change:

if weight >= lastWeight || rand.Uint64() % lastWeight < weight {
	return choice
}

choice, lastWeight := w.root.choose(val)
weight := w.wfn(choice)
if weight != lastWeight {
w.setWeight(choice, weight)
}
if weight >= lastWeight || uint64(rand.Int63n(int64(lastWeight))) < weight {
if weight >= lastWeight || rand.Uint64()%lastWeight < weight {
return choice
}
}
Expand Down
14 changes: 14 additions & 0 deletions les/utils/weighted_select_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,17 @@ func TestWeightedRandomSelect(t *testing.T) {
testFn(100000)
testFn(1000000)
}

// TestOOB tests values which doesn't fit in int64
func TestOOB(t *testing.T) {
s := NewWeightedRandomSelect(func(i interface{}) uint64 {
// Dummy weight function to return a very large weight
return uint64(0xffffffffffffffff)
})
s.Update(testWrsItem{idx: 0, widx: nil})
// int64 conversion should make the sumweight negative
if int64(s.root.sumWeight) >= 0 {
t.Fatalf("test is dysfunctional, sumweight not negative: %d", int64(s.root.sumWeight))
}
s.Choose()
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// TestOOB tests values which doesn't fit in int64
func TestOOB(t *testing.T) {
	s := NewWeightedRandomSelect(func(i interface{}) uint64 {
		// Dummy weight function to return a very large weight
		return uint64(0xffffffffffffffff)
	})
	s.Update(testWrsItem{idx: 0, widx: nil})
	// int64 conversion should make the sumweight negative
	if int64(s.root.sumWeight) >= 0 {
		t.Fatalf("test is dysfunctional, sumweight not negative: %d", int64(s.root.sumWeight))
	}
	s.Choose()
}

This test can capture the very large single weight. For some cornercases.